Log4Net在.NET Fromework和.NET Core中的使用


  本文讨论的是在都需要使用Log4Net的前提下,因为.NET Core已经内置了日志服务,不使用Log4Net也是可以看到日志的.

  一、区别

  相同:

  1,都需要引用log4net.dll。

  不同:

  1,需要格式化日志输出方式的,它们中的Log4Net.config配置文件格式是不同的。

  2,.NET Core还需要引用Microsoft.Extensions.Logging.Log4Net.AspNetCore.dll。

  3,使用方式不同,.NET Framework一般是需要借助帮助类库的,.NET Core是可以直接使用依赖注入,也可以使用帮助类库。

  二、使用方式

  1,.NET Framework

  1 using log4net;
  2 using System;
  3 using System.Collections.Concurrent;
  4 using System.IO;
  5 using System.Reflection;
  6 using System.Xml;
  7 
  8 namespace MS.Quality.Component.Utility
  9 {
 10     /// 
 11     /// 日志帮助类
 12     /// 
 13     public class Log4NetUtility
 14     {
 15         private static readonly ConcurrentDictionary _loggers = new ConcurrentDictionary();
 16         /// 
 17         /// 获取记录器
 18         /// 
 19         /// 
 20         /// 
 21         private static ILog GetLogger(Type source)
 22         {
 23             if (_loggers.ContainsKey(source))
 24             {
 25                 return _loggers[source];
 26             }
 27             else
 28             {
 29                 ILog logger = LogManager.GetLogger(source);
 30                 SetLog4NetConfiguration();
 31                 _loggers.TryAdd(source, logger);
 32                 return logger;
 33             }
 34         }
 35 
 36         /// 
 37         /// 调试信息
 38         /// 
 39         /// 
 40         /// 
 41         public static void Debug(object source, string message)
 42         {
 43             Debug(source.GetType(), message);
 44         }
 45 
 46         /// 
 47         /// 调试信息
 48         /// 
 49         /// 
 50         /// 
 51         /// 
 52         public static void Debug(object source, string message, params object[] ps)
 53         {
 54             Debug(source.GetType(), string.Format(message, ps));
 55         }
 56 
 57         /// 
 58         /// 调试信息
 59         /// 
 60         /// 
 61         /// 
 62         public static void Debug(Type source, string message)
 63         {
 64             ILog logger = GetLogger(source);
 65             if (logger.IsDebugEnabled)
 66                 logger.Debug(message);
 67         }
 68         /// 
 69         /// 关键信息
 70         /// 
 71         /// 
 72         /// 
 73         public static void Info(object source, object message)
 74         {
 75             Info(source.GetType(), message);
 76         }
 77 
 78         /// 
 79         /// 关键信息
 80         /// 
 81         /// 
 82         /// 
 83         public static void Info(Type source, object message)
 84         {
 85             ILog logger = GetLogger(source);
 86             if (logger.IsInfoEnabled)
 87                 logger.Info(message);
 88         }
 89 
 90         /// 
 91         /// 警告信息
 92         /// 
 93         /// 
 94         /// 
 95         public static void Warn(object source, object message)
 96         {
 97             Warn(source.GetType(), message);
 98         }
 99 
100         /// 
101         /// 警告信息
102         /// 
103         /// 
104         /// 
105         public static void Warn(Type source, object message)
106         {
107             ILog logger = GetLogger(source);
108             if (logger.IsWarnEnabled)
109                 logger.Warn(message);
110         }
111 
112         /// 
113         /// 错误信息
114         /// 
115         /// 
116         /// 
117         public static void Error(object source, object message)
118         {
119             Error(source.GetType(), message);
120         }
121 
122         /// 
123         /// 错误信息
124         /// 
125         /// 
126         /// 
127         public static void Error(Type source, object message)
128         {
129             ILog logger = GetLogger(source);
130             if (logger.IsErrorEnabled)
131                 logger.Error(message);
132         }
133 
134         /// 
135         /// 失败信息
136         /// 
137         /// 
138         /// 
139         public static void Fatal(object source, object message)
140         {
141             Fatal(source.GetType(), message);
142         }
143 
144         /// 
145         /// 失败信息
146         /// 
147         /// 
148         /// 
149         public static void Fatal(Type source, object message)
150         {
151             ILog logger = GetLogger(source);
152             if (logger.IsFatalEnabled)
153                 logger.Fatal(message);
154         }
155 
156         /* Log a message object and exception */
157 
158         /// 
159         /// 调试信息
160         /// 
161         /// 
162         /// 
163         /// 
164         public static void Debug(object source, object message, Exception exception)
165         {
166             Debug(source.GetType(), message, exception);
167         }
168 
169         /// 
170         /// 调试信息
171         /// 
172         /// 
173         /// 
174         /// 
175         public static void Debug(Type source, object message, Exception exception)
176         {
177             GetLogger(source).Debug(message, exception);
178         }
179 
180         /// 
181         /// 关键信息
182         /// 
183         /// 
184         /// 
185         /// 
186         public static void Info(object source, object message, Exception exception)
187         {
188             Info(source.GetType(), message, exception);
189         }
190 
191         /// 
192         /// 关键信息
193         /// 
194         /// 
195         /// 
196         /// 
197         public static void Info(Type source, object message, Exception exception)
198         {
199             GetLogger(source).Info(message, exception);
200         }
201 
202         /// 
203         /// 警告信息
204         /// 
205         /// 
206         /// 
207         /// 
208         public static void Warn(object source, object message, Exception exception)
209         {
210             Warn(source.GetType(), message, exception);
211         }
212 
213         /// 
214         /// 警告信息
215         /// 
216         /// 
217         /// 
218         /// 
219         public static void Warn(Type source, object message, Exception exception)
220         {
221             GetLogger(source).Warn(message, exception);
222         }
223 
224         /// 
225         /// 错误信息
226         /// 
227         /// 
228         /// 
229         /// 
230         public static void Error(object source, object message, Exception exception)
231         {
232             Error(source.GetType(), message, exception);
233         }
234 
235         /// 
236         /// 错误信息
237         /// 
238         /// 
239         /// 
240         /// 
241         public static void Error(Type source, object message, Exception exception)
242         {
243             GetLogger(source).Error(message, exception);
244         }
245 
246         /// 
247         /// 失败信息
248         /// 
249         /// 
250         /// 
251         /// 
252         public static void Fatal(object source, object message, Exception exception)
253         {
254             Fatal(source.GetType(), message, exception);
255         }
256 
257         /// 
258         /// 失败信息
259         /// 
260         /// 
261         /// 
262         /// 
263         public static void Fatal(Type source, object message, Exception exception)
264         {
265             GetLogger(source).Fatal(message, exception);
266         }
267         private static void SetLog4NetConfiguration()
268         {
269             var repo = LogManager.CreateRepository(
270                 Assembly.GetEntryAssembly(), typeof(log4net.Repository.Hierarchy.Hierarchy));
271             log4net.Config.XmlConfigurator.Configure(repo, new FileInfo("Log4Net.config"));
272         }
273     }
274 }
Log4NetUtility
 1 <?xml version="1.0" encoding="utf-8"?>
 2 
 3   
 4     
 5     
"log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/> 6 7 8 9 10 "Log4Net_INFO" type="log4net.Appender.RollingFileAppender"> 11 12 "Log/Info/"/> 13 14 "true"/> 15 "Date"/> 16 17 "yyyy-MM/yyyy-MM-dd".log"" /> 18 19 "false"/> 20 21 "log4net.Appender.FileAppender+MinimalLock" /> 22 23 "log4net.Layout.PatternLayout"> 24 36
"[Header] "/> 37
"[Footer] "/> 38 39 "%date ThreadID:[%thread] Level:%-5level Logger:%logger property:[%property{NDC}] %nMessage:%message%newline" /> 40 41 "log4net.Filter.LevelRangeFilter"> 42 "Debug" /> 43 "Warn" /> 44 45 46 47 "Log4Net_ERROR" type="log4net.Appender.RollingFileAppender"> 48 "Log/Error/"/> 49 "true"/> 50 "Date"/> 51 "yyyy-MM/yyyy-MM-dd".log"" /> 52 "false"/> 53 "log4net.Appender.FileAppender+MinimalLock" /> 54 "log4net.Layout.PatternLayout"> 55
"[Header] "/> 56
"[Footer] "/> 57 58 "%date ThreadID:[%thread] Level:%-5level Logger:%logger property:[%property{NDC}] %nMessage:%message%newline" /> 59 60 "log4net.Filter.LevelRangeFilter"> 61 "ERROR" /> 62 "FATAL" /> 63 64 65 66 67 "ALL"/> 68 ref ref="Log4Net_INFO" /> 69 ref ref="Log4Net_ERROR" /> 70 71 72 73 74
Log4Net.config

   Log4NetUtility.Info(this, "guid:" + guid);

  2,.NET Core

  a,使用Log4NetUtility.cs帮助类库,使用方式同.NET Framework,Log4Net.config同上

  b,使用依赖注入方式

 1 <?xml version="1.0" encoding="utf-8"?>
 2 
 3   
 4   "Log4Net_INFO" type="log4net.Appender.RollingFileAppender">
 5     
 6     "Log/Info/"/>
 7     
 8     "true"/>
 9     "Date"/>
