C# 使用NLog记录日志入门操作

 环境:win7 64位, VS2010

1、首先用VS2010创建命令行工程NLogDemo

2、在程序包管理器控制台中输入:Install-Package NLog -Version 4.4.12

  这句是怎么来的,要是你用过nuget包管理工具,那就可以跳过这里的说明了。

  要使用nuget添加NLog包到项目中。请看下图。

 

然后在程序包管理工具控制台下输入:Install-Package NLog -Version 4.4.12

再看看Install-Package NLog -Version 4.4.12这个怎么找。

打开百度搜索:Nuget

然后在Nuget官网上搜索栏输入:Nlog 回车

选择第一项Nlog

 

然后在 Version History 下选择 4.4.12 这个版本

 

至于为什么选择这个版本,因为这个版本下载的次数多。嘿嘿,没办法,随大流。当然还要看这个版本包的依赖项

这个包的没有什么特殊依赖项,所以可以使用。然后拷贝

 

 

 这里这句话就是要我们要找的。是不是挺简单的。

当我们在包程序包管理器控制台中输入:Install-Package NLog -Version 4.4.12 然后按下回车键,VS IDE 会自动到 nuget.org 这里下载依赖包。

NLog 包添加完之后,还要添加 NLog.config(4.4.12)(Install-Package NLog.Config -Version 4.4.12) 这个包,按道理 NLog 和 NLog.config 应该一起的,

突然从某个版本开始分开了,要单独添加。具体情况可以去官网看介绍:https://nlog-project.org/

 

添加 NLog.config 的方法跟上面添加 NLog 的方法一样。

3、简单封装 Log

  添加类Log.cs到工程中,修改代码如下:

public sealed class Log
{
    private static NLog.Logger _logger = NLog.LogManager.GetCurrentClassLogger();

    private Log() { }

    public static void Trace(string strMsg)
    {
        _logger.Trace(strMsg);
    }

    public static void Debug(string strMsg)
    {
        _logger.Debug(strMsg);
    }

    public static void Info(string strMsg)
    {
        _logger.Info(strMsg);
    }

    public static void Warn(string strMsg)
    {
        _logger.Warn(strMsg);
    }

    public static void Error(string strMsg)
    {
        _logger.Error(strMsg);
    }

    public static void Fatal(string strMsg)
    {
        _logger.Fatal(strMsg);
    }

}

4、修改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">

  <!-- optional, add some variables
  https://github.com/nlog/NLog/wiki/Configuration-file#variables
  -->
    <!--
  <variable name="myvar" value="myvalue"/>
    -->
    <variable name="fileFormat"
            value="
            ${newline}date: ${date}
            ${newline}level: ${level}
            ${newline}logger: ${logger}
            ${newline}machinename: ${machinename}
            ${newline}message: ${message}
            ${newline}appdomain: ${appdomain}
            ${newline}assembly-version: ${assembly-version}
            ${newline}basedir: ${basedir}
            ${newline}callsite: ${callsite}
            ${newline}counter: ${counter}
            ${newline}nlogdir: ${nlogdir}
            ${newline}processid: ${processid}
            ${newline}processname: ${processname}
            ${newline}specialfolder: ${specialfolder}
            ${newline}stacktrace: ${stacktrace}
            ${newline}------------------------------------------------------------" />

  <!--
  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="file" xsi:type="File"
            fileName="${basedir}/Logs/${date:format=yyyy-MM}/${shortdate}.log"
            layout="${fileFormat}"
            maxArchiveFiles="5"
            archiveAboveSize="10240" />
      
  </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" />
    -->

    <!--
        Level    Example
        Fatal    Highest level: important stuff down
        Error    For example application crashes / exceptions.
        Warn    Incorrect behavior but the application can continue
        Info    Normal behavior like mail sent, user updated profile etc.
        Debug    Executed queries, user authenticated, session expired
        Trace    Begin method X, end method X etc
    -->
    <!--
        Logging 水平分为以下等级“Trace<<Debug<<Info<<Warn<<Error<<Fatal ”,如果我们选择Info值,则Trace和Debug等级的信息不会被输出。
    -->
     <logger name="*" minlevel="Trace" writeTo="file"/>
  </rules>
</nlog>

简单解释:

variable  log文件的内容输出格式
targets 目标文件(要生成的Log文件)的配置(文件名、格式变量、文件个数、文件大小等等)
rules 规则,也就是俗话说的Log输出级别

以上内容不进行过多解释了,再多解释也不如官网的说明。详细介绍请看官网:https://github.com/nlog/NLog/wiki/Configuration-file#configuration-file-format

更多配置文件可以参考: https://github.com/jkowalski/NLog/tree/master/examples/targets/Configuration%20File

5、使用Log输出日志到文件,简单示例代码如下

class Program
{
    static void Main(string[] args)
    {
        RunTest();
        
        Console.WriteLine("Press a key end ...");
        Console.ReadKey(true);
    }

    static void RunTest()
    {
        for (int i = 0; i < 1000; i++)
        {
            Log.Info(string.Format("{0}", i + 1));

            System.Threading.Thread.Sleep(10);
        }
    }

}

输出路径结构

输出文件内容:

以上内容输出格式可以在NLog.config中根据需求进行裁剪。

demo下载

 

posted @ 2018-09-20 23:15  碧水青荷  阅读(12409)  评论(1编辑  收藏  举报