当前位置:网站首页>How to integrate and use log4net logging plug-in in vs2019 class library
How to integrate and use log4net logging plug-in in vs2019 class library
2022-07-24 08:44:00 【Bird of paradise in the wind】
log4net brief introduction
log4net Currently, it is a very popular log plug-in .
log4net Kuo is Apache log4j In the framework of Microsoft .NET Implementation of the platform , It is a tool to help programmers output log information to various targets ( Console 、 file 、 Database etc. ) Tools for .
log4net yes Apache Software foundation Apache Logging Services Part of the project .Apache The logging service project is committed to providing cross language logging services for program debugging and auditing .
VS2019 Use in log4net, Three steps :
step 1: Integrate log4net Plug in to the project
open VS2019, New class library project :
In the project , open NulGet Program management pack , Search and install log4net:
step2: Create a new calling class MyLogHelper.
Create a new class in the project , The code is as follows :
using System;
// Here is the configuration log4net The location of the configuration file , Is the key , Most of it is because there is no pair configured here, resulting in no log Output
//ConfigFile Express log4net Location of profile .
[assembly: log4net.Config.XmlConfigurator(ConfigFile = "mylog4net.xml", ConfigFileExtension = "config", Watch = true)]
namespace MyLog4netHelper
{
public class MyLogHelper
{
//GetLogger Express log4net In profile logger In the label name attribute , Be consistent here Otherwise none log Output
private static readonly log4net.ILog Log = log4net.LogManager.GetLogger("RollingLogFileAppender");
// private static readonly log4net.ILog logError = log4net.LogManager.GetLogger("logerror");
/// <summary>
/// Record Info journal
/// </summary>
/// <param name="msg"></param>
/// <param name="ex"></param>
public static void Info(string msg)
{
if (Log.IsInfoEnabled)
{
Log.Info(msg);
}
}
/// <summary>
/// Record Fatal journal
/// </summary>
/// <param name="msg"></param>
/// <param name="ex"></param>
public static void Fatal(string msg)
{
if (Log.IsFatalEnabled)
{
Log.Fatal(msg);
}
}
/// <summary>
/// Record Debug journal
/// </summary>
/// <param name="msg"></param>
/// <param name="ex"></param>
public static void Debug(string msg)
{
if (Log.IsDebugEnabled)
{
Log.Debug(msg);
}
}
/// <summary>
/// Record Warn journal
/// </summary>
/// <param name="msg"></param>
/// <param name="ex"></param>
public static void Warn(string msg)
{
if (Log.IsWarnEnabled)
{
Log.Warn(msg);
}
}
/// <summary>
/// Record Error journal
/// </summary>
/// <param name="errorMsg"></param>
/// <param name="ex"></param>
public static void Error(string info, Exception ex = null)
{
if (!string.IsNullOrEmpty(info) && ex == null)
{
Log.ErrorFormat("【 Additional information 】 : {0}<br>", new object[] { info });
}
else if (!string.IsNullOrEmpty(info) && ex != null)
{
string errorMsg = BeautyErrorMsg(ex);
Log.ErrorFormat("【 Additional information 】 : {0}<br>{1}", new object[] { info, errorMsg });
}
else if (string.IsNullOrEmpty(info) && ex != null)
{
string errorMsg = BeautyErrorMsg(ex);
Log.Error(errorMsg);
}
}
/// <summary>
/// Beautify error messages
/// </summary>
/// <param name="ex"> abnormal </param>
/// <returns> error message </returns>
private static string BeautyErrorMsg(Exception ex)
{
string errorMsg = string.Format("【 Exception types 】:{0} <br>【 Abnormal information 】:{1} <br>【 Stack call 】:{2}", new object[] { ex.GetType().Name, ex.Message, ex.StackTrace });
errorMsg = errorMsg.Replace("\r\n", "<br>");
errorMsg = errorMsg.Replace(" Location ", "<strong style=\"color:red\"> Location </strong>");
return errorMsg;
}
}
}
step3 Configure and use :
First look at the configuration file :mylog4net.xml
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net" />
</configSections>
<log4net>
<root>
</root>
<logger name="RollingLogFileAppender">
<level value="ALL" />
<!--<appender-ref ref="RollingFileDebug" />-->
<appender-ref ref="RollingFileInfo" />
<appender-ref ref="RollingFileWarn" />
<appender-ref ref="RollingFileError" />
<appender-ref ref="RollingFileFatal" />
<appender-ref ref="Console" />
</logger>
<appender name="Console" type="log4net.Appender.ConsoleAppender">
<layout type="log4net.Layout.PatternLayout">
<!-- Pattern to output the caller's file name and line number -->
<conversionPattern value="%5level [%thread] (%file:%line) - %message%newline" />
</layout>
</appender>
<appender name="RollingFileDebug" type="log4net.Appender.RollingFileAppender">
<param name="File" value="MyLog/Debug/"/>
<param name="AppendToFile" value="true"/>
<param name="MaxSizeRollBackups" value="100"/>
<param name="StaticLogFileName" value="false"/>
<param name="DatePattern" value="yyyyMMdd".htm""/>
<param name="RollingStyle" value="Date"/>
<param name="MaxFileSize" value="10240" />
<layout type="log4net.Layout.PatternLayout">
<!--<conversionPattern value="[%date{HH:mm:ss fff}] %-5level - %message%newline" />-->
<param name="ConversionPattern" value="<HR COLOR=red>%n【 Log time 】:%d [%t] <BR>%n【 The level of logging 】:%-5p <BR>%n【 Exception class 】:%c [%x] <BR>%n%m <BR>%n <HR Size=1>" />
</layout>
<lockingmodel type="log4net.appender.fileappender+minimallock" />
<filter type="log4net.Filter.LevelRangeFilter">
<param name="LevelMin" value="Debug" />
<param name="LevelMax" value="Debug" />
</filter>
</appender>
<appender name="RollingFileInfo" type="log4net.Appender.RollingFileAppender">
<param name="File" value="MyLog/Info/"/>
<param name="AppendToFile" value="true"/>
<param name="MaxSizeRollBackups" value="100"/>
<param name="MaxFileSize" value="10240" />
<param name="StaticLogFileName" value="false"/>
<param name="DatePattern" value="yyyyMMdd".htm""/>
<param name="RollingStyle" value="Date"/>
<layout type="log4net.Layout.PatternLayout">
<param name="ConversionPattern" value="<HR COLOR=blue>%n Log time :%d [%t] <BR>%n The level of logging :%-5p <BR>%n Japan Records class :%c [%x] <BR>%n%m <BR>%n <HR Size=1>" />
</layout>
<lockingmodel type="log4net.appender.fileappender+minimallock" />
<filter type="log4net.Filter.LevelRangeFilter">
<param name="LevelMin" value="INFO" />
<param name="LevelMax" value="INFO" />
</filter>
</appender>
<appender name="RollingFileWarn" type="log4net.Appender.RollingFileAppender">
<param name="File" value="MyLog/Warn/"/>
<param name="AppendToFile" value="true"/>
<param name="MaxSizeRollBackups" value="100"/>
<param name="MaxFileSize" value="10240" />
<param name="StaticLogFileName" value="false"/>
<param name="DatePattern" value="yyyyMMdd".htm""/>
<param name="RollingStyle" value="Date"/>
<layout type="log4net.Layout.PatternLayout">
<param name="ConversionPattern" value="<HR COLOR=yellow>%n Log time :%d [%t] <BR>%n The level of logging :%-5p <BR>%n Japan Records class :%c [%x] <BR>%n%m <BR>%n <HR Size=1>" />
</layout>
<lockingmodel type="log4net.appender.fileappender+minimallock" />
<filter type="log4net.Filter.LevelRangeFilter">
<param name="LevelMin" value="WARN" />
<param name="LevelMax" value="WARN" />
</filter>
</appender>
<appender name="RollingFileError" type="log4net.Appender.RollingFileAppender">
<param name="File" value="MyLog/Error/"/>
<param name="AppendToFile" value="true"/>
<param name="MaxSizeRollBackups" value="10"/>
<param name="MaxFileSize" value="10240" />
<param name="StaticLogFileName" value="false"/>
<param name="DatePattern" value="yyyyMMdd".htm""/>
<param name="RollingStyle" value="Date"/>
<layout type="log4net.Layout.PatternLayout">
<param name="ConversionPattern" value="<HR COLOR=red>%n Log time :%d [%t] <BR>%n The level of logging :%-5p <BR>%n Japan Records class :%c [%x] <BR>%n%m <BR>%n <HR Size=1>" />
</layout>
<lockingmodel type="log4net.appender.fileappender+minimallock" />
<filter type="log4net.Filter.LevelRangeFilter">
<param name="LevelMin" value="ERROR" />
<param name="LevelMax" value="ERROR" />
</filter>
</appender>
<appender name="RollingFileFatal" type="log4net.Appender.RollingFileAppender">
<param name="File" value="MyLog/Fatal/"/>
<param name="AppendToFile" value="true"/>
<param name="MaxSizeRollBackups" value="10"/>
<param name="StaticLogFileName" value="false"/>
<param name="DatePattern" value="yyyyMMdd".htm""/>
<param name="MaxFileSize" value="10240" />
<param name="RollingStyle" value="Date"/>
<layout type="log4net.Layout.PatternLayout">
<param name="ConversionPattern" value="<HR COLOR=red>%n Log time :%d [%t] <BR>%n The level of logging :%-5p <BR>%n Japan Records class :%c [%x] <BR>%n%m <BR>%n <HR Size=1>" />
</layout>
<lockingmodel type="log4net.appender.fileappender+minimallock" />
<filter type="log4net.Filter.LevelRangeFilter">
<param name="LevelMin" value="FATAL" />
<param name="LevelMax" value="FATAL" />
</filter>
</appender>
</log4net>
</configuration>
The configuration file is placed in the root directory of the program that calls the class library .
It's easy to use :
MyLogHelper.Info("msg");
MyLogHelper.Fatal("msg");
MyLogHelper.Debug("msg");
MyLogHelper.Error("msg");
According to the configuration in the configuration file , Different types of log files will be written to the corresponding configuration file path , In specific use, you can customize the format you want in the configuration file according to your needs .
Last
Project structure :
matters needing attention :MyLogHelper The configuration file path written earlier in the class [assembly: log4net.Config.XmlConfigurator(ConfigFile = "mylog4net.xml", ConfigFileExtension = "config", Watch = true)] Don't get the corresponding file name wrong , To ensure that the configuration file can be read correctly .
log4net Plug ins are thread safe , Everything has been done inside the plug-in , Don't worry about locking in the process of use .( It is said that the lower version is not thread safe , Try to use the latest version )
边栏推荐
- SQL problem summary
- [Shangshui Shuo series] final rad New Literacies
- Typora提示【This beta version of Typora is expired, please download and install a newer version】的解决方案
- Bit.store, which has attracted much attention, is at a glance of the latest developments
- 「题解」蝙蝠侠的麻烦
- T-SQL query statement
- Larave uses sanctum for API authentication
- Typescript -- Generic
- C language - the difference between sizeof and strlen
- [Sheung Shui Shuo series] EE feedback details
猜你喜欢