10     
11     "yyyy-MM/yyyy-MM-dd".log"" />
12     
13     "false"/>
14     
15     "log4net.Appender.FileAppender+MinimalLock" />
16     
17     "log4net.Layout.PatternLayout">
18       
30       
"[Header] "/> 31
"[Footer] "/> 32 33 "%date ThreadID:[%thread] Level:%-5level Logger:%logger property:[%property{NDC}] %nMessage:%message%newline" /> 34 35 "log4net.Filter.LevelRangeFilter"> 36 "Debug" /> 37 "Warn" /> 38 39 40 41 "Log4Net_ERROR" type="log4net.Appender.RollingFileAppender"> 42 "Log/Error/"/> 43 "true"/> 44 "Date"/> 45 "yyyy-MM/yyyy-MM-dd".log"" /> 46 "false"/> 47 "log4net.Appender.FileAppender+MinimalLock" /> 48 "log4net.Layout.PatternLayout"> 49
"[Header] "/> 50
"[Footer] "/> 51 52 "%date ThreadID:[%thread] Level:%-5level Logger:%logger property:[%property{NDC}] %nMessage:%message%newline" /> 53 54 "log4net.Filter.LevelRangeFilter"> 55 "ERROR" /> 56 "FATAL" /> 57 58 59 60 61 "ALL"/> 62 ref ref="Log4Net_INFO" /> 63 ref ref="Log4Net_ERROR" /> 64 65 66
Log4Net.config

  Programe.cs:

.ConfigureLogging(logging =>
{
    logging.AddFilter("System", LogLevel.Warning);//过滤系统日志
    logging.AddFilter("Microsoft", LogLevel.Warning);
    logging.AddLog4Net("Log4Net.config");//Log4Net.config文件路径
})

 日志Level过滤也可以在appconfigs.json中进行配置:

 1 {
 2   "Logging": {
 3     "LogLevel": { // No provider, LogLevel applies to all the enabled providers.
 4       "Default": "Information",
 5       "Microsoft": "Warning",
 6       "Microsoft.Hosting.Lifetime": "Warning"
 7     },
 8     "Debug": { // Debug provider.
 9       "LogLevel": {
10         "Default": "Information" // Overrides preceding LogLevel:Default setting.
11       }
12     },
13     "Console": {
14       "IncludeScopes": true,
15       "LogLevel": {
16         "Microsoft.AspNetCore.Mvc.Razor.Internal": "Warning",
17         "Microsoft.AspNetCore.Mvc.Razor.Razor": "Debug",
18         "Microsoft.AspNetCore.Mvc.Razor": "Error",
19         "Default": "Information"
20       }
21     },
22     "EventSource": {
23       "LogLevel": {
24         "Microsoft": "Information"
25       }
26     },
27     "EventLog": {
28       "LogLevel": {
29         "Microsoft": "Information"
30       }
31     },
32     "AzureAppServicesFile": {
33       "IncludeScopes": true,
34       "LogLevel": {
35         "Default": "Warning"
36       }
37     },
38     "AzureAppServicesBlob": {
39       "IncludeScopes": true,
40       "LogLevel": {
41         "Microsoft": "Information"
42       }
43     },
44     "ApplicationInsights": {
45       "LogLevel": {
46         "Default": "Information"
47       }
48     }
49   }
50 }
appsettings.json