介绍
NLog
是.NET平台下一款日志组件,同时也支持.NET Core
。可以直接在项目中安装nuget包使用NLog
。
以下示例代码中引用了如下NLog
及NLog.Config
两个nuget包,其中后者是用来生成NLog
的配置文件.
NLog配置
<?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.
-->
<!--
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}" />
-->
<target xsi:type="Null" name="blackhole" />
<target name="database" xsi:type="Database" dbProvider="MySql.Data.MySqlClient.MySqlConnection, MySql.Data" connectionString="server=127.0.0.1;Database=example;user id=root;password=123456;SslMode=none" >
<commandText>
insert into log
(Application, Logged, Level, Message,Logger, CallSite, Exception)
values (@Application, @Logged, @Level, @Message,@Logger, @Callsite, @Exception);
</commandText>
<parameter name="@application" layout="NLogDemo" />
<parameter name="@logged" layout="${date}" />
<parameter name="@level" layout="${level}" />
<parameter name="@message" layout="${message}" />
<parameter name="@logger" layout="${logger}" />
<parameter name="@callSite" layout="${callsite:filename=true}" />
<parameter name="@exception" layout="${exception:tostring}" />
</target>
<target xsi:type="File" name="logfile" fileName="${basedir}/logs/${shortdate}.log"
layout="${longdate} [${uppercase:${level}}] ${newline} ${message}" />
</targets>
<rules>
<!-- add your logging rules here -->
<!--
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" />
-->
<logger name="Microsoft.*" minlevel="Trace" writeTo="blackhole" final="true" />
<logger name="NLogDemo.*" minlevel="Info" writeTo="database" />
<logger name="*" minlevel="Info" maxlevel="Fatal" writeTo="logfile" />
</rules>
</nlog>
需要记录到数据库可使用以下语句创建表:
CREATE TABLE `log` (
`Id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`Application` varchar(50) DEFAULT NULL,
`Logged` datetime DEFAULT NULL,
`Level` varchar(50) DEFAULT NULL,
`Message` varchar(512) DEFAULT NULL,
`Logger` varchar(250) DEFAULT NULL,
`Callsite` varchar(512) DEFAULT NULL,
`Exception` varchar(512) DEFAULT NULL,
PRIMARY KEY (`Id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
说明:以上配置中logfile
用于写入文件,database
用于写入数据库(本示例中写入MySql)。
控制台示例Demo
引入命名空间using NLog
。
示例代码
static void Main(string[] args)
{
Logger logger = LogManager.GetCurrentClassLogger();
logger.Trace("Trace Message");
logger.Debug("Debug Message");
logger.Info("Info Message");
logger.Error("Error Message");
logger.Fatal("Fatal Message");
Console.WriteLine("Hello World!");
}
.NET Core WebApi示例Dmeo
StartUp.cs配置:
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
//使用NLog作为日志记录工具
loggerFactory.AddNLog();
//引入Nlog配置文件
env.ConfigureNLog("Nlog.config");
app.UseMvc();
}
Program.cs中绑定:
public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseNLog()
.UseStartup<Startup>()
.Build();
使用方式同上述控制台示例:
private readonly Logger logger = LogManager.GetCurrentClassLogger();
// GET api/values
[HttpGet]
public IEnumerable<string> Get()
{
logger.Trace("Trace Message");
logger.Debug("Debug Message");
logger.Info("Info Message");
logger.Error("Error Message");
logger.Fatal("Fatal Message");
return new string[] { "value1", "value2" };
}