原文地址:http://dotnet.9sssd.com/csbase/art/793

[摘要]Nlog是一个很不错的.NET日志记录组件,它可以将日志输出到控件台,保存到文本,也可以很方便的记录到数据库中。本文为你介绍C# 使用Nlog记录日志到数据库。

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

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

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

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

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

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

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

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

在Nlog.config中的rule中增加日志记录规则:

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

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

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

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

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

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

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

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

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

重新配置Nlog.Config如下:

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

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

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

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

C# 使用Nlog记录日志到数据库 使用LogEventInfo类获取,命名空间名称、类名、方法名的更多相关文章

  1. [转]C# 使用Nlog记录日志到数据库

    本文转自:http://www.cnblogs.com/weixing/archive/2013/04/26/3044422.html 摘要]Nlog是一个很不错的.NET日志记录组件,它可以将日志输 ...

  2. C# 使用Nlog记录日志到数据库

    [摘要]Nlog是一个很不错的.NET日志记录组件,它可以将日志输出到控件台,保存到文本,也可以很方便的记录到数据库中.本文为你介绍C# 使用Nlog记录日志到数据库. Nlog是一个很不错的.NET ...

  3. 转:使用Nlog记录日志到数据库

    原文:http://www.cnblogs.com/Gyoung/archive/2012/10/18/2729613.html Nlog是一个很不错的.NET日志记录组件,它可以将日志输出到控件台, ...

  4. 使用Nlog记录日志到数据库

    Nlog是一个很不错的.NET日志记录组件,它可以将日志输出到控件台,保存到文本,也可以很方便的记录到数据库中. 可以在这里下载Nlog:http://nlog-project.org/ 这里分享一下 ...

  5. 从零开始搭建前后端分离的NetCore2.2(EF Core CodeFirst+Autofac)+Vue的项目框架之四Nlog记录日志至数据库

    为什么要进行日志记录呢?为什么要存至数据库呢?只能说日志记录是每个系统都应当有的. 好的日志记录方式可以提供我们足够多定位问题的依据.查找系统或软件或项目的错误或异常记录.程序在运行时就像一个机器人, ...

  6. .Net Core 使用NLog记录日志到文件和数据库

    NLog 记录日志是微软官方推荐使用. 接下来,通过配置日志记录到文件和Sql Server数据库. 第一步:首先添加包NLog.Config (可通过微软添加包命令Install-Package 包 ...

  7. Asp.Net Core中使用NLog记录日志

    2019/10/28, Asp.Net Core 3.0, NLog 4.6.7, NLog.Web.AspNetCore 4.9.0 摘要:NLog在asp.net网站中的使用,NLog日志写入数据 ...

  8. EF+LINQ事物处理 C# 使用NLog记录日志入门操作 ASP.NET MVC多语言 仿微软网站效果(转) 详解C#特性和反射(一) c# API接受图片文件以Base64格式上传图片 .NET读取json数据并绑定到对象

    EF+LINQ事物处理   在使用EF的情况下,怎么进行事务的处理,来减少数据操作时的失误,比如重复插入数据等等这些问题,这都是经常会遇到的一些问题 但是如果是我有多个站点,然后存在同类型的角色去操作 ...

  9. .NET中使用NLog记录日志

    以前小编记录日志使用的是Log4Net,虽然好用但和NLog比起来稍显复杂.下面小编就和大伙分享一下NLog的使用方式. 引用NLog.Config 在使用NLog之前,我们要首先添加对NLog.Co ...

随机推荐

  1. sql - union all

    我的 表1中有字段([c],[num]), 记录诸如: [c] [num] 0   188 1   167 2   373 3   378 4   377 表二也有同样的字段,记录有的id不同, 请问 ...

  2. SQL Server T-SQL高级查询【转】

    高级查询在数据库中用得是最频繁的,也是应用最广泛的. Ø 基本常用查询 --select select * from student;   --all 查询所有 select all sex from ...

  3. JS异步阻塞的迷思

    还是百度前端技术学院的“任务十九”可视化排序算法的题,在写出快速排序算法之后,要求用动画的形式把这个排序过程呈现出来.排序过程在CPU里不过是瞬间的事,但要转换成“缓慢的”动画效果给人类看,就不得不把 ...

  4. Java中报错No enclosing instance of type caiquan is accessible. Must qualify the allocation with an enclosing instance of type caiquan (e.g. x.new A() where x is an instance of caiquan).

    package test;import java.util.Scanner;import java.util.Random;public class caiquan { public static v ...

  5. SVM对偶形式

    dual svm 对偶SVM linear SVM 可以用二次规划方法解 xn通过非线性转换变成zn SVM配合非线性特征转换 透过large-margin降低模型复杂度 透过特征转换得到弯弯曲曲的边 ...

  6. 图像处理简单实例[OpenCV 笔记1]

    几个入门的简单程序,和对应的CMakeList, 虽然简单重新测一下写一下也是好的. CMake教程传送门 图像显示 ShowImage.cxx #include <opencv2/opencv ...

  7. nullptr和NULL 区别

    注:本文内容摘自网络,准确性有待验证,现阶段仅供学习参考.尊重作品作者成果,原文链接 :http://www.2cto.com/kf/201302/190008.html 1.为什要有nullptr ...

  8. Fedora 21 设置开机启动脚本

    sudo touch /etc/rc.d/rc.localsudo vim /etc/rc.d/rc.local 在/etc/rc.d/rc.local文件中写入, 然后使用:wq命令 保存并退出. ...

  9. 从一个标准 url 里取出文件的扩展名

    在php预定义函数中有一个叫做"pathinfo()"的函数,专门用于返回文件路径信息的. 那好,我们就来看一下它能为我们做些什么?       语法:pathinfo($url_ ...

  10. Bluestacks 安卓模拟器利器

    蓝手指测试安卓比较给力,尤其含有安卓原生态的多语言是现在厂商手机所无法提供了的.   但是有一点需要注意:BlueStack的日志文件非常大,日志目录默认是%Sysem Dir%/Program Da ...