dotnet core 6.0 配置使用log4net

开发工具 vs2022社区版,.net 6.0

一、NuGet添加 Microsoft.Extensions.Logging.Log4Net.AspNetCore

二、在项目根目录添加log4net.config



	
		
		
		
		
		
		
		
		
			
		
	
	
				
		
	

 

三、添加LogHelper类

public class LogHelp
    {
        public static readonly log4net.ILog loginfo = log4net.LogManager.GetLogger("loginfo");
       
        private static object thisLock = new object();
        /// 
        /// 将内容记录到info
        /// 客户端调用写法如下:LogHelp.WriteLog("123");  
        /// 
        /// 
        /// 
        public static void WriteLog(string info, bool realWriteLog = true)
        {
            lock (thisLock)
            {
                if (realWriteLog)
                {
                    if (loginfo.IsInfoEnabled)
                    {
                        loginfo.Info(info);
                    }
                }
            }
        }


        /// 
        /// 将内容记录到error
        /// 客户端调用写法如下:LogHelp.WriteLog("456",new Exception ("错误"));
        /// 
        /// 
        /// 
        /// 
        public static void WriteLog(string info, Exception se, bool realWriteLog = true)
        {
            lock (thisLock)
            {
                if (realWriteLog)
                {
                    if (loginfo.IsInfoEnabled)
                    {
                        loginfo.Info(info,se);
                    }
                }
            }
        }
        /// 
        /// 日志保留多少天
        /// 
        /// 
        /// 
        public static void SaveLogDays(string logFilePath, int saveDays)
        {
            lock (thisLock)
            {
                string[] logFileName = Directory.GetFiles(logFilePath);
                if (logFileName.Count() > saveDays)
                {
                    File.Delete(logFileName[0]);
                }
            }
        }
    }

四、在appsetting.json中添加

"Log4NetCore": {
    "Name": "MyLog",
    "LoggerRepository": "Fantastic",
    "OverrideCriticalLevelWith": "Critical",
    "Watch": false,
    "UseWebOrAppConfig": false    
  }

五、在Program.cs文件中添加

builder.Logging.AddLog4Net("log4net.config");

 

六、调用loghelp

LogHelp.WriteLog("msg");
LogHelp.WriteLog("msg",new Exception("testLog"));

输出结果展示:

 dotnet core 6.0 配置使用log4net_第1张图片

 

 

 

你可能感兴趣的:(Asp.net,core,C#,宝塔面板,asp.net,core)