原文地址:http://www.cnblogs.com/sorex/archive/2013/01/31/2887174.html

--------------------------------------------------------------------------------------------

每条跟踪信息都包含一个记录等级(log level)信息,用来描述该条信息的重要性。NLog支持如下几种记录等级:

  1. Trace - 最常见的记录信息,一般用于普通输出
  2. Debug - 同样是记录信息,不过出现的频率要比Trace少一些,一般用来调试程序
  3. Info - 信息类型的消息
  4. Warn - 警告信息,一般用于比较重要的场合
  5. Error - 错误信息
  6. Fatal - 致命异常信息。一般来讲,发生致命异常之后程序将无法继续执行。

--------------------------------------------------------------------------------------------

之前一直都是使用log4net,但是那令人生畏的维护速度,还是令我转向了NLog。首先我不确定各版本的差异,所以这里仅仅以我用的版本来写。其次,本文以基本应用为基准,不涉及复杂的配置方案。

本文地址http://www.cnblogs.com/sorex/archive/2013/01/31/2887174.html

O、情景(设想情景,各位请按自己需求进行变更)

1.在Logs文件夹下,分日期文件夹记录每日的错误信息。

2.在日期文件夹下,有All.log记录全部错误信息以及UI.log、BLL.log、DAL.log三个日志文件分别记录错误信息。

3.同时在一个单独的MySQL数据库ProjectLogDB中的Logs表中记录错误信息。

4.错误信息包含发生错误的时间、错误级别、堆栈信息、发生错误的方法、源文件路径及行号、错误内容、错误分类(UI、BLL、DAL)。

ok就是上面这些设定,没有其他的神马了。

一、在项目中加入NLog的引用

打开NuGet搜索NLog安装下面的4个

安装完成后会在项目中出现如下2个文件

二、设置日志记录

1.打开NLog.config文件,首先我们搞的All.log

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
<?xml version="1.0" encoding="utf-8" ?>
    <!-- 定义参数:
    ${basedir}:系统路径
    ${shortdate}:短日期 yyyy-MM-dd(例:2013-01-31)
    ${basedir}/Logs/${shortdate}:即为在系统路径下的Logs文件夹下面的日期文件夹-->
    <variable name="logDirectory" value="${basedir}/Logs/${shortdate}"/>
    <targets>
        <!-- 定义输出模板:
        type="File":这个记录方式为文件类型
        fileName="${logDirectory}/All.log":表示输出到文件All.log中
        layout="...":输出文件中错误的显示格式
        ${logDirectory}:为上述定义的路径
        ${longdate}:输出长日期 yyyy-MM-dd HH:mm:ss.ffff(例:2013-01-31 14:49:21.2120)
        ${level}:错误等级(由低到高为Trace,Debug,Info,Warn,Error,Fatal)
        ${newline}:输出 新的一行
        ${stacktrace}:输出 堆栈信息
        ${callsite:className=True:fileName=True:includeSourcePath=True:methodName=True}:输出 命名空间.类名.方法名(文件路径:行号)
        ${message}:输出错误信息-->
        <target xsi:type="File" name="AllFile" fileName="${logDirectory}/All.log"
                layout="${longdate}        ■${level}${newline}    ▲${stacktrace}${newline}    ◇${callsite:className=True:fileName=True:includeSourcePath=True:methodName=True}${newline}    ◆${message}${newline}${newline}***************************************************************************" />
    </targets>
    <rules>
        <!-- 定义输出日志:
        name="*":记录所有信息
        minlevel="Trace":记录的最低错误级别为Trace
        writeTo="AllFile":日志写入AllFile的target中-->
        <logger name="*" minlevel="Trace" writeTo="AllFile" />
    </rules>
</nlog>

2.将上面的AllFile的target复制3次修改名字为UI、BLL、DAL,添加相应的logger如下代码

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
45
<?xml version="1.0" encoding="utf-8" ?>
    <!-- 定义参数:
    ${basedir}:系统路径
    ${shortdate}:短日期 yyyy-MM-dd(例:2013-01-31)
    ${basedir}/Logs/${shortdate}:即为在系统路径下的Logs文件夹下面的日期文件夹-->
    <variable name="logDirectory" value="${basedir}/Logs/${shortdate}"/>
    <targets>
        <!-- 定义输出模板:
        type="File":这个记录方式为文件类型
        fileName="${logDirectory}/All.log":表示输出到文件All.log中
        layout="...":输出文件中错误的显示格式
        ${logDirectory}:为上述定义的路径
        ${longdate}:输出长日期 yyyy-MM-dd HH:mm:ss.ffff(例:2013-01-31 14:49:21.2120)
        ${level}:错误等级(由低到高为Trace,Debug,Info,Warn,Error,Fatal)
        ${newline}:输出 新的一行
        ${stacktrace}:输出 堆栈信息
        ${callsite:className=True:fileName=True:includeSourcePath=True:methodName=True}:输出 命名空间.类名.方法名(文件路径:行号)
        ${message}:输出错误信息-->
        <target xsi:type="File" name="AllFile" fileName="${logDirectory}/All.log"
                layout="${longdate}        ■${level}${newline}    ▲${stacktrace}${newline}    ◇${callsite:className=True:fileName=True:includeSourcePath=True:methodName=True}${newline}    ◆${message}${newline}${newline}***************************************************************************" />
 
        <target xsi:type="File" name="UI" fileName="${logDirectory}/UI.log"
            layout="${longdate}        ■${level}${newline}    ▲${stacktrace}${newline}    ◇${callsite:className=True:fileName=True:includeSourcePath=True:methodName=True}${newline}    ◆${message}${newline}${newline}***************************************************************************" />
 
        <target xsi:type="File" name="BLL" fileName="${logDirectory}/BLL.log"
            layout="${longdate}        ■${level}${newline}    ▲${stacktrace}${newline}    ◇${callsite:className=True:fileName=True:includeSourcePath=True:methodName=True}${newline}    ◆${message}${newline}${newline}***************************************************************************" />
 
        <target xsi:type="File" name="DAL" fileName="${logDirectory}/DAL.log"
            layout="${longdate}        ■${level}${newline}    ▲${stacktrace}${newline}    ◇${callsite:className=True:fileName=True:includeSourcePath=True:methodName=True}${newline}    ◆${message}${newline}${newline}***************************************************************************" />
    </targets>
    <rules>
        <!-- 定义输出日志:
        name="*":记录所有信息
        minlevel="Trace":记录的最低错误级别为Trace
        writeTo="AllFile":日志写入AllFile的target中-->
        <logger name="*" minlevel="Trace" writeTo="AllFile" />
        <!-- 定义输出日志:
        name="*.UI.*":记录包含.UI.的命名空间的所有信息(第一个*最好替换为固定的,例如我的UI层命名空间为J.UI那么这里就可以写J.UI.*)-->
        <logger name="*.UI.*" minlevel="Trace" writeTo="UI" />
        <logger name="*.BLL.*" minlevel="Trace" writeTo="BLL" />
        <logger name="*.DAL.*" minlevel="Trace" writeTo="DAL" />
    </rules>
</nlog>

3.到这里我们创建一个Class1来测试下,文件内容如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
using NLog;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace J.BLL
{
    public class Class1
    {
        private static Logger logger = LogManager.GetCurrentClassLogger();
 
        public void Test()
        {
            logger.Log(LogLevel.Debug, "this is at BLL Error");
        }
    }
}

4.我们得到的错误信息如下

1
2
3
4
5
6
2013-01-31 14:49:21.3590        ■Debug
    ▲<no type>.lambda_method => HomeController.Index => Class1.Test
    ◇J.BLL.Class1.Test(d:\ProjectTest\J.BLL\Class1.cs:16)
    ◆this is at BLL Error
 
***************************************************************************

5.输出到文件目前没有问题了,下面就来配置如何连接到MySQL,首先在ProjectLogDB中创建表Logs

1
2
3
4
5
6
7
8
9
10
11
12
13
-- ----------------------------
-- Table structure for `Logs`
-- ----------------------------
DROP TABLE IF EXISTS `Logs`;
CREATE TABLE `Logs` (
  `ID` int(11) NOT NULL AUTO_INCREMENT,
  `CreateDate` datetime NOT NULL,
  `LogLevel` varchar(5) NOT NULL,
  `CallSite` varchar(5000) DEFAULT NULL,
  `Massage` longtext,
  `StackTrace` varchar(5000) DEFAULT NULL,
  PRIMARY KEY (`ID`)
) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8;

6.修改NLog的配置文件如下

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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
<?xml version="1.0" encoding="utf-8" ?>
    <!-- 定义参数:
    ${basedir}:系统路径
    ${shortdate}:短日期 yyyy-MM-dd(例:2013-01-31)
    ${basedir}/Logs/${shortdate}:即为在系统路径下的Logs文件夹下面的日期文件夹-->
    <variable name="logDirectory" value="${basedir}/Logs/${shortdate}"/>
    <targets>
        <!-- 定义输出模板:
        type="File":这个记录方式为文件类型
        fileName="${logDirectory}/All.log":表示输出到文件All.log中
        layout="...":输出文件中错误的显示格式
        ${logDirectory}:为上述定义的路径
        ${longdate}:输出长日期 yyyy-MM-dd HH:mm:ss.ffff(例:2013-01-31 14:49:21.2120)
        ${level}:错误等级(由低到高为Trace,Debug,Info,Warn,Error,Fatal)
        ${newline}:输出 新的一行
        ${stacktrace}:输出 堆栈信息
        ${callsite:className=True:fileName=True:includeSourcePath=True:methodName=True}:输出 命名空间.类名.方法名(文件路径:行号)
        ${message}:输出错误信息-->
        <target xsi:type="File" name="AllFile" fileName="${logDirectory}/All.log"
                layout="${longdate}        ■${level}${newline}    ▲${stacktrace}${newline}    ◇${callsite:className=True:fileName=True:includeSourcePath=True:methodName=True}${newline}    ◆${message}${newline}${newline}***************************************************************************" />
 
        <target xsi:type="File" name="UI" fileName="${logDirectory}/UI.log"
            layout="${longdate}        ■${level}${newline}    ▲${stacktrace}${newline}    ◇${callsite:className=True:fileName=True:includeSourcePath=True:methodName=True}${newline}    ◆${message}${newline}${newline}***************************************************************************" />
 
        <target xsi:type="File" name="BLL" fileName="${logDirectory}/BLL.log"
            layout="${longdate}        ■${level}${newline}    ▲${stacktrace}${newline}    ◇${callsite:className=True:fileName=True:includeSourcePath=True:methodName=True}${newline}    ◆${message}${newline}${newline}***************************************************************************" />
 
        <target xsi:type="File" name="DAL" fileName="${logDirectory}/DAL.log"
            layout="${longdate}        ■${level}${newline}    ▲${stacktrace}${newline}    ◇${callsite:className=True:fileName=True:includeSourcePath=True:methodName=True}${newline}    ◆${message}${newline}${newline}***************************************************************************" />
 
        <!-- 定义输出到MySQL中:
        type="Database":这个记录方式是数据库
        dbProvider="MySql.Data.MySqlClient":使用MySQL的连接方式
        connectionString="Server=XXX.XXX.XXX.XXX;Database=ProjectLogDB;Uid=XXX;Pwd=XXX;":数据库的连接字符串
        commandText="insert into Logs(CreateDate,LogLevel,CallSite,Massage,StackTrace) values (@CreateDate,@LogLevel,@CallSite,@Massage,@StackTrace)":insert语句
        <parameter name="CreateDate" layout="${longdate}" />对应到insert语句的参数的值-->
        <target xsi:type="Database" name="AllDatabase" dbProvider="MySql.Data.MySqlClient"
                        connectionString="Server=XXX.XXX.XXX.XXX;Database=ProjectLogDB;Uid=XXX;Pwd=XXX;"
                        commandText="insert into Logs(CreateDate,LogLevel,CallSite,Massage,StackTrace) values (@CreateDate,@LogLevel,@CallSite,@Massage,@StackTrace)">
            <parameter name="CreateDate" layout="${longdate}" />
            <parameter name="LogLevel" layout="${level}" />
            <parameter name="CallSite" layout="${callsite:className=True:fileName=True:includeSourcePath=True:methodName=True}" />
            <parameter name="Massage" layout="${message}" />
            <parameter name="StackTrace" layout="${stacktrace}" />
        </target>
    </targets>
    <rules>
        <!-- 定义输出日志:
        name="*":记录所有信息
        minlevel="Trace":记录的最低错误级别为Trace
        writeTo="AllFile,AllDatabase":日志写入AllFile和AllDatabase的target中-->
        <logger name="*" minlevel="Trace" writeTo="AllFile,AllDatabase" />
        <!-- 定义输出日志:
        name="*.UI.*":记录包含.UI.的命名空间的所有信息(第一个*最好替换为固定的,例如我的UI层命名空间为J.UI那么这里就可以写J.UI.*)-->
        <logger name="*.UI.*" minlevel="Trace" writeTo="UI" />
        <logger name="*.BLL.*" minlevel="Trace" writeTo="BLL" />
        <logger name="*.DAL.*" minlevel="Trace" writeTo="DAL" />
    </rules>
</nlog>

7.完整的无说明的配置文件如下

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
<?xml version="1.0" encoding="utf-8" ?>
    <variable name="logDirectory" value="${basedir}/Logs/${shortdate}"/>
    <targets>
        <target xsi:type="File" name="AllFile" fileName="${logDirectory}/All.log"
            layout="${longdate}        ■${level}${newline}    ▲${stacktrace}${newline}    ◇${callsite:className=True:fileName=True:includeSourcePath=True:methodName=True}${newline}    ◆${message}${newline}${newline}***************************************************************************" />
 
        <target xsi:type="File" name="UI" fileName="${logDirectory}/UI.log"
            layout="${longdate}        ■${level}${newline}    ▲${stacktrace}${newline}    ◇${callsite:className=True:fileName=True:includeSourcePath=True:methodName=True}${newline}    ◆${message}${newline}${newline}***************************************************************************" />
 
        <target xsi:type="File" name="BLL" fileName="${logDirectory}/BLL.log"
            layout="${longdate}        ■${level}${newline}    ▲${stacktrace}${newline}    ◇${callsite:className=True:fileName=True:includeSourcePath=True:methodName=True}${newline}    ◆${message}${newline}${newline}***************************************************************************" />
 
        <target xsi:type="File" name="DAL" fileName="${logDirectory}/DAL.log"
            layout="${longdate}        ■${level}${newline}    ▲${stacktrace}${newline}    ◇${callsite:className=True:fileName=True:includeSourcePath=True:methodName=True}${newline}    ◆${message}${newline}${newline}***************************************************************************" />
 
        <target xsi:type="Database" name="AllDatabase" dbProvider="MySql.Data.MySqlClient"
                        connectionString="Server=XXX.XXX.XXX.XXX;Database=ProjectLogDB;Uid=XXX;Pwd=XXX;"
                        commandText="insert into Logs(CreateDate,LogLevel,CallSite,Massage,StackTrace) values (@CreateDate,@LogLevel,@CallSite,@Massage,@StackTrace)">
            <parameter name="CreateDate" layout="${longdate}" />
            <parameter name="LogLevel" layout="${level}" />
            <parameter name="CallSite" layout="${callsite:className=True:fileName=True:includeSourcePath=True:methodName=True}" />
            <parameter name="Massage" layout="${message}" />
            <parameter name="StackTrace" layout="${stacktrace}" />
        </target>
    </targets>
    <rules>
        <logger name="*" minlevel="Trace" writeTo="AllFile,AllDatabase" />
        <logger name="*.UI.*" minlevel="Trace" writeTo="UI" />
        <logger name="*.BLL.*" minlevel="Trace" writeTo="BLL" />
        <logger name="*.DAL.*" minlevel="Trace" writeTo="DAL" />
    </rules>
</nlog>

8.数据库中记录如下

三、总结

NLog其实也是一个用起来蛮简单的工具,复杂的功能请到官网查询,以上示例仅供日常使用。

NLog 2.0.0.2000 使用实例的更多相关文章

  1. [ActionScript 3.0] Away3D 官网实例

    /* Dynamic tree generation and placement in a night-time scene Demonstrates: How to create a height ...

  2. JAX-RS 2.0 REST客户端编程实例

    JAX-RS 2.0 REST客户端编程实例 2014/01/28 | 分类: 基础技术, 教程 | 0 条评论 | 标签: JAX-RS, RESTFUL 分享到:3 本文由 ImportNew - ...

  3. Asp.Net MVC2.0 Url 路由入门---实例篇

    本篇主要讲述Routing组件的作用,以及举几个实例来学习Asp.Net MVC2.0 Url路由技术. 接着上一篇开始讲,我们在Global.asax中注册一条路由后,我们的请求是怎么转到相应的Vi ...

  4. 《Drools7.0.0.Final规则引擎教程》第3章 3.1 Hello World 实例

    3.1 Hello World 实例 在上一章中介绍了Drools5x版本中规则引擎使用的实例,很明显在Drools7中KnowledgeBase类已经标注为"@Deprecated&quo ...

  5. NPOI2.2.0.0实例详解(十)—设置EXCEL单元格【文本格式】 NPOI 单元格 格式设为文本 HSSFDataFormat

    NPOI2.2.0.0实例详解(十)—设置EXCEL单元格[文本格式] 2015年12月10日 09:55:17 阅读数:3150 using System; using System.Collect ...

  6. Oracle 远程访问配置 在 Windows Forms 和 WPF 应用中使用 FontAwesome 图标 C#反序列化XML异常:在 XML文档(0, 0)中有一个错误“缺少根元素” C#[Win32&WinCE&WM]应用程序只能运行一个实例:MutexHelper Decimal类型截取保留N位小数向上取, Decimal类型截取保留N位小数并且不进行四舍五入操作

    Oracle 远程访问配置   服务端配置 如果不想自己写,可以通过 Net Manager 来配置. 以下配置文件中的 localhost 改为 ip 地址,否则,远程不能访问. 1.网络监听配置 ...

  7. yii2.0增删改查实例讲解

    yii2.0增删改查实例讲解一.创建数据库文件. 创建表 CREATE TABLE `resource` ( `id` int(10) NOT NULL AUTO_INCREMENT, `textur ...

  8. NPOI2.2.0.0实例详解(十一)—向EXCEL插入图片

    --------------------- 本文来自 天水宇 的CSDN 博客 ,全文地址请点击:https://blog.csdn.net/xxs77ch/article/details/50553 ...

  9. NPOI2.2.0.0实例详解(八)—设置EXCEL单元格【数字格式】

    using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.T ...

  10. [ActionScript 3.0] 动态绘制扇形实例(拖拽绘制)

    package { import flash.display.Shape; import flash.display.Sprite; import flash.events.MouseEvent; / ...

随机推荐

  1. 免费 Bootstrap 管理后台模块下载

    在这文章中我们将分享17+个最好的免费 Bootstrap 管理模板.你可以免费下载这些Twitter bootstrap 框架来开发网站后台. SB Admin 2 SB Admin is a fr ...

  2. hdu3415:最大k子段和,单调队列

    题目大意:给定长度为n的数组,求出最大的区间和,其中区间长度在[1,k]之间 分析: 学动态规划的时候我们会遇到一个经典问题 最大子段和,这个题跟最大子段和很类似 不同的是区间的长度有限制,无法用原算 ...

  3. hdu1573:数论,线性同余方程组

    题目大意: 给定一个N ,m 找到小于N的  对于i=1....m,满足  x mod ai=bi  的 x 的数量. 分析 先求出 同余方程组 的最小解x0,然后 每增加lcm(a1...,am)都 ...

  4. stardict词典(星际译王)

    sudo apt-get install stardict 下载词库: http://abloz.com/huzheng/stardict-dic/zh_CN/ 把下载的压缩包解压,以a为例cd /u ...

  5. MongoDB[mark]总忘记它们是干啥的

    MongoDB集群包括一定数量的mongod(分片存储数据).mongos(路由处理).config server(配置节点).clients(客户端).arbiter(仲裁节点:为了选举某个分片存储 ...

  6. Citrix 服务器虚拟化之十 Xenserver高可用性HA

    Citrix 服务器虚拟化之十 Xenserver高可用性HA HA是一套全自动功能设计,规划.它可以安全地恢复出现问题的XenServe 主机.例如物理破坏网络或主机的硬件故障,HA可确保无需任何人 ...

  7. Cortex-A9 PWM Timer

    PWM定时器        4412时钟为我们提供了PWM定时器,在4412中共有5个32位的定时器,这些定时器可发送中断信号给ARM子系统.另外,定时器0.1.2.3包含了脉冲宽度调制(PWM),并 ...

  8. My way on Linux - [Shell基础] - Bash Shell中判断文件、目录是否存在或者判断其是否具有某类属性(权限)的常用方法

    Conditional Logic on Files # 判断文件是否存在及文件类型 -a file exists. #文件存在 -b file exists and is a block speci ...

  9. 页面全屏显示JS代码

    1.直接在页面加载时就全屏. <body onload="window.open(document.location,'big','fullscreen=yes'):window.cl ...

  10. .net 4.0 面向对象编程漫谈基础篇读书笔记

    话说笔者接触.net 已有些年头,做过的项目也有不少,有几百万的,也有几十万的,有C/S的,也有B/S的.感觉几年下来,用过的框架不少,但是.net的精髓一直没有掌握.就像学武之人懂得各种招式,但内功 ...