1:安装
Install-Package NLog.Config 或 通过Nuget
2:Log levels
Trace 非常详细的信息,一般在开发时使用。
Debug 比Trace稍微少一点一般不在生产环境使用
Info 消息信息,一般在生产环境使用
Warn 警告信息,一般用于非 严格限制,能够自动回复或临时失败的消息
Error 错误消息,一般用作异常信息
Fatal 非常严重的错误消息
3:配置
Target
打开 NLog.config,
在<targets>节点内添加:
<target name="logfile" xsi:type="File" fileName="${basedir}/file.txt" />
在MVC项目中要加上${basedir}
在<rules> 节点下添加:
<logger name="*" minlevel="Info" writeTo="logfile" />
这个rule将会把所有的的消息(name="*"),且消息级别>=Info(Info, Warn, Error, Fatal) 发送到targetName位logfile的target上。
4:Demo
using NLog;
public class MyClass
{
private static Logger logger = LogManager.GetCurrentClassLogger();
public void MyMethod1()
{
logger.Trace("Sample trace message");
logger.Debug("Sample debug message");
logger.Info("Sample informational message");
logger.Warn("Sample warning message");
logger.Error("Sample error message");
logger.Fatal("Sample fatal error message");
// alternatively you can call the Log() method
// and pass log level as the parameter.
logger.Log(LogLevel.Info, "Sample informational message");
}
}
--指定特殊Routing
<?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="logfile" xsi:type="File" fileName="file.txt" /> </targets> <rules> <logger name="SomeNamespace.Component.*" minlevel="Trace" writeTo="logfile" final="true" /> <logger name="*" minlevel="Info" writeTo="logfile" /> </rules> </nlog>
第一个rule 将会发送所有的名称以SomeNamespace.Component. 且lever>=Trace,属性 final="true" 将会在写入只有中断之后的rule的执行。
--Wrappers
简单的将一个target 放在另外一个target中即可
<?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="asyncFile" xsi:type="AsyncWrapper"> <target name="logfile" xsi:type="File" fileName="file.txt" /> </target> </targets> <rules> <logger name="*" minlevel="Info" writeTo="asyncFile" /> </rules> </nlog>
--Layouts
Layout提供了一种格式化输出内容的方式,主要有2中Layout
--简单Layout, Layout Renderers集成
--结构化Layout,可以输出XML,CVS,和其他复杂的结构.
简单的Layouti仅仅是一个String ,是由嵌入在${xxx}的特殊Tag,例如下面的声明,
<target name="logfile" xsi:type="File" fileName="file.txt" layout="${date:format=yyyyMMddHHmmss} ${message}" />
将会在每条消息前面加上格式化的日期信息
Extending NLog
自定义Target
using NLog; using NLog.Config; using NLog.Targets; namespace MyNamespace { [Target("MyFirst")] public sealed class MyFirstTarget: TargetWithLayout { public MyFirstTarget() { this.Host = "localhost"; } [RequiredParameter] public string Host { get; set; } protected override void Write(LogEventInfo logEvent) { string logMessage = this.Layout.Render(logEvent); SendTheMessageToRemoteHost(this.Host, logMessage); } private void SendTheMessageToRemoteHost(string host, string message) { // TODO - write me } } }
自定义Layout:[LayoutRenderer("hello-world")]
public class HelloWorldLayoutRenderer : LayoutRenderer {
protected override void Append(StringBuilder builder, LogEventInfo logEvent) { builder.Append("hello world!"); } }
带参数的Layout
[LayoutRenderer("hello-world")] public class HelloWorldLayoutRenderer : LayoutRenderer { /// <summary> /// I'm not required or default /// </summary> public string Config1 { get; set; } /// <summary> /// I'm required /// </summary> [RequiredParameter] public string Config2 { get; set; } /// <summary> /// I'm the default parameter. You can set me as required also. /// </summary> [DefaultParameter] public bool Caps {get;set;}
Example usages
${hello-world}
- raises exception: required parameter Config2 isn't set${hello-world:Config2=abc}
- OK, Config2 property set${hello-world:true:config2=abc}
- default parameter (Caps) set totrue
${hello-world:true:config2=abc:config1=yes}
- all the three properties set.
怎么使用自定义Target/Layout:
1:分开的DLL
<nlog> <extensions> <add assembly="MyAssembly"/> </extensions> <targets> <target name="a1" type="MyFirst" host="localhost"/> <target name="f1" type="file" layout="${longdate} ${hello-world}" fileName="${basedir}/logs/logfile.log" /> </targets> <rules> <logger name="*" minLevel="Info" appendTo="a1"/> <logger name="*" minLevel="Info" appendTo="f1"/> </rules> </nlog>
对应DLL名称放入Extensions中
2:编程方式
//target ConfigurationItemFactory.Default.Targets .RegisterDefinition("MyFirst", typeof(MyNamespace.MyFirstTarget)); //layout renderer ConfigurationItemFactory.Default.LayoutRenderers .RegisterDefinition("hello-world", typeof(MyNamespace.HelloWorldLayoutRenderer )); // start logging here