C# 使用Nlog记录日志文件 - 简易使用

目录导航

【C#】使用Nlog记录日志文件

一、准备工作

1、安装Nlog和Nlog.config
右键项目

ba0f3faf08e97a787b4b7c92c700cd76.png
安装这两个内容

61df7e58513f344a4aa2d3d90eeae632.png

二、配置NLog.config

安装好后项目中会自动生成一个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"/>

  <!--
  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}" />
    -->

       </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" />
    -->

    </rules>
</nlog>

我们只需要关注两个,targets和rules。
在targets标签内加入

<!--此部分中的所有目标将自动异步-->
<target name="asyncFile" xsi:type="AsyncWrapper">
    <target name="log_file" xsi:type="File"
        fileName="${basedir}/Logs/${shortdate}.log"
        layout="${longdate} | ${message} ${onexception:${exception:format=message} ${newline} ${stacktrace} ${newline}"
        concurrentWrites="true"
        keepFileOpen="false" />
</target>

这个是异步执行的,位置会放在基础路径的logs文件夹下的用当前年月日命名的log文件下
在rules标签内加入

<logger name="*" minlevel="Info" writeTo="asyncFile" />

三、写log读写类

新建类LoggerHelper

public class LoggerHelper
 {
    /// <summary>
    /// 实例化nLog,即为获取配置文件相关信息(获取以当前正在初始化的类命名的记录器)
    /// </summary>
    private readonly NLog.Logger _logger = LogManager.GetCurrentClassLogger();

    private static LoggerHelper _obj;

    public static LoggerHelper _
    {
        get => _obj ?? (new LoggerHelper());
        set => _obj = value;
    }

    #region Debug,调试
    public void Debug(string msg)
    {
         _logger.Debug(msg);
    }

    public void Debug(string msg, Exception err)
    {
        _logger.Debug(err, msg);
    }
    #endregion

    #region Info,信息
    public void Info(string msg)
    {
        _logger.Info(msg);
    }

    public void Info(string msg, Exception err)
    {
        _logger.Info(err, msg);
    }
    #endregion

    #region Warn,警告
    public void Warn(string msg)
    {
        _logger.Warn(msg);
    }

    public void Warn(string msg, Exception err)
    {
        _logger.Warn(err, msg);
    }
    #endregion

    #region Trace,追踪
    public void Trace(string msg)
    {
        _logger.Trace(msg);
    }

    public void Trace(string msg, Exception err)
    {
        _logger.Trace(err, msg);
    }
    #endregion

    #region Error,错误
    public void Error(string msg)
    {
        _logger.Error(msg);
    }

    public void Error(string msg, Exception err)
    {
        _logger.Error(err, msg);
    }
    #endregion

    #region Fatal,致命错误
    public void Fatal(string msg)
    {
        _logger.Fatal(msg);
    }

    public void Fatal(string msg, Exception err)
    {
        _logger.Fatal(err, msg);
    }
    #endregion
}

四、实际使用

使用举例

LoggerHelper._.Info($"完成");

try 
{
//...
}
catch (Exception ex)
{
    LoggerHelper._.Error(ex.Message);
}
posted @ 2021-02-22 13:42  养鼠的猫  阅读(914)  评论(0编辑  收藏  举报