简体   繁体   English

NLog 正在写入文件但未写入数据库表

[英]NLog is writing to file but not to database table

This is my NLog.config file:这是我的 NLog.config 文件:

<?xml version="1.0" encoding="utf-8" ?>
    <nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:schemaLocation="http://www.nlog-project.org/schemas/NLog.xsd NLog.xsd"
          autoReload="true"
          throwExceptions="false"
          internalLogLevel="Off" internalLogFile="c:\temp\nlog-internal.log" >

      <variable name="myvar" value="myvalue"/>

      <targets>

        <target name="database" xsi:type="Database"
                dbUserName="internwebuser"
                dbProvider="System.Data.SqlClient"
                connectionStringName="SECURE"
                connectionString="Data Source=sqlservtest.starledger.com;Initial Catalog=SECURE;User ID=webuser;Password=password"
                commandText="insert into dbo.tracelog (custom_message, excep_message, insertdate) 
                values 
                (@custom_message, @excep_message, @insertdate);" >


          <parameter name="@custom_message"     layout="${exception}" />
          <parameter name="@excep_message"      layout="${exception:tostring}" />
          <parameter name="@insertdate"         layout="${date}" />


        </target>


        <target name="file" xsi:type="File"
                layout="${longdate} ${uppercase:${level}} ${callsite} from Line: ${callsite-linenumber} ${newline} 
    ${exception} ${newline}
    ${exception:tostring} ${newline}"
                fileName="${basedir}/logs/${shortdate}-${level}.log" />


      </targets>  

      <rules>

        <logger name="*" minlevel="Debug" writeTo="file" />
        <logger name="*" minlevel="Debug" writeTo="database" />

      </rules>
    </nlog>

And my controller looks something like this:我的控制器看起来像这样:

public class ReportController : Controller
{
    private static Logger logger = LogManager.GetCurrentClassLogger();

    public ActionResult Index()
    {
        try 
        {
            <!-- some statement -->
        }
        catch (Exception e)
        {
            logger.Error(e);
        }
        return View();
   }
}

This code writes perfectly into the file but the database table remains empty.此代码完美地写入文件,但数据库表保持为空。 Also, in my file, when I do it using StreamWriter and create a file instead of using NLog, the application writes 2/3 kinds of error into the file simultaneously.此外,在我的文件中,当我使用StreamWriter创建文件而不是使用 NLog 时,应用程序同时将 2/3 种错误写入文件。 But NLog only writes the last error.但是 NLog 只写了最后一个错误。

For example:例如:

In case of StreamWriter , the errors are:StreamWriter情况下,错误是:

Exception Name:ExecuteReader requires an open and available Connection. The connection's current state is closed.

Exception Name:Object reference not set to an instance of an object.

But In case of NLog, I only get:但在 NLog 的情况下,我只会得到:

Exception Name:Object reference not set to an instance of an object.
and the first one is missed out.

My StreamWriter method looks like this:我的StreamWriter方法如下所示:

DateTime today = DateTime.Now;

            string path = Directory.GetCurrentDirectory();

            string fileName = "error-log-" + today.Date.ToString("MM-dd-yyyy") + ".txt";

            var file = Path.Combine(path, fileName);

            StreamWriter log;

            if (!File.Exists(file))
            {
                log = new StreamWriter(file);
            }

            else
            {
                log = File.AppendText(file);
            }

            // Write to the file:

            log.WriteLine("Data Time:" + DateTime.Now);    
            log.WriteLine("Exception Name:" + sExceptionName);    
            log.WriteLine("Event Name:" + sEventName);    
            log.WriteLine("Error Line No.:" + nErrorLineNo);    

            // Close the stream:

            log.Close();

and I pass the method into the catch section of my controller.然后我将该方法传递到控制器的catch部分。

My main issue here is writing into the database table, although I'd appreciate help in writing all the errors too, using Nlog, instead of just the last one.我在这里的主要问题是写入数据库表,尽管我也很感激使用 Nlog 编写所有错误的帮助,而不仅仅是最后一个。

请启用内部日志记录以获取更多信息

I faced the same issue.To find the exact issue I added <nlog internalLogFile="c:\\DemoLogs\\nlog-internal.txt" and internalLogLevel="Error"> inside the nlog tag.我遇到了同样的问题。为了找到确切的问题,我在 nlog 标签中添加了<nlog internalLogFile="c:\\DemoLogs\\nlog-internal.txt" and internalLogLevel="Error"> which will write the exact proplem to the log file这会将确切的proplem写入日志文件

For my case Could not load file or assembly 'System.Data.SqlClient was resolved when I installed that nuget package.对于我的情况, Could not load file or assembly 'System.Data.SqlClient在我安装该 nuget 包时已解决。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM