C#应用使用NLog记录日志

前言

本文主要讲述C#应用如何使用NLog记录应用日志。具体使用步骤参考下方。

NLog是一个基于.NET平台编写的类库,我们可以使用NLog在应用程序中添加极为完善的跟踪调试代码。

NLog是一个简单灵活的.NET日志记录类库。

使用步骤

1、添加NLog引用

创建控制台应用,使用nuget添加NLog包到项目中。或者直接在项目中添加NLog.dll、NLog.config引用。

2、添加NLog封装类

添加类MyLog.cs到项目中,完整代码如下:

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

        private MyLog() { }

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

    }
}

3、修改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.
    -->
    <target name="file" xsi:type="File"
            fileName="${basedir}/log/${date:format=yyyy-MM}/logfile.log"
            layout="${date:format=HH\:mm\:ss.fff}[${level:uppercase=true:padding=-5}][${mdc:item=logkey:padding=-20}]:${message}"
            archiveFileName="${basedir}/log/logfile-{#}.txt"
            archiveEvery="Day"
            archiveNumbering="Date"
            archiveDateFormat="yyyyMMdd"
            maxArchiveFiles="6"/>
    <target name="console" xsi:type="Console" layout="${longdate}|${level}|${message}"/>
    <!--
    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 -->
    <logger name="*"  minlevel="Debug" writeTo="file"/>
    <!--
    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>

4、使用MyLog输出日志到文件

示例代码如下所示:

using System;
using WebSocketSharp;
using WebSocketSharp.Server;

namespace ConsoleApp4
{
    class Program
    {
        static void Main(string[] args)
        {
            MyLog.Info("启动ws服务...");
            var wssv = new WebSocketServer(10086);
            wssv.AddWebSocketService<ScannerHandler>("/scan");
            wssv.Start();
            if (wssv.IsListening)
            {
                MyLog.Info(string.Format("Listening on port {0}, and providing WebSocket services:", wssv.Port));
                Console.WriteLine("Listening on port {0}, and providing WebSocket services:", wssv.Port);
                foreach (var path in wssv.WebSocketServices.Paths)
                    Console.WriteLine("- {0}", path);
            }

            Console.WriteLine("\nPress Enter key to stop the server...");
            Console.ReadLine();

            wssv.Stop();
        }
    }

    public class ScannerHandler : WebSocketBehavior
    {
        protected override void OnMessage(MessageEventArgs e)
        {
            Console.WriteLine(e.Data);
            Send("scan success");
        }
    }
}

5、测试日志输出

在bin/Debug目录下,我们发现多了log目录,查看日志内容如下所示:

02:07:36.444[INFO ][         ]:启动ws服务...
02:07:36.504[INFO ][         ]:Listening on port 10086, and providing WebSocket services:

(完)

C#
最后修改于:2023年04月16日 02:20

添加新评论