当前位置:网站首页>. 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 !
边栏推荐
- 4k-hdmi optical transceiver 1 channel [email protected] Hdmi2.0 optical transceiver HDMI HD video optical transceiver
- First exposure! The only Alibaba cloud native security panorama behind the highest level in the whole domain
- 有向图D和E
- Tt-slam: dense monocular slam for flat environment (IEEE 2021)
- What should I do if a serious bug occurs within the scope of my own test and I am about to go online?
- Go write permissions to file writefile (FileName, data, 0644)?
- 支持HomeKit、NFC:智汀智能门锁SL1仅需要149元
- What are the criteria for judging the end of the test?
- Restcloud ETL resolves shell script parameterization
- &lt; Sicily&gt; 1000. number reversal
猜你喜欢

2-optical-2-electric cascaded optical fiber transceiver Gigabit 2-optical-2-electric optical fiber transceiver Mini embedded industrial mine intrinsic safety optical fiber transceiver

Homekit supports the matter protocol. What does this imply?

Hanyuan high tech USB2.0 optical transceiver USB2.0 optical fiber extender USB2.0 optical fiber transmitter USB2.0 interface to optical fiber

#云原生征文#深入了解Ingress

After the uncommitted transactions in the redo log buffer of MySQL InnoDB are persisted to the redo log, what happens if the transaction rollback occurs?

Go write permissions to file writefile (FileName, data, 0644)?

Architecture design methods in technical practice

Homekit and NFC support: smart Ting smart door lock SL1 only costs 149 yuan

腾讯的技术牛人们,是如何完成全面上云这件事儿的?

AAIG看全球6月刊(上)发布|AI人格真的觉醒了吗?NLP哪个细分方向最具社会价值?Get新观点新启发~
随机推荐
【深入理解TcaplusDB技术】单据受理之事务执行
Oracle中dbms_output.put_line怎么使用
在線文本過濾小於指定長度工具
The two 985 universities share the same president! School: true
R语言使用MatchIt包进行倾向性匹配分析(设置匹配方法为nearest,匹配倾向性评分最近的对照组和病例组,1:1配比)、使用match.data函数构建匹配后的样本集合
UI framework
Network foundation and framework
How to enable the SMS function of alicloud for crmeb knowledge payment
R language dplyr package arrange function sorts dataframe data and sorts dataframe data through multiple data columns (ascending sort by default)
RestCloud ETL解决shell脚本参数化
逆向调试入门-了解PE结构文件
R语言将距离矩阵输入给hclust函数进行层次聚类分析,使用cutree函数进行层次聚类簇的划分、参数k指定聚类簇的个数、给每个样本都分配了簇标签
Is there any discount for opening an account now? Is it safe to open a mobile account?
Analysis and solution of connection failure caused by MySQL using replicationconnection
Windows install MySQL
R language dplyr package mutate_ The all function multiplies all numeric columns (variables) in the dataframe by a fixed value to generate a new data column, and specifies a user-defined suffix name f
R语言dplyr包mutate_all函数将dataframe中的所有数值数值列(变量)乘以某一固定值并生成新的数据列,为新的数据列(变量)指定自定义后缀名称
理财产品长期是几年?新手最好买长期还是短期?
R language is used to build ordered multi classification logistic regression model, ordinal or. The display function obtains the summary statistical information of the ordered logistic regression mode
The filter function of dplyr package in R language filters the data rows containing the specified string in the specified data column of dataframe data based on the grepl function