当前位置:网站首页>. 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 !
边栏推荐
- Dataset之GermanCreditData:GermanCreditData数据集的简介、下载、使用方法之详细攻略
- R语言dplyr包filter函数过滤dataframe数据中指定数据列的内容包含指定字符串的数据行、基于grepl函数
- First exposure! The only Alibaba cloud native security panorama behind the highest level in the whole domain
- 16 channel HD-SDI optical transceiver multi channel HD-SDI HD video optical transceiver 16 channel 3g-sdi HD audio video optical transceiver
- AssetBundle resource management
- What should I do if a serious bug occurs within the scope of my own test and I am about to go online?
- React query tutorial ④ - cache status and debugging tools
- Broadcast level E1 to aes-ebu audio codec E1 to stereo audio XLR codec
- "Four highs" of data midrange stability | startdt Tech Lab 18
- R语言使用MASS包的polr函数构建有序多分类logistic回归模型、使用exp函数和coef函数获取模型中每个变量(自变量改变一个单位)对应的优势比(odds ratio)
猜你喜欢

First exposure! The only Alibaba cloud native security panorama behind the highest level in the whole domain

Unity learning day14 -- collaboration and WWW

Configure SSH Remote Login for H3C switch

4E1 PDH optical transceiver 19 inch rack type single fiber transmission 20km E1 interface optical network optical transceiver

Broadcast level E1 to aes-ebu audio codec E1 to stereo audio XLR codec

Network foundation and framework

New project, how to ensure the coverage of the test?

华三交换机配置SSH远程登录

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

Androd Gradle模块依赖替换如何使用
随机推荐
Cloud native essay deep understanding of ingress
Unity learning day14 -- collaboration and WWW
Qunhui 10 Gigabit network configuration and test
Ablebits Ultimate Suite for Excel
Tuikit audio and video low code solution navigation page
You call this shit MQ?
Go写文件的权限 WriteFile(filename, data, 0644)?
Has aaig really awakened its AI personality after reading the global June issue (Part 1)? Which segment of NLP has the most social value? Get new ideas and inspiration ~
Is it safe for flush to open an account online? What should we pay attention to
AAIG看全球6月刊(上)发布|AI人格真的觉醒了吗?NLP哪个细分方向最具社会价值?Get新观点新启发~
R language uses the multinom function of NNET package to build a disordered multi classification logistic regression model, uses regression coefficients and their standard errors to calculate the valu
R语言dplyr包filter函数过滤dataframe数据中指定数据列的内容包含指定字符串的数据行、基于grepl函数
理财产品长期是几年?新手最好买长期还是短期?
Germancreditdata of dataset: a detailed introduction to the introduction, download and use of germancreditdata dataset
TUIKit 音视频低代码解决方案导航页
If there is a problem with minority browsers, do you need to do a compatibility test?
R language uses the polR function of mass package to build an ordered multi classification logistic regression model, and uses the summary function to obtain the summary statistical information of the
那些技术实战中的架构设计方法
腾讯的技术牛人们,是如何完成全面上云这件事儿的?
Network foundation and framework