NLog的基本使用
1.nuget包安装NLog(控制台),如果在 ASP.NET Core 项目,则NLog.Web.AspNetCore;
2.创建nlog.config配置文件,尽量放置在bin/debug文件下,以便于程序查找
基本配置如下:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<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">
<targets>
<target xsi:type="File" name="file" fileName="log.txt" />
<target xsi:type="Console" name="console" />
</targets>
<rules>
<logger name="*" minlevel="Trace" writeTo="file,console" />
</rules>
</nlog>
</configuration>
该配置既可以在控制台上输出,也可以输入到文件中
3.使用(方法如下)
class Program
{
private static readonly Logger logger = LogManager.GetCurrentClassLogger();
static void Main()
{
// 设置日志服务
// LogManager.Configuration = new XmlLoggingConfiguration("nlog.config");
// 使用日志
logger.Info("Information message");
logger.Warn("Warning message");
logger.Error("Error message");
}
}
真实的应用程序中,通常无需手动配置 LogManager。NLog 会尝试自动加载配置文件(如 nlog.config),并配置 LogManager。
写入的日志文件可以不存在,只需要在nlog.config文件中修改为所需要的名字即可,应用运行后可以在/bin/debug目录下自动生成日志文件