I explained how to use it before log4net To record logs, but recently I like another simple and easy-to-use logging framework NLog 。 The comparison between NLog and log4net is not discussed here. Interested friends can refer to Introduction to. NET Logging Tool and log4net vs. Nlog These two articles. This article mainly introduces how to use NLog in projects.
Installing NLog in Nuget
NLog can be installed directly using Nuget: PM > Install-Package Nlog
Use NLog
NLog is basically used in the same way as other log libraries, including five levels: Trace, Debug, Info, Error, Fatal
private static Logger logger = LogManager .GetCurrentClassLogger();
static
void Main( string [] args)
{
logger. Trace( "Trace Message" );
logger. Debug( "Debug Message" );
logger. Info( "Info Message" );
logger. Error( "Error Message" );
logger. Fatal( "Fatal Message" );
}
However, it provides many methods. Trace alone has 42 overload forms. Although powerful functions are a good thing, they also increase learning costs to some extent.
Configure NLog
After executing the above statement, there is actually no effect. Because we have not configured the log output path. This output path is generally configured in the configuration file (hard coding is also supported). NLog supports two configuration file formats
-
Configuration information is embedded in NET application standard *. exe.config or web.config file
-
Stored in a separate file, also known as a single format
The first method is more conventional, but I don't like this method because it is written together with other configurations unrelated to logs, which makes it inconvenient to share configurations in different projects. This section mainly introduces the independent file mode. NLog supports the following three file names: "NLog. config", "*. exe. nlog" and "NLog. dll. nlog". I prefer the first. No matter which one, its content is the same. A simple example is as follows:
< nlog
xmlns = " http://www.nlog-project.org/schemas/NLog.xsd "
xmlns:xsi = " http://www.w3.org/2001/XMLSchema-instance " >
< targets >
< target
name = " console "
xsi:type = " Console " />
< target
name = " debugger "
xsi:type = " Debugger "
layout = " ${date:format=HH\:mm\:ss.fff}: ${message} " />
< target
name = " error_file "
xsi:type = " File "
fileName = " ${basedir}/Logs/Error/${shortdate}/error.txt " maxArchiveFiles = " thirty "
layout = " ${longdate} | ${level:uppercase=false} | ${message} ${onexception:${exception:format=tostring} ${newline} ${stacktrace} ${newline} " />
</ targets >
< rules >
<!-- <logger name="*" writeTo="console" /> -->
< logger
name = " * "
minlevel = " Debug "
writeTo = " debugger " />
< logger
name = " * "
minlevel = " Error "
writeTo = " error_file " />
</ rules >
</ nlog >
It mainly includes two parts: Output target and Routing rule 。 Let's introduce them respectively.
Output target
Each target represents an output target, which mainly contains two attributes: name and type. Name is the name of the output template, which is used in the following routing rules, and type is the output type. Common examples are
-
Console Output to Console
-
Debugger output to
-
File Output to File
-
Mail output sent as mail
-
Network output to network address
-
Database output to database
When selecting a type, you need to configure the corresponding parameters. For example, if the output type is File, we need to configure the log path filename. Here are some variables that can be used (in curly braces). My example is:
fileName = " ${basedir}/Logs/Error/${shortdate}/error.txt "
The output log format is/Log/2014-10-01/err.txt. A folder is generated every day, which is very convenient.
Control of output format:
Sometimes, we need to control the output format of objects such as time and exception. They can be implemented by modifying the layout parameter. This part is relatively complicated and is not covered in this article. I will introduce it when I have time.
Reference example:
There are many ready-made examples on the Internet. It will save you a lot of time to refer to them directly instead of writing them from scratch. Here I simply list two examples. Readers are welcome to recommend them.
By the way, I also post a common configuration document here:
< nlog
xmlns = " http://www.nlog-project.org/schemas/NLog.xsd "
xmlns:xsi = " http://www.w3.org/2001/XMLSchema-instance " >
< targets >
<!-- Screen Print Message -->
< target
name = " console "
xsi:type = " ColoredConsole "
layout = " ${date:format=HH\:mm\:ss}> ${message} " />
<!-- VS output window -->
< target
name = " debugger "
xsi:type = " Debugger "
layout = " ${date:format=HH\:mm\:ss} | ${level:padding=-5} | ${message} " />
<!-- Save to File -->
< target
name = " error_file "
xsi:type = " File "
maxArchiveFiles = " thirty "
fileName = " ${basedir}/Logs/Error/${shortdate}/error.txt "
layout = " ${longdate} | ${level:uppercase=false:padding=-5} | ${message} ${onexception:${exception:format=tostring} ${newline} ${stacktrace} ${newline} " />
</ targets >
< rules >
<!-- <logger name="*" writeTo="console" /> -->
< logger
name = " * "
minlevel = " Debug "
writeTo = " debugger " />
< logger
name = " * "
minlevel = " Error "
writeTo = " error_file " />
</ rules >
</ nlog >
Routing rule
Routing rules are mainly used to match logs with output targets. They generally have the following attributes
-
Name - The name of the recorder (wildcard * is allowed)
-
Minlevel - The lowest level matching the log range
-
Maxlevel - The highest level matching the log range
-
Level - Matched single log level
-
Levels - A series of matching log levels, separated by commas.
-
WriteTo - A series of targets to which logs should be written when rules match, separated by commas.
It seems that there are several attributes, but in fact they are relatively simple to use. For example, my three previous rules are explained as follows:
< logger
name = " * "
writeTo = " console " /> Output all logs to the console
< logger
name = " * "
minlevel = " Debug "
writeTo = " debugger " /> take Debug Log output above level to Debugger in
< logger
name = " * "
minlevel = " Error "
writeTo = " error_file " /> take Error Log above level is output to file
In addition, NLOG supports the configuration of multiple routing rules, which is very convenient for our output.
Due to the limited space, the introduction here is brief. For more detailed configuration file settings, please refer to the official document: https://github.com/nlog/NLog/wiki/Configuration-file#configuration -file-locations
Simple packaging:
The usage of NLog has been listed previously. Although its use is not complicated, a simple wrapper can reduce the threshold of use, standardize the usage, and even facilitate the later switching of the log framework. In many cases, it is very necessary. Here is a simple package:
one class Logger two { three NLog. Logger logger; four
five private Logger(NLog.Logger logger) six { seven this .logger = logger; eight } nine
ten public Logger( string name) eleven : this (NLog.LogManager.GetLogger(name)) twelve { thirteen } fourteen
fifteen public static Logger Default { get ; private set ; } sixteen static Logger() seventeen { eighteen Default = new Logger(NLog.LogManager.GetCurrentClassLogger()); nineteen } twenty
twenty-one public void Debug( string msg, params object [] args) twenty-two { twenty-three logger. Debug(msg, args); twenty-four } twenty-five
twenty-six public void Debug( string msg, Exception err) twenty-seven { twenty-eight logger. Debug(msg, err); twenty-nine } thirty
thirty-one public void Info( string msg, params object [] args) thirty-two { thirty-three logger. Info(msg, args); thirty-four } thirty-five
thirty-six public void Info( string msg, Exception err) thirty-seven { thirty-eight logger. Info(msg, err); thirty-nine } forty
forty-one public void Trace( string msg, params object [] args) forty-two { forty-three logger. Trace(msg, args); forty-four } forty-five
forty-six public void Trace( string msg, Exception err) forty-seven { forty-eight logger. Trace(msg, err); forty-nine } fifty
fifty-one public void Error( string msg, params object [] args) fifty-two { fifty-three logger. Error(msg, args); fifty-four } fifty-five
fifty-six public void Error( string msg, Exception err) fifty-seven { fifty-eight logger. Error(msg, err); fifty-nine } sixty
sixty-one public void Fatal( string msg, params object [] args) sixty-two { sixty-three logger. Fatal(msg, args); sixty-four } sixty-five
sixty-six public void Fatal( string msg, Exception err) sixty-seven { sixty-eight logger. Fatal(msg, err); sixty-nine } seventy }
View Code
Although it is relatively simple, most simple scenarios are sufficient. If you want a more powerful package, you can consider Common. Logging , SimpleLoggingFacade And other molding libraries.
Third party viewing tools
Like log4net, NLog is also supported by some third-party log viewing tools. I have found two: Sentinel And Harvester 。 I didn't use these viewing tools in many places and didn't study them specifically. However, NLog supports DB output. It is more convenient and powerful to use SQL query after output to DB, but its real-time performance is poor.
Learning materials:
This article is just a quick introduction to NLOG, which is still in the peep through the bush stage. NLOG itself is very powerful. There are a series of articles in the garden that give a more in-depth introduction. Friends who need this can see:
http://www.cnblogs.com/dflying/category/78087.html
In addition, there are many well written introductory documents on the Internet, which can also be learned: