首页 > 其他分享 >.net 控制台 Nlog的使用

.net 控制台 Nlog的使用

时间:2022-09-29 17:14:27浏览次数:49  
标签:控制台 string strMsg public Nlog static net NLogHelper logger

nuget引入NLog组件

 

 NLog.config 记得改为始终复制

<?xml version="1.0" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      autoReload="true"
      throwExceptions="false"
      internalLogLevel="Trace">

	<variable name="fileFormat"
		 value="
            ${newline}date: ${date}
            ${newline}level: ${level}
            ${newline}logger: ${logger}
            ${newline}machinename: ${machinename}
            ${newline}message: ${message}
            ${newline}------------------------------------------------------------" />
	<targets>

	<target name="logfile"
	xsi:type="File"
	maxArchiveFiles="1"
	layout="${fileFormat}"
	archiveAboveSize="102400000"
	fileName="${basedir}/Logs/${date:format=yyyy-MM}/${shortdate}.log" />

	</targets>
	<!--写入到文件-->
	<rules>
		<logger name="*" minlevel="Debug" writeTo="logfile" />
	</rules>
</nlog>

  NLogHelper

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp
{
    public class NLogHelper
    {
        private static NLog.Logger _logger = NLog.LogManager.GetCurrentClassLogger();

        private NLogHelper() { }

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

    }
}

  使用方法

            for (int i = 0; i < 100; i++)
            {
                var date = DateTime.Now;
                NLogHelper.Warn("LogTest:" + date.ToString());
                NLogHelper.Info("LogTest:" + date.ToString());
                NLogHelper.Error("LogTest:" + date.ToString());
                NLogHelper.Debug("LogTest:" + date.ToString());
            }

  输出效果

 

 Nlog和Log4net相比,配置更少更简便,输出内容格式更清晰,使用方便。

标签:控制台,string,strMsg,public,Nlog,static,net,NLogHelper,logger
From: https://www.cnblogs.com/request/p/16742188.html

相关文章