当前位置:网站首页>. Net how to use log framework NLog

. Net how to use log framework NLog

2022-06-23 13:23:00 Yisu cloud

.Net How to use the log framework NLog

This article mainly explains “.Net How to use the log framework NLog”, The explanation in the text is simple and clear , Easy to learn and understand , Next, please follow Xiaobian's ideas and go deeper slowly , Study and learn together “.Net How to use the log framework NLog” Well !

stay Nuget Install in NLog

NLog You can use it directly Nuget install :PM > Install-Package Nlog

Use NLog

NLog Is basically the same as other Log The library is almost , It is divided into Trace、Debug、Info、Error、Fatal Five levels

    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");    }

But it provides a lot of methods , light Trace There is 42 Heavy duty . Although powerful events are good , But it also increases the learning cost to some extent .

To configure NLog

After executing the above statement , In fact, it has no effect . Because we haven't configured the log output path yet . This output path is usually configured in the configuration file ( Hard coding is also supported ),NLog Two configuration file formats are supported

  • Configuration information is embedded in .NET Application standard *.exe.config perhaps web.config In the document

  • Saved in a separate file , Also called single format

The first one is more conventional , But I don't like this way , Because it is written together with other log independent configurations , It is not convenient to share configurations among different projects . Here we mainly introduce the way of independent files .NLog Configuration files with the following three file names are supported :"NLog.config"、"*.exe.nlog" and "NLog.dll.nlog", I prefer the first one . Either way , The 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="30"                        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 consists of two parts : Output target target and Routing rules rule. Let's introduce them respectively .

Output target target

Every target Represents an output target , It mainly contains two properties :name and type.name Is the name of the output template , Use in the following routing rules ,type Is the output type , Common are

  • Console         Output to console

  • Debugger     Output to

  • File         output to a file

  • Mail         The output is sent by mail

  • Network         Output to network address

  • Database         Output to database

When choosing a certain type , You also need to configure the corresponding parameters . If the output type is File when , We need to configure the log path filename, Here are some variables that can be used ( Inside the curly brackets ), My example here :

fileName="${basedir}/Logs/Error/${shortdate}/error.txt"

The output log format is /Log/2014-10-01/err.txt     Generate a folder every day , Very convenient .

Control of output format :

sometimes , We need time to 、 The output format of these objects, such as exceptions, is controlled . They can be modified layout Parameter to implement . This part is relatively complicated , Beyond the scope of this article , I'd like to make a special introduction if I have time .

By the way, I also post a configuration document that I often use :

<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="30"                        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 rules rule

Routing rules are mainly used to match logs with output targets , It generally has the following properties

  • name - Name of recorder ( Wildcards are allowed *)

  • minlevel - Match the lowest level of log range

  • maxlevel - Match the highest level of log range

  • level - Matching single log level

  • levels - A series of matching log levels , Separated by commas .

  • writeTo - A set of targets that the log should be written to when the rules match , Separated by commas .

There seem to be several properties , In fact, it is relatively simple to use , For example, my previous three rules are explained as follows :

    <logger name="*" writeTo="console" />     Output all logs to the console     <logger name="*" minlevel="Debug" writeTo="debugger" />             take Debug Logs above level are output to Debugger in     <logger name="*" minlevel="Error" writeTo="error_file" />         take Error Logs above level are output to a file 

in addition ,NLOG Support to configure multiple routing rules , It is very convenient for our output .

Simple encapsulation :

We have already listed NLog How to use , Although its use is not miscellaneous , But a simple Wrapper It can lower the threshold of use , Standardize the way of use , It is even convenient to switch the logging framework later , It is very necessary in many cases . Here is a simple package :

    class Logger    {        NLog.Logger logger;        private Logger(NLog.Logger logger)        {            this.logger = logger;        }        public Logger(string name)            :this(NLog.LogManager.GetLogger(name))        {        }        public static Logger Default { get; private set; }        static Logger()        {            Default = new Logger(NLog.LogManager.GetCurrentClassLogger());        }        public void Debug(string msg, params object[] args)        {            logger.Debug(msg, args);        }        public void Debug(string msg, Exception err)        {            logger.Debug(msg, err);        }        public void Info(string msg, params object[] args)        {            logger.Info(msg, args);        }        public void Info(string msg, Exception err)        {            logger.Info(msg, err);        }        public void Trace(string msg, params object[] args)        {            logger.Trace(msg, args);        }        public void Trace(string msg, Exception err)        {            logger.Trace(msg, err);        }        public void Error(string msg, params object[] args)        {            logger.Error(msg, args);        }        public void Error(string msg, Exception err)        {            logger.Error(msg, err);        }        public void Fatal(string msg, params object[] args)        {            logger.Fatal(msg, args);        }        public void Fatal(string msg, Exception err)        {            logger.Fatal(msg, err);        }    }

Thank you for reading , That's all “.Net How to use the log framework NLog” Content. , After learning this article , I'm sure you're right .Net How to use the log framework NLog I have a deeper understanding of this problem , The specific use needs to be verified by practice . This is billion speed cloud , Xiaobian will push you articles with more relevant knowledge points , Welcome to your attention !

原网站

版权声明
本文为[Yisu cloud]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/174/202206231247396630.html

随机推荐