Wargames NATAS (11-15) problem solving essay

Move protocol global health declaration, step into Web3 in sports

Musk responded that the brain has been uploaded to the cloud: already did it!

面试官:哥们Go语言的读写锁了解多少?

The beta version of move protocol is stable, and it is temporarily decided to expand the scale of the prize pool

Source code analysis of BlockingQueue (arraybq and linkedbq)

Is yuancosmos hype? Or the future

4、 Midway integrates swagger and supports JWT bearers

「题解」火神之友

0 threshold takes you to know two-point search
随机推荐
Bit.store, which has attracted much attention, is at a glance of the latest developments
JS built-in method
Ansible automatic operation and maintenance
Dynamic programming & backtracking various deformation problems
JMX Console 未授权访问漏洞
5、 Use of environment variables in midway
G1 (garbage first) collector
Typora prompt [this beta version of typora is expired, please download and install a new version]
C language - the difference between sizeof and strlen
M-dao creates a one-stop Dao platform, allowing hundreds of millions of players to join Dao space
脉脉网友出了道 Go 面试题,你能答对吗?
Larave uses sanctum for API authentication
How RPC callers implement asynchronous calls: completable future
JQ native write bullet frame mask layer
0 threshold takes you to know two-point search
Learn the rxjs operator
3587. 连通图(吉林大学考研机试题)
Install SQL Server database
Wargames NATAS (0-10) problem solving essay
Online lover