使用NLog记录上位机操作日志

发布时间 2023-09-08 23:31:32作者: hanzq_go

在上位机中一些重要日志信息需要保存到日志中,比如登录信息,操作信息等。

用于日志的库常用的有NLog、Log4Net等,相较而言NLog库配置简单,学习成本低。

使用方法如下:

1、NuGet下载安装NLog库;

2、修改或创建配置文件,方法有两种,分别如下:

方法1:创建一个“nlog.config”的配置文件(注意,文件名nlog是NLog库中约定的,不能随便改),配置如下:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <!-- 示例配置文件 nlog.config -->
    <nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

        <targets>
            <!--以日期+log命名的日志,第一种方法-->
            <target xsi:type="File" name="file" fileName="E:\log\${date:format=yyyyMMdd}log.txt" />
            
            <!--以日期+log命名的日志,第二种方法-->
            <!--
            <target xsi:type="File" name="file" fileName="E:\log\${shortdate}log.txt" />
            -->
            
            <!--保存到指定文件夹-->
            <!--
            <target xsi:type="File" name="file" fileName="E:\log.txt" />
            -->

            <!--保存到当前文件夹-->
            <!--
            <target xsi:type="File" name="file" fileName="./log.txt" />
            -->
            
        </targets>

        <rules>
            <logger name="UserActionLogger" minlevel="Info" writeTo="file" />
        </rules>

    </nlog>
</configuration>

上面的代码中,分别演示了将日志文件保存到相对路径,绝对路径,以及按时间日期,每天一个日志文件的保存方法。

方法2:使用 App.config 或 Web.config:将 NLog 的配置信息添加到应用程序的配置文件中。实例项目为winform项目,使用App.config 文件,对其修改如下:

<configuration>
  <configSections>
    <section name="nlog" type="NLog.Config.ConfigSectionHandler, NLog" />
  </configSections>
 
  <nlog>
    <!-- NLog的配置内容 -->  
    <targets>
      <target name="logfile" xsi:type="File" fileName="log.txt" />
    </targets>
 
    <rules>
      <logger name="*" minlevel="Info" writeTo="logfile" />
    </rules>
  </nlog>
</configuration>

3、获取NLog实例,有两种方法:

方法1,使用LogManager.GetLogger方法,如下:

private static readonly Logger logger = LogManager.GetLogger("UserActionLogger");

要求:配置文件中<logger name="UserActionLogger" minlevel="Info" writeTo="file" />,logger name与LogManager.GetLogger(name)中的参数name必须相同。

方法2,使用方法,如下:

private static readonly Logger logger = LogManager.GetCurrentClassLogger();

要求:配置文件中<logger name="*" minlevel="Info" writeTo="file" />,logger name="*"

4、使用logger记录日志,

logger.Trace()logger.Debug()logger.Info()logger.Warn()logger.Error()logger.Fatal() 是 NLog 中的日志级别方法,用于记录不同级别的日志。

这里常用的是logger.Info();

例如点击按钮操作时:logger.Info("用户点击了按钮");