前边我们解释了log4net的学习,我们再介绍一下NLog

一、什么是NLog

  NLog是一个基于.NET平台编写的类库,我们可以使用NLog在应用程序中添加极为完善的跟踪调试代码。NLog是一个简单灵活的.NET日志记录类库。

  通过使用NLog,我们可以在任何一种.NET语言中输出带有上下文的(contextual information)调试诊断信息,根据喜好配置其表现样式之后发送到一个或多个输出目标(target)中。

  NLog遵从BSD license,即允许商业应用且完全开放源代码。任何人都可以免费使用并对其进行测试,然后通过邮件列表反馈问题以及建议。
  NLog支持.NET、C/C++以及COM interop API,因此我们的程序、组件、包括用C++/COM 编写的遗留模块都可以通过同一个路由引擎将信息发送至NLog中。

二、NLog和Log4net的区别

  NLog的API非常类似于log4net,且配置方式非常简单。NLog使用路由表(routing table)进行配置,但log4net却使用层次性的appender配置,这样就让NLog的配置文件非常容易阅读,并便于今后维护。

三、NLog配置介绍

  

  1、下面的配置是nlog的基础配置结构

<?xml version="1.0" encoding="utf-8" ?>
<!-- 默认命名空间 -->
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd">
<!-- 这个命名空间里面的元素或者属性就必须要以xsi:这种方式来写,比如schemaLocation就是他的一个属性,所以写成xsi:schemaLocation。
而默认命名空间不带类似xsi这种;其实xml标签名称有个专业叫法叫做QName,而如果没有前面的xsi:这种一般叫做NCName -->
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
<!--表示把定义这个命名空间的schema文件给引用进来,好让开发类型工具能够解析和验证你的xml文件是否符合语法规范
简单来说 上面是用来验证你XML格式是否正确的。-->
xsi:schemaLocation="http://www.nlog-project.org/schemas/NLog.xsd NLog.xsd"
<!--一旦启动程序,这时候NLog.config文件被读取后,知道程序再启动都不会再读取配置文件了。假如我们不想停掉程序,比如说服务器哪能说停就停哈。这就用上这个配置了,这个配置功能是,一旦你对配置文件修改,程序将会重新读取配置文件,也就是自动再配置。-->
autoReload="true"
<!--NLog日志系统抛出异常-->
throwExceptions="false"
<!--日志级别 -->
internalLogLevel="Debug"
<!--NLog内部日志文件位置 -->
internalLogFile="c:\temp\nlog-internal.log">
<!--variable定义配置文件中用到的变量-->
<variable name="myvar" value="myvalue"/>
<!--定义日志的目标/输出-->
<targets> </targets>
<!--定义日志的路由规则-->
<rules> </rules>
</nlog>

  2、NLog的重要配置说明

    (1)Layout布局

      几种常见的

      ${var:basePath} basePath是前面自定义的变量
      ${longdate} 日期格式 2017-01-17 16:58:03.8667
      ${shortdate}日期格式 2017-01-17 
      ${date:yyyyMMddHHmmssFFF} 日期 20170117165803866
      ${message} 输出内容
      ${guid} guid
      ${level}日志记录的等级
      ${logger} 配置的logger

    (2)NLog记录等级

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

    (3)NLog等级使用

      指定特定等级 如:level="Warn" 
      指定多个等级 如:levels=“Warn,Debug“ 以逗号隔开
      指定等级范围 如:minlevel="Warn" maxlevel="Error"

    (4)Logger使用

      从配置文件读取信息并初始化 两种常用的方式

      方法一:根据配置的路由名获生成特定的logger:

         Logger logger = LogManager.GetLogger("LoggerDemo");

      方法二:初始化为当前命名空间下当前类的logger :

        Logger logger = LogManager.GetCurrentClassLogger();

    区别是logger的name不一样 前者是LoggerDemo,后者是当前命名空间+点+当前类名 如类比较多,并且往同一个日志文件记录,建议用GetCurrentClassLogger

    (5)Logger有以下三种常用的写入方式

      logger.Error("这是DatabaseDemo的错误信息");
      logger.Error(“ContentDemo {0}:{1}”,“时间”,DateTime.Now.ToString());需要拼接字符串的话推荐这种,NLog做了延迟处理,用的时候才拼接。
      logger.Log(LogLevel.Error, "这是ContentDemo");

    (6)Logger发邮件参数

      smtpServer=“*****” 邮件服务器 例如126邮箱是smtp.126.com
      smtpPort=“25“端口
      smtpAuthentication=“Basic“ 身份验证方式 基本
      smtpUserName=“*****“ 邮件服务器用户名
      smtpPassword=“******”邮件服务器密码
      enableSsl=“false”是否使用安全连接 需要服务器支持
      addNewLines=“true” 开头与结尾是否换行
      from=“****” 发件邮箱
      to=“XXXX@XX.com,XXXXX@XX.com”收件邮箱 多个以逗号分隔
      subject=“subject:${machinename}报错“ 邮件主题
      header=“---------------------开头-------------------------“ 邮件开头
      body=“${newline}${message}${newline}“ 邮件内容
      footer=“---------------------结尾-------------------------“ 邮件结尾

  3、NLog实例

  

<?xml version="1.0" encoding="utf-8" ?>
<!--nlog教程详情:http://www.cnblogs.com/dflying/archive/2006/12/04/581750.html--> <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"> <!-- optional, add some variables
https://github.com/nlog/NLog/wiki/Configuration-file#variables
-->
<variable name="myvar" value="myvalue"/> <!--
See https://github.com/nlog/nlog/wiki/Configuration-file
for information on customizing logging rules and outputs.
-->
<targets> <!--
add your targets here
See https://github.com/nlog/NLog/wiki/Targets for possible targets.
See https://github.com/nlog/NLog/wiki/Layout-Renderers for the possible layout renderers.
--> <!--
Write events to a file with the date in the filename.
<target xsi:type="File" name="f" fileName="${basedir}/logs/${shortdate}.log"
layout="${longdate} ${uppercase:${level}} ${message}" />
-->
<target name="console" xsi:type="Console"/>
<target name="file" xsi:type="File" fileName="${basedir}/logs/${shortdate}.log"
layout="${longdate} ${callsite} ${level}:${message} ${event-context:item=exception} ${stacktrace} ${event-context:item=stacktrace}"/>
</targets>

    <target xsi:type="Mail"
      name="SendMail"
      smtpServer="你的邮件服务器"
      smtpPort="你的邮件服务器端口"
      smtpAuthentication="Basic"
      smtpUserName="你的邮件服务器名"
      smtpPassword="你的邮件服务器密码"
      enableSsl="false"
      addNewLines="false"
      from="你的发件邮箱"
      to="你的收件邮箱"
      subject="subject:${machinename}报错"
      header="---------------------开头-------------------------"
      body="${newline}${message}${newline}"
      footer="---------------------结尾-------------------------"
      encoding="UTF-8"/>

    <target xsi:type="Database"
      name="DatabaseFile"
      dbProvider=“System.Data.SqlClient”数据库类型
      commandText=“Insert into ErrorLog(ID, Content, CreateTime) Values(@id, @content, @createTime);”插入操作
      connectionString=“data source=.;initial catalog=NLog;user id=sa;password=******;”> 数据库连接字符串 跟我们webcofig中的一样
      <parameter name=“@id” layout=“${guid}” /> 参数
      <parameter name="@content" layout="${message}" />
      <parameter name="@createTime" layout="${date:format=yyyy\-MM\-dd HH\:mm\:ss.fff} " />
    </target>

  <rules>
<!--
Write all events with minimal level of Debug (So Debug, Info, Warn, Error and Fatal, but not Trace) to "f"
<logger name="*" minlevel="Debug" writeTo="f" />
-->
<logger name="*" minlevel="Info" writeTo="console"/>
<logger name="*" minlevel="Trace" writeTo="file"/>
   <logger name="*" level="Error"  writeTo="SendMail"></logger>    <logger name="Database" level="Error" writeTo="DatabaseFile"/>
  </rules>
</nlog>

四、NLog配置的注意事项

  NLog.config可以单独放,也可以放在WebConfig里。

  1、放在webconfig中示例

  

<configuration>
<configSections>
<section name="nlog" type="NLog.Config.ConfigSectionHandler, NLog"/>
</configSections>
<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="true"
internalLogLevel="Off"
internalLogFile="c:\temp\nlog-internal.log">
<variable name="myvar" value="myvalue"/>
<targets async="false">
<target xsi:type="File" name="WebDemoFile" fileName="C:\Users\Zachary\Desktop\练习\20170113NLog\Logs\${date:yyyyMMddHHmm}WebDemo.txt" layout="${longdate} ${message}" encoding="UTF-8"/>
</targets>
<rules>
<logger name="WebDemo" level="Error" writeTo="WebDemoFile"/>
</rules>
</nlog>
</configuration>

  2、单独放置

  新建一个NLog.config文件

  

<?xml version="1.0" encoding="utf-8" ?>
<!--nlog教程详情:http://www.cnblogs.com/dflying/archive/2006/12/04/581750.html--> <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"> <!-- optional, add some variables
https://github.com/nlog/NLog/wiki/Configuration-file#variables
-->
<variable name="myvar" value="myvalue"/> <!--
See https://github.com/nlog/nlog/wiki/Configuration-file
for information on customizing logging rules and outputs.
-->
<targets> <!--
add your targets here
See https://github.com/nlog/NLog/wiki/Targets for possible targets.
See https://github.com/nlog/NLog/wiki/Layout-Renderers for the possible layout renderers.
--> <!--
Write events to a file with the date in the filename.
<target xsi:type="File" name="f" fileName="${basedir}/logs/${shortdate}.log"
layout="${longdate} ${uppercase:${level}} ${message}" />
-->
<target name="console" xsi:type="Console"/>
<target name="file" xsi:type="File" fileName="${basedir}/logs/${shortdate}.log"
layout="${longdate} ${callsite} ${level}:${message} ${event-context:item=exception} ${stacktrace} ${event-context:item=stacktrace}"/>
</targets> <rules>
<!-- add your logging rules here --> <!--
Write all events with minimal level of Debug (So Debug, Info, Warn, Error and Fatal, but not Trace) to "f"
<logger name="*" minlevel="Debug" writeTo="f" />
-->
<logger name="*" minlevel="Info" writeTo="console"/>
<logger name="*" minlevel="Trace" writeTo="file"/>
</rules>
</nlog>

下一篇NLOG实例

日志学习系列(三)——NLog基础知识的更多相关文章

  1. 日志学习系列(一)——Log4net的基础知识学习

    今天把Log4net日志记录做了封装,作为一个公共的类库.记录一下应该注意的地方.先了解一下log4net的理论知识. 参考百度百科 一.log4net是什么? log4net库是Apache log ...

  2. MyBatis学习系列三——结合Spring

    目录 MyBatis学习系列一之环境搭建 MyBatis学习系列二——增删改查 MyBatis学习系列三——结合Spring MyBatis在项目中应用一般都要结合Spring,这一章主要把MyBat ...

  3. Django学习系列之Form基础

     Django学习系列之Form基础 2015-05-15 07:14:57 标签:form django 原创作品,允许转载,转载时请务必以超链接形式标明文章 原始出处 .作者信息和本声明.否则将追 ...

  4. scrapy爬虫学习系列三:scrapy部署到scrapyhub上

    系列文章列表: scrapy爬虫学习系列一:scrapy爬虫环境的准备:      http://www.cnblogs.com/zhaojiedi1992/p/zhaojiedi_python_00 ...

  5. DocX开源WORD操作组件的学习系列三

    DocX学习系列 DocX开源WORD操作组件的学习系列一 : http://www.cnblogs.com/zhaojiedi1992/p/zhaojiedi_sharp_001_docx1.htm ...

  6. RabbitMQ学习系列三-C#代码接收处理消息

    RabbitMQ学习系列三:.net 环境下 C#代码订阅 RabbitMQ 消息并处理 http://www.80iter.com/blog/1438251320680361 http://www. ...

  7. ios开发学习笔记001-C语言基础知识

    先来学习一下C语言基础知识,总结如下: 在xcode下编写代码. 1.编写代码 2.编译:cc –c 文件名.c 编译成功会生成一个 .o的目标文件 3.链接:把目标文件.o和系统自带的库合并在一起, ...

  8. .net reactor 学习系列(三)---.net reactor代码自动操作相关保护功能

    原文:.net reactor 学习系列(三)---.net reactor代码自动操作相关保护功能         接上篇,上篇已经学习了界面的各种功能以及各种配置,这篇准备学习下代码控制许可证. ...

  9. Spring Ioc源码分析系列--Ioc的基础知识准备

    Spring Ioc源码分析系列--Ioc的基础知识准备 本系列文章代码基于Spring Framework 5.2.x Ioc的概念 在Spring里,Ioc的定义为The IoC Containe ...

随机推荐

  1. Spring AOP实现统一日志输出

    目的: 统一日志输出格式 思路: 1.针对不同的调用场景定义不同的注解,目前想的是接口层和服务层. 2.我设想的接口层和服务层的区别在于: (1)接口层可以打印客户端IP,而服务层不需要 (2)接口层 ...

  2. java基础(五)-----关键字static

    在Java中并不存在全局变量的概念,但是我们可以通过static来实现一个“伪全局”的概念,在Java中static表示“全局”或者“静态”的意思,用来修饰成员变量和成员方法,当然也可以修饰代码块. ...

  3. Solr 10 - SolrCloud集群模式简介 + 组成结构的说明

    目录 1 什么是SolrCloud 2 SolrCloud的结构 2.1 物理结构 2.2 逻辑结构 2.2.1 Collection(集合) 2.2.2 Core(内核) 2.2.3 Shard(分 ...

  4. 带着新人学springboot的应用06(springboot+RabbitMQ 中)

    上一节说了这么多废话,看也看烦了,现在我们就来用鼠标点点点,来简单玩一下这个RabbitMQ. 注意:这一节还是不用敲什么代码,因为上一节我们设置了那个可视化工具,我们先用用可视化工具熟悉一下流程. ...

  5. 前端笔记之JavaScript(八)关于元素&计算后的样式

    一.获取元素方法(JS选择器) 1.1概述 得到id元素的方法 document.getElementById() 得到一个元素.事实上,还有一个方法可以得到标签元素,并且得到的是多个元素: docu ...

  6. ELK-Logstash采集日志和输送日志流程测试

    讲解Logstash采集日志和输送日志流程测试,包括input,filter和output元素的测试 配置一:从elasticsearch日志文件读取日志信息,输送到控制台 $ cd /home/es ...

  7. Servlet主要相关类核心类 容器调用的过程浅析 servlet解读 怎么调用 Servlet是什么 工作机制

      WEB简介   Web项目 是 B/S结构 浏览器/服务器模式的 浏览器发起请求,服务器作出响应   请求的发起和响应使用HTTP协议进行通讯 所谓协议也就是一种固定格式   而Socket是应用 ...

  8. eclipse svn插件卸载 重新安装 Subclipse卸载安装 The project was not built since its build path is incomplete This client is too old to work with the working copy at

    安装插件的原则就是,要按照规则,插件与本地的svn版本要一致, 这样子本地和eclipse上面就可以无缝使用,不会出现问题 1.卸载eclipse  svn插件 2,安装新版的svn插件 2.1,下载 ...

  9. 四种途径提高RabbitMQ传输数据的可靠性(二)

    前言 上一篇四种途径提高RabbitMQ传输消息数据的可靠性(一)已经介绍了两种方式提高数据可靠性传输的方法,本篇针对上一篇中提出的问题(1)与问题(2)提出解决常用的方法. 本文其实也就是结合以上四 ...

  10. 【.NET Core项目实战-统一认证平台】第八章 授权篇-IdentityServer4源码分析

    [.NET Core项目实战-统一认证平台]开篇及目录索引 上篇文章我介绍了如何在网关上实现客户端自定义限流功能,基本完成了关于网关的一些自定义扩展需求,后面几篇将介绍基于IdentityServer ...