This article describes the log plug-in for C # Nlog
Installing plugins
Create Logger
Log level
Writing log information
Configuration
Packaging device
Layout
-
Installing plugins
直接下载插件包 Install-NLog.Config
-
Create Logger
使用LogManager创建Logger实例,最好一个类里面一个Logger实例 写法一 ConsoleApp1.Program privatestatic=LogManager.GetCurrentClassLogger(); 写法二 这种写法,可以手动设置日志文件中的logger名字 =LogManager.GetLogger("myTest");
-
Log level
级别由低到高Trace 记录完整的信息,一般只用在开发环境Debug 记录调试信息,没有Trace信息完整,一般也只用在开发环境Info 简单的信息,一般用在生产环境Warn 记录警告信息,一些可以解决的小问题Error 记录报错信息,一般都是Exceptions信息Fatal 非常严重的错误信息
-
Writing log information
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");or useLogger.Log(LogLevel.Info, "Sample Informational Message");Support formattingMyLogger.Fatal("Sample {0} error message", "Fetal");Try to use Nlog built-in formatting tools, Nlog do the optimization work
-
Configuration
The most basic configuration is the first step, openNLog.ConfigConfiguration file, add the following configuration<Targets> <Target Name="LogFile"XSi:Type="File"FileName="File.txt" />//Create a target that represents the configuration of the output log file</targets> <Rules> <Logger name="*"MinLevel="Info"WriteTo="LogFile" />//Set the log above the info level to be able to enter what is called the logfile target /* 1Here logger itself has a name, this name corresponds to the class name, which means that the class name can output the log, asConsoleApp1. Program 2. You can add final="true"property, which indicates that all subsequent logger for this specified name are invalid*/ </rules>in the second step, you can run the codeMulti-target configuration<targets><target name= "logfile" xsi:type= "File" filename= "file.txt"/> <Target Name="Console"XSi:Type="Console" />//Create a target indicating the output of log information with the console</targets> <Rules> <Logger name="*"MinLevel="Trace"WriteTo="LogFile" /><logger name= "*"minlevel=" Info "writeto=" console "/> //The configuration information above the info level is output to target named console </rules>
-
Packaging device
Asynchronous wrapper configuration<Targets> <Target Name="Asyncfile"XSi:Type="Asyncwrapper"> <Target Name="LogFile"XSi:Type="File"FileName="File.txt"/></target> </targets><rules><logger name= "*"minlevel=" Trace "writeto=" Asyncfile "/> </rules>There are many wrappers, on-demand self- examination
-
Layout
布局是用来格式化日志输出信息的 simple日志格式化 <target name="logfile" xsi:type="File" fileName="file.txt" layout="${date:format=yyyyMMddHHmmss} ${message} ${counter:increment=3:sequence=Layout:value=5}"/> 还有很多格式化写法,自行查阅
-
Subclass Inherits Log
public Demo1{ protected Logger Log { Get set } protected demo1 () {
Log = logmanager . getlogger (gettype (). fullname ) } public class Demo2: demo1{ public Demo2 () : base () { } }
C # Log plug-in Nlog basic use