C#快速配置NLog日志的教程详解

 更新时间:2024年02月20日 10:43:10   作者:搬砖的诗人Z  
这篇文章主要为大家详细介绍了C#快速配置NLog日志的教程相关知识,文中的示例代码讲解详细,具有一定的借鉴价值,感兴趣的小伙伴可以了解一下

首先我们需要在Nuget中安装Nlog和Nlog-Schema。

添加配置文件: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="d:\nlog\nlog-internal.log">

  <!-- optional, add some variables
  https://github.com/nlog/NLog/wiki/Configuration-file#variables
  -->
  <!--<variable name="myvar" value="myvalue"/>-->

  <variable name="logDir" value="${basedir}/nlog"/>
  <variable name="logFileName" value="${date:format=yyyyMMdd}.txt"/>
  <variable name="logArchiveFileName" value="${date:format=yyyyMMdd}_{#}.txt"/>
  <variable name="logLayout" value="${date:format=yyyy-MM-dd HH\:mm\:ss.fff} [${level}] ${message}"/>

  <!--
  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 xsi:type="File" name="info"
            layout="${logLayout}"
            fileName="${logDir}/info/${logFileName}"
            archiveFileName="${logDir}/info/${logArchiveFileName}"
            archiveAboveSize="10485760"
            archiveNumbering="Sequence"
            maxArchiveFiles="100"
            concurrentWrites="true"
            keepFileOpen="true"
            openFileCacheTimeout="30"
            encoding="UTF-8" />

    <target xsi:type="File" name="debug"
            layout="${logLayout}"
            fileName="${logDir}/debug/${logFileName}"
            archiveFileName="${logDir}/debug/${logArchiveFileName}"
            archiveAboveSize="10485760"
            archiveNumbering="Sequence"
            maxArchiveFiles="100"
            concurrentWrites="true"
            keepFileOpen="true"
            openFileCacheTimeout="30"
            encoding="UTF-8" />

    <target xsi:type="File" name="error"
            layout="${logLayout}"
            fileName="${logDir}/error/${logFileName}"
            archiveFileName="${logDir}/error/${logArchiveFileName}"
            archiveAboveSize="10485760"
            archiveNumbering="Sequence"
            maxArchiveFiles="100"
            concurrentWrites="true"
            keepFileOpen="true"
            openFileCacheTimeout="30"
            encoding="UTF-8" />

    <target xsi:type="File" name="warn"
        layout="${logLayout}"
        fileName="${logDir}/warn/${logFileName}"
        archiveFileName="${logDir}/warn/${logArchiveFileName}"
        archiveAboveSize="10485760"
        archiveNumbering="Sequence"
        maxArchiveFiles="100"
        concurrentWrites="true"
        keepFileOpen="true"
        openFileCacheTimeout="30"
        encoding="UTF-8" />

  </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" maxlevel="Info" writeTo="info" />

    <logger name="*" minlevel="Debug" maxlevel="Debug" writeTo="debug" />

    <logger name="*" minlevel="Error" maxlevel="Error" writeTo="error" />

    <logger name="*" minlevel="Warn" maxlevel="Warn" writeTo="warn" />

  </rules>
</nlog>

定义了5种log类型Debug,Info,Debug,Error,Warn,详细配置可以自己定义。

定义一个常用的log类

  public class NLogHelper
  {
      private static Logger _log = NLog.LogManager.GetCurrentClassLogger();

      /// <summary>
      /// Debug日志
      /// </summary>
      /// <param name="log"></param>
      public static void Debug(string log)
      {
          _log.Debug(log);
      }

      /// <summary>
      /// Error日志
      /// </summary>
      /// <param name="log"></param>
      public static void Error(string log)
      {
          _log.Error(log);
      }

      /// <summary>
      /// Warn日志
      /// </summary>
      /// <param name="log"></param>
      public static void Warn(string log)
      {
          _log.Warn(log);
      }

      /// <summary>
      /// Info日志
      /// </summary>
      /// <param name="log"></param>
      public static void Info(string log)
      {
          _log.Info(log);
      }

      /// <summary>
      /// 详细异常日志
      /// </summary>
      /// <param name="ex"></param>
      public static void Exception_Error(Exception ex)
      {
          try
          {
              if (ex != null)
              {
                  StringBuilder strBuilder = new StringBuilder();
                  strBuilder.Append("【异常日志消息】");
                  strBuilder.AppendLine(ex.Message);
                  strBuilder.Append("【异常日志Trace】");
                  strBuilder.AppendLine(ex.StackTrace);
                  strBuilder.Append("【异常日志全部】");
                  strBuilder.Append(ex.ToString());
                  _log.Error(strBuilder.ToString());
              }
          }
          catch (Exception)
          {
          }
      }
  }

调用代码

   NLogHelper.Info($"系统正在运行中...");

到此这篇关于C#快速配置NLog日志的教程详解的文章就介绍到这了,更多相关C#配置NLog日志内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • C#使用selenium实现爬虫

    C#使用selenium实现爬虫

    这篇文章介绍了C#使用selenium实现爬虫的方法,文中通过示例代码介绍的非常详细。对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2022-06-06
  • C#不登录电脑启动程序

    C#不登录电脑启动程序

    本文主要介绍了创建系统服务;开启服务,启动程序。具有一定的参考价值,下面跟着小编一起来看下吧
    2017-01-01
  • C# pictureBox用法案例详解

    C# pictureBox用法案例详解

    这篇文章主要介绍了C# pictureBox用法案例详解,本篇文章通过简要的案例,讲解了该项技术的了解与使用,以下就是详细内容,需要的朋友可以参考下
    2021-08-08
  • C# IEnumerator枚举器的具体使用

    C# IEnumerator枚举器的具体使用

    本文主要介绍了C# IEnumerator枚举器的具体使用,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2022-06-06
  • C#实现简易猜数字游戏

    C#实现简易猜数字游戏

    这篇文章主要为大家详细介绍了C#实现简易猜数字游戏,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2018-04-04
  • C#自定义事件监听实现方法

    C#自定义事件监听实现方法

    这篇文章主要介绍了C#自定义事件监听实现方法,涉及C#事件监听的实现技巧,具有一定参考借鉴价值,需要的朋友可以参考下
    2015-08-08
  • c#之圆形无标题栏椭圆窗体的实现详解

    c#之圆形无标题栏椭圆窗体的实现详解

    本篇文章是对c#中圆形无标题栏椭圆窗体的实现方法进行了详细的分析介绍,需要的朋友参考下
    2013-06-06
  • C#中TransactionScope的使用小结

    C#中TransactionScope的使用小结

    本篇文章主要是对C#中TransactionScope的使用方法进行了详细的介绍,需要的朋友可以过来参考下,希望对大家有所帮助
    2014-01-01
  • c# 遍历 Dictionary的四种方式

    c# 遍历 Dictionary的四种方式

    这篇文章主要介绍了c# 遍历 Dictionary的四种方式,帮助大家更好的理解和使用c#,感兴趣的朋友可以了解下
    2020-09-09
  • 3种C# 加载Word的方法

    3种C# 加载Word的方法

    本次经验内容分享通过C#程序来加载Word文档的3种不同方法。分别是:加载本地Word文档、以只读模式加载Word文档、从流加载Word 想具体了解的小伙伴请参考下文
    2021-09-09

最新评论