零基础WPF使用NLog记录日志
使用步骤:
1、NuGet安装NLog.conf包即可,这个包会同时安装其他的依赖包;
2、修改NLog.conf的配置,配置参数参考:NLog详解-CSDN博客
<?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">
<variable name="myvar" value="myvalue"/>
<targets>
<!-- 写入文件的配置 -->
<target name="info_file" xsi:type="File"
fileName="${basedir}/logs/info_file.txt"
archiveFileName="${basedir}/logs/info_file.{###}.txt"
archiveEvery="Day"
archiveNumbering="DateAndSequence"
archiveAboveSize="10000000"
maxArchiveFiles="90"
keepFileOpen="true"
layout="${longdate} ${uppercase:${level}} ${message} ${exception:stacktrace}" />
</targets>
<rules>
<!-- 记录的级别 -->
<logger name="*" minlevel="Info" writeTo="info_file" />
</rules>
</nlog>
3、新建一个日志的类,后续方便统一使用打印
using System;
using System.Collections.Generic;
using NLog;
namespace XXX项目的命令空间XXX
{
internal class LoggerHelper
{
public static Logger logger = LogManager.GetCurrentClassLogger(); //初始化日志类
/// <summary>
///
/// </summary>
/// <param name="errorFile">错误源文件</param>
/// <param name="errorMsg">错误消息</param>
/// <param name="errorFunc">错误函数</param>
public static void Logger_Debug(string errorFile,string errorMsg ,string errorFunc="")
{
string errorStr="调试源文件:《"+errorFile+"》,调试源函数:["+errorFunc+ "],调试信息:" + errorMsg;
logger.Debug(errorStr);
}
/// <summary>
///
/// </summary>
/// <param name="errorFile">错误源文件</param>
/// <param name="errorMsg">错误消息</param>
/// <param name="errorFunc">错误函数</param>
public static void Logger_Info(string errorFile, string errorMsg, string errorFunc = "")
{
string errorStr = "源文件:《" + errorFile + "》,源函数:[" + errorFunc + "],信息:" + errorMsg;
logger.Info(errorStr);
}
/// <summary>
///
/// </summary>
/// <param name="errorFile">错误源文件</param>
/// <param name="errorMsg">错误消息</param>
/// <param name="errorFunc">错误函数</param>
public static void Logger_Warn(string errorFile, string errorMsg, string errorFunc = "")
{
string errorStr = "警告源文件:《" + errorFile + "》,警告源函数:[" + errorFunc + "],警告信息:" + errorMsg;
logger.Warn(errorStr);
}
/// <summary>
///
/// </summary>
/// <param name="errorFile">错误源文件</param>
/// <param name="errorMsg">错误消息</param>
/// <param name="errorFunc">错误函数</param>
public static void Logger_Error(string errorFile, string errorMsg, string errorFunc = "")
{
string errorStr = "错误源文件:《" + errorFile + "》,错误源函数:[" + errorFunc + "],错误信息:" + errorMsg;
logger.Error(errorStr);
}
}
}