使用Nlog记录日志到数据库

Nlog是一个很不错的.NET日志记录组件,它可以将日志输出到控件台,保存到文本,也可以很方便的记录到数据库中。

可以在这里下载Nlog:http://nlog-project.org/

这里分享一下如何配置Nlog,可以使其日志记录到数据库中(这里我用的是SQL server 2008).

新建一个控件台项目:NlogSample,再通过NuGet加入Nlog程序集,如果没有装NuGet也可以在Nlog官网上下载,如图:

安装好以后,在项目中就有了Nlog程序集和Nlog.config文件

打开Nlog.config文件,在target节点中,增加对数据库的配置。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<target type="Database" name="database" connectionstring="Data Source=.;Initial Catalog=ReportServerTempDB;Integrated Security=True">
      <commandText>
        insert into MyLog ([CreateDate], [Origin], [LogLevel], [Message], [StackTrace])
        values (@createDate, @origin, @logLevel, @message, @stackTrace);
      </commandText>
      <parameter name="@createDate" layout="${longdate}"/>
      <!--日志发生时间-->
      <parameter name="@origin" layout="${callsite}"/>
      <!--日志来源-->
      <parameter name="@logLevel" layout="${level}"/>
      <!--日志等级-->
      <parameter name="@message" layout="${message}"/>
      <!--日志信息-->
      <parameter name="@stackTrace" layout="${stacktrace}"/>
      <!--堆栈信息-->
</target>

  其中:connectionstring是数据库连接串,commandText是插入的SQL语句,parameter 是参数信息。当然在记录之前我们要先在数据库中建好相应的表。
在Nlog.config中的rule中增加日志记录规则

1
2
3
4
5
6
7
<rules>
    <!-- add your logging rules here -->
    <logger name="*" writeTo="database"/>
    <!--
    <logger name="*" minlevel="Trace" writeTo="f" />
    -->
 </rules>

  这样,我们的Nlog.config就设置好了。在Main方法中写几句代码测试一下: 

1
2
3
4
5
6
7
8
class Program
  {
      private static Logger logger = LogManager.GetCurrentClassLogger();
      static void Main(string[] args)
      {
          logger.Fatal("发生致命错误");
      }
  }

  执行成功,数据库中已经增加一条日志记录了

1
2
LigID    CreateDate    Origin    LogLevel    Message    Exception    StackTrace
20    2012-10-18 15:49:16.4114    NlogSample.Program.Main    Fatal    发生致命错误    NULL    <br>AppDomain.ExecuteAssembly => AppDomain._nExecuteAssembly => Program.Main

  我们也可以将日志等级比较低的记录到文本,只将比较严重的日志记录到数据库中,相应的Nlog.config如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
<?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"
      throwExceptions="true" internalLogFile="c:\nlog.txt" internalLogLevel="Debug">
 
  <!--
  See http://nlog-project.org/wiki/Configuration_file
  for information on customizing logging rules and outputs.
   -->
  <!--<nlog throwExceptions="true" internalLogFile="c:\nlog.txt" internalLogLevel="Debug" />-->
  <targets>
    <!-- add your targets here -->
    <target name="file" xsi:type="File" fileName="${basedir}/logs/Log ${shortdate}.txt" layout="${longdate} ${callsite} ${level}: ${message} ${event-context:item=exception} ${stacktrace}" />
    <target type="Database" name="database" connectionstring="Data Source=.;Initial Catalog=ReportServerTempDB;Integrated Security=True">
      <commandText>
        insert into MyLog ([CreateDate], [Origin], [LogLevel], [Message], [StackTrace]) values (@createDate, @origin, @logLevel, @message, @stackTrace);
      </commandText>
      <parameter name="@createDate" layout="${longdate}"/><!--日志发生时间-->
      <parameter name="@origin" layout="${callsite}"/><!--日志发生时间-->
      <parameter name="@logLevel" layout="${level}"/><!--日志等级-->
      <parameter name="@message" layout="${message}"/><!--日志信息-->
      <parameter name="@stackTrace" layout="${stacktrace}"/><!--日志发生时间-->
    </target>
    <!--
    <target xsi:type="File" name="f" fileName="${basedir}/logs/${shortdate}.log"
            layout="${longdate} ${uppercase:${level}} ${message}" />
    -->
  </targets>
 
  <rules>
    <!-- add your logging rules here -->
    <logger name="*"  writeTo="file"/>
    <logger name="*" minlevel="Error" appendTo="database"/>
    <!--
    <logger name="*" minlevel="Trace" writeTo="f" />
    -->
  </rules>
</nlog>

    在根结点上设置:throwExceptions="true" internalLogFile="c:\nlog.txt" internalLogLevel="Debug" ,可以让我们看到Nlog的内部错误,对调试有很大的帮助。

这里也许有人要问,上面日志表中的参数${longdate},${level} 等都是Nlog内部恰好有提供的,要是我要记录的信息Nlog没有怎么办?没问题,我们完全可以自己定义日志

表的数据结构。

重新配置Nlog.Config如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
<?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"
      throwExceptions="true" internalLogFile="c:\nlog1.txt" internalLogLevel="Debug">
 
  <!--
  See http://nlog-project.org/wiki/Configuration_file
  for information on customizing logging rules and outputs.
   -->
  <targets>
    <!-- add your targets here -->
    <target name="file" xsi:type="File" fileName="D:\ProcLogs/${event-context:item=appName}/${event-context:item=moduleName}/${event-context:item=procName}/${event-context:item=logTitle}/${shortdate}-${level}.txt"
            layout="${longdate} ${level}:${event-context:item=logMessage}" />
    <target name="fi" xsi:type="File" fileName="${basedir}/logs/Log ${shortdate}.txt"
           layout="${longdate} ${level}:${message} ${stacktrace}" />
    <target type="Database" name="database" connectionstring="Data Source=.;Initial Catalog=ReportServerTempDB;Integrated Security=True">
      <commandText>
        insert into DevLog ([AppName],[ModuleName],[ProcName],[LogLevel],[LogTitle],[LogMessage],[LogDate],[StackTrace]) values (@appName, @moduleName, @procName, @logLevel, @logTitle, @logMessage,@logDate,@stackTrace);
      </commandText>
      <parameter name="@appName" layout="${event-context:item=appName}"/>
      <parameter name="@moduleName" layout="${event-context:item=moduleName}"/>
      <parameter name="@procName" layout="${event-context:item=procName}"/>
      <parameter name="@logLevel" layout="${event-context:item=logLevel}"/>
      <parameter name="@logTitle" layout="${event-context:item=logTitle}"/>
      <parameter name="@logMessage" layout="${event-context:item=logMessage}"/>
      <parameter name="@logDate" layout="${longdate}"/>
      <parameter name="@stackTrace" layout="${stacktrace}"/>
    </target>
    <!--
    <target xsi:type="File" name="f" fileName="${basedir}/logs/${shortdate}.log"
            layout="${longdate} ${uppercase:${level}} ${message}" />
    -->
  </targets>
 
  <rules>
    <!-- add your logging rules here -->
    <logger name="Log"  writeTo="file"/>
    <logger name="L"  writeTo="fi"/>
    <!--<logger name="Log" minlevel="Info" appendTo="database"/>-->
    <!--
    <logger name="*" minlevel="Trace" writeTo="f" />
    -->
  </rules>
</nlog>

  类似<parameter name="@appName" layout="${event-context:item=appName}"/> ,我们就可以定义自己的参数。

然后在写日志的时候,可以通过LogEventInfo 类给我们的参数赋值,代码如下:

1
2
3
4
5
6
7
8
9
10
11
void WriteLog(LogLevel levle, string appName, string moduleName, string procName, string logLevel, string logTitle, string logMessage)
 {
         LogEventInfo ei = new LogEventInfo(levle, "", "");
         ei.Properties["appName"] = appName;
         ei.Properties["moduleName"] = moduleName;
         ei.Properties["procName"] = procName;
         ei.Properties["logLevel"] = logLevel.ToUpper();
         ei.Properties["logTitle"] = logTitle;
         ei.Properties["logMessage"] = logMessage;
         logger.Log(ei);
 }

 注意,设置数据库时,时间要为字符串类型。

posted @   每天进步多一点  阅读(1441)  评论(0编辑  收藏  举报
编辑推荐:
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· [.NET]调用本地 Deepseek 模型
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· .NET Core 托管堆内存泄露/CPU异常的常见思路
· PostgreSQL 和 SQL Server 在统计信息维护中的关键差异
阅读排行:
· DeepSeek “源神”启动!「GitHub 热点速览」
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· C# 集成 DeepSeek 模型实现 AI 私有化(本地部署与 API 调用教程)
· DeepSeek R1 简明指南:架构、训练、本地部署及硬件要求
· 2 本地部署DeepSeek模型构建本地知识库+联网搜索详细步骤
点击右上角即可分享
微信分享提示