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);
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM