当前位置:网站首页>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 )
边栏推荐
- POI operation excel collation
- OpenCV中文文档4.0.0学习笔记(更新中……)
- 2022.7.11全盘题解
- Houdini 官方HDA SideFX Labs 安装
- [Shangshui Shuo series] final rad New Literacies
- 安装软件时提示【An error occurred while trying to create a file in the destination directory: 拒绝访问】的解决方法
- RPC中实现提供者信息变化后通知消费者
- 脉脉网友出了道 Go 面试题,你能答对吗?
- Look at the most influential infrastructure m-dao of Web3 through the current situation of Dao
- Relationship between fork and pipeline
猜你喜欢

Figure storage geabase

Learn the rxjs operator

Typora提示【This beta version of Typora is expired, please download and install a newer version】的解决方案

阻塞队列BlockingQueue 源码解析(ArrayBQ和LinkedBQ)

"Move to earn" motion metauniverse, move starts a new journey

2、 Encapsulation and tool classes for adding, deleting, modifying and checking in midway

Houdini 笔记

Hack the box - Introduction to networking module detailed Chinese tutorial

Dao race track is booming. What are the advantages of m-dao?

Cyclic multiple scatter
随机推荐
RPC调用方如何实现异步调用:CompletableFuture
Scatter chart - date
「题解」带分数
OpenCV中文文档4.0.0学习笔记(更新中……)
WordPress free theme: document, making reading more convenient
Okaleido tiger NFT is about to log in to binance NFT platform, and the era of NFT rights and interests is about to start
Typora prompt [this beta version of typora is expired, please download and install a new version]
阻塞队列BlockingQueue 源码解析(ArrayBQ和LinkedBQ)
Use the bark app to realize the process of pushing messages to mobile phones
Read and understand move2earn project - move
「题解」火神之友
Selenium webdriver page refresh
Hack the box - Introduction to networking module detailed Chinese tutorial
Porting boa server on imx6ull
Houdini 官方HDA SideFX Labs 安装
Golang implements sanggi diagram and analyzes user behavior trajectory
Learn the rxjs operator
3587. Connected graph (Jilin University postgraduate entrance examination machine test question)
Go: how to gracefully time out
Ubuntu20.04 install MySQL 5.7