1.引入NLog.dll,这里使用的版本如下:
2.建立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">
<targets>
<!--屏幕打印消息-->
<target name="console" xsi:type="ColoredConsole"
layout="${longdate}> ${message}"/>
<!--VS输出窗口-->
<target name="debugger" xsi:type="Debugger"
layout="${longdate} | ${level:padding=-5} | ${message}" />
<!--保存至文件-->
<target name="info" xsi:type="File" maxArchiveFiles="30"
fileName="${basedir}/Logs/Info/info${shortdate}.txt"
layout="${date:format=HH\:mm\:ss} | ${message}" />
<!--保存至文件-->
<target name="error" xsi:type="File" maxArchiveFiles="30"
fileName="${basedir}/Logs/Error/error${shortdate}.txt"
layout="${date:format=HH\:mm\:ss} | ${message} | ${onexception:${exception:format=tostring} ${newline} ${stacktrace} ${newline}" />
</targets>
<rules>
<logger name="*" writeTo="console" />
<logger name="*" minlevel="Debug" writeTo="debugger" />
<logger name="*" minlevel="Info" maxlevel="Info" writeTo="info" />
<logger name="*" minlevel="Error" writeTo="error" />
</rules>
</nlog>
3.测试代码
using System;
using NLog;
namespace ConsoleApp1
{
class Program
{
private static readonly ILogger logger = LogManager.GetLogger("Logger");
static void Main(string[] args)
{
logger.Trace("trace...");
logger.Debug("debug...");
logger.Error(new ArgumentException("error..."));
logger.Info("info...");
Console.ReadKey();
}
}
}
4.日志输出结果
控制台日志按颜色输出
异常日志按天输出到文件