NetStandard類庫實現Log4Net集成


前面都是Log4Net集成到NetCore項目中,集成到NetStandard類庫還是第一次,所以記錄一下

小提示:NetStandard要想同時被NetCore和NetFramework調用,需要在項目右鍵編輯xxxx.csproj, 然后打開項目編輯

修改保存后會重新生成加載項目,選確定就行了

上面是前話,下面直接進入正題

1、需要添加的NetStandard類庫右鍵----管理Nuget程序包,選擇log4net包添加到類庫中

2、類庫下添加一個應用程序配置文件,名字隨意,我這里用的是log4net.config

3、log4net.config配置文件內容

  1 <?xml version="1.0" encoding="utf-8" ?>
  2 <configuration>
  3   <configSections>
  4     <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
  5   </configSections>
  6   <log4net>
  7     <!--根配置-->
  8     <root>
  9       <!--日志級別:可選值: ERROR > WARN > INFO > DEBUG -->
 10       <level value="FATAL" />
 11       <level value="ERROR"/>
 12       <level value="WARN"/>
 13       <level value="INFO"/>
 14       <level value="DEBUG"/>
 15       <appender-ref ref="FatalLog" />
 16       <appender-ref ref="ErrorLog" />
 17       <appender-ref ref="WarnLog" />
 18       <appender-ref ref="InfoLog" />
 19       <appender-ref ref="DebugLog" />
 20     </root>
 21 
 22     <!-- 錯誤 Fatal.log-->
 23     <appender name="FatalLog" type="log4net.Appender.RollingFileAppender">
 24       <!--目錄路徑,可以是相對路徑或絕對路徑-->
 25       <param name="File" value="Logs"/>
 26       <!--文件名,按日期生成文件夾-->
 27       <param name="DatePattern" value="/yyyy-MM-dd/&quot;Fatal.log&quot;"/>
 28       <!--追加到文件-->
 29       <appendToFile value="true"/>
 30       <!--創建日志文件的方式,可選值:Date[日期],文件大小[Size],混合[Composite]-->
 31       <rollingStyle value="Composite"/>
 32       <!--寫到一個文件-->
 33       <staticLogFileName value="false"/>
 34       <!--單個文件大小。單位:KB|MB|GB-->
 35       <maximumFileSize value="200MB"/>
 36       <!--最多保留的文件數,設為"-1"則不限-->
 37       <maxSizeRollBackups value="-1"/>
 38       <!--日志格式-->
 39       <layout type="log4net.Layout.PatternLayout">
 40         <param name="ConversionPattern" value="時間:%date 描述:%message 異常:%exception  %n" />
 41       </layout>
 42       <filter type="log4net.Filter.LevelRangeFilter">
 43         <param name="LevelMin" value="FATAL" />
 44         <param name="LevelMax" value="FATAL" />
 45       </filter>
 46     </appender>
 47     
 48     <!-- 錯誤 Error.log-->
 49     <appender name="ErrorLog" type="log4net.Appender.RollingFileAppender">
 50       <!--目錄路徑,可以是相對路徑或絕對路徑-->
 51       <param name="File" value="Logs"/>
 52       <!--文件名,按日期生成文件夾-->
 53       <param name="DatePattern" value="/yyyy-MM-dd/&quot;Error.log&quot;"/>
 54       <!--追加到文件-->
 55       <appendToFile value="true"/>
 56       <!--創建日志文件的方式,可選值:Date[日期],文件大小[Size],混合[Composite]-->
 57       <rollingStyle value="Composite"/>
 58       <!--寫到一個文件-->
 59       <staticLogFileName value="false"/>
 60       <!--單個文件大小。單位:KB|MB|GB-->
 61       <maximumFileSize value="200MB"/>
 62       <!--最多保留的文件數,設為"-1"則不限-->
 63       <maxSizeRollBackups value="-1"/>
 64       <!--日志格式-->
 65       <layout type="log4net.Layout.PatternLayout">
 66         <param name="ConversionPattern" value="時間:%date 描述:%message 異常:%exception  %n" />
 67       </layout>
 68       <filter type="log4net.Filter.LevelRangeFilter">
 69         <param name="LevelMin" value="ERROR" />
 70         <param name="LevelMax" value="ERROR" />
 71       </filter>
 72     </appender>
 73 
 74     <!-- 警告 Warn.log-->
 75     <appender name="WarnLog" type="log4net.Appender.RollingFileAppender">
 76       <!--目錄路徑,可以是相對路徑或絕對路徑-->
 77       <param name="File" value="Logs"/>
 78       <!--文件名,按日期生成文件夾-->
 79       <param name="DatePattern" value="/yyyy-MM-dd/&quot;Warn.log&quot;"/>
 80       <!--追加到文件-->
 81       <appendToFile value="true"/>
 82       <!--創建日志文件的方式,可選值:Date[日期],文件大小[Size],混合[Composite]-->
 83       <rollingStyle value="Composite"/>
 84       <!--寫到一個文件-->
 85       <staticLogFileName value="false"/>
 86       <!--單個文件大小。單位:KB|MB|GB-->
 87       <maximumFileSize value="200MB"/>
 88       <!--最多保留的文件數,設為"-1"則不限-->
 89       <maxSizeRollBackups value="-1"/>
 90       <!--日志格式-->
 91       <layout type="log4net.Layout.PatternLayout">
 92         <param name="ConversionPattern" value="時間:%date 描述:%message %n" />
 93       </layout>
 94       <filter type="log4net.Filter.LevelRangeFilter">
 95         <param name="LevelMin" value="WARN" />
 96         <param name="LevelMax" value="WARN" />
 97       </filter>
 98     </appender>
 99 
100     <!-- 信息 Info.log-->
101     <appender name="InfoLog" type="log4net.Appender.RollingFileAppender">
102       <!--目錄路徑,可以是相對路徑或絕對路徑-->
103       <param name="File" value="Logs"/>
104       <!--文件名,按日期生成文件夾-->
105       <param name="DatePattern" value="/yyyy-MM-dd/&quot;Info.log&quot;"/>
106       <!--追加到文件-->
107       <appendToFile value="true"/>
108       <!--創建日志文件的方式,可選值:Date[日期],文件大小[Size],混合[Composite]-->
109       <rollingStyle value="Composite"/>
110       <!--寫到一個文件-->
111       <staticLogFileName value="false"/>
112       <!--單個文件大小。單位:KB|MB|GB-->
113       <maximumFileSize value="200MB"/>
114       <!--最多保留的文件數,設為"-1"則不限-->
115       <maxSizeRollBackups value="-1"/>
116       <!--日志格式-->
117       <layout type="log4net.Layout.PatternLayout">
118         <param name="ConversionPattern" value="時間:%date 描述:%message %n" />
119       </layout>
120       <filter type="log4net.Filter.LevelRangeFilter">
121         <param name="LevelMin" value="INFO" />
122         <param name="LevelMax" value="INFO" />
123       </filter>
124     </appender>
125 
126     <!-- 調試 Debug.log-->
127     <appender name="DebugLog" type="log4net.Appender.RollingFileAppender">
128       <!--目錄路徑,可以是相對路徑或絕對路徑-->
129       <param name="File" value="Logs"/>
130       <!--文件名,按日期生成文件夾-->
131       <param name="DatePattern" value="/yyyy-MM-dd/&quot;Debug.log&quot;"/>
132       <!--追加到文件-->
133       <appendToFile value="true"/>
134       <!--創建日志文件的方式,可選值:Date[日期],文件大小[Size],混合[Composite]-->
135       <rollingStyle value="Composite"/>
136       <!--寫到一個文件-->
137       <staticLogFileName value="false"/>
138       <!--單個文件大小。單位:KB|MB|GB-->
139       <maximumFileSize value="200MB"/>
140       <!--最多保留的文件數,設為"-1"則不限-->
141       <maxSizeRollBackups value="-1"/>
142       <!--日志格式-->
143       <layout type="log4net.Layout.PatternLayout">
144         <param name="ConversionPattern" value="時間:%date 描述:%message 異常:%exception  %newline" />
145       </layout>
146       <filter type="log4net.Filter.LevelRangeFilter">
147         <param name="LevelMin" value="DEBUG" />
148         <param name="LevelMax" value="DEBUG" />
149       </filter>
150     </appender>
151 
152   </log4net>
153 </configuration>
View Code

這里配置會在bin/log下生成一個時間文件夾,文件夾有五個文件,分別是debug,info,warn,error,fatal,根據不同的錯誤級別寫在不同的文件內。log4Net的具體配置請自行百度

4、添加自定義Logger類

  1 using log4net;
  2 using System;
  3 using System.Reflection;
  4 
  5 [assembly: log4net.Config.XmlConfigurator(ConfigFile = "log4net.config", Watch = true)]
  6 namespace FiiiCoin.Utility
  7 {
  8     public sealed class Logger
  9     {
 10         #region [ 單例模式 ]
 11 
 12         private static Logger logger;
 13         private static readonly log4net.ILog _Logger4net = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
 14 
 15         /// <summary>  
 16         /// 無參私有構造函數  
 17         /// </summary>  
 18         private Logger()
 19         {
 20         }
 21 
 22         /// <summary>  
 23         /// 得到單例  
 24         /// </summary>  
 25         public static Logger Singleton
 26         {
 27             get
 28             {
 29                 if (logger == null)
 30                 {
 31                     logger = new Logger();
 32                 }
 33                 return logger;
 34             }
 35         }
 36 
 37         #endregion  
 38 
 39         #region [ 參數 ]
 40 
 41         public bool IsDebugEnabled
 42         {
 43             get { return _Logger4net.IsDebugEnabled; }
 44         }
 45         public bool IsInfoEnabled
 46         {
 47             get { return _Logger4net.IsInfoEnabled; }
 48         }
 49         public bool IsWarnEnabled
 50         {
 51             get { return _Logger4net.IsWarnEnabled; }
 52         }
 53         public bool IsErrorEnabled
 54         {
 55             get { return _Logger4net.IsErrorEnabled; }
 56         }
 57         public bool IsFatalEnabled
 58         {
 59             get { return _Logger4net.IsFatalEnabled; }
 60         }
 61 
 62         #endregion  
 63 
 64         #region [ 接口方法 ]
 65 
 66         #region [ Debug ]
 67 
 68         public void Debug(string message)
 69         {
 70             if (this.IsDebugEnabled)
 71             {
 72                 this.Log(LogLevel.Debug, message);
 73             }
 74         }
 75 
 76         public void Debug(string message, Exception exception)
 77         {
 78             if (this.IsDebugEnabled)
 79             {
 80                 this.Log(LogLevel.Debug, message, exception);
 81             }
 82         }
 83 
 84         public void DebugFormat(string format, params object[] args)
 85         {
 86             if (this.IsDebugEnabled)
 87             {
 88                 this.Log(LogLevel.Debug, format, args);
 89             }
 90         }
 91 
 92         public void DebugFormat(string format, Exception exception, params object[] args)
 93         {
 94             if (this.IsDebugEnabled)
 95             {
 96                 this.Log(LogLevel.Debug, string.Format(format, args), exception);
 97             }
 98         }
 99 
100         #endregion
101 
102         #region [ Info ]
103 
104         public void Info(string message)
105         {
106             if (this.IsInfoEnabled)
107             {
108                 this.Log(LogLevel.Info, message);
109             }
110         }
111 
112         public void Info(string message, Exception exception)
113         {
114             if (this.IsInfoEnabled)
115             {
116                 this.Log(LogLevel.Info, message, exception);
117             }
118         }
119 
120         public void InfoFormat(string format, params object[] args)
121         {
122             if (this.IsInfoEnabled)
123             {
124                 this.Log(LogLevel.Info, format, args);
125             }
126         }
127 
128         public void InfoFormat(string format, Exception exception, params object[] args)
129         {
130             if (this.IsInfoEnabled)
131             {
132                 this.Log(LogLevel.Info, string.Format(format, args), exception);
133             }
134         }
135 
136         #endregion
137 
138         #region  [ Warn ]
139 
140         public void Warn(string message)
141         {
142             if (this.IsWarnEnabled)
143             {
144                 this.Log(LogLevel.Warn, message);
145             }
146         }
147 
148         public void Warn(string message, Exception exception)
149         {
150             if (this.IsWarnEnabled)
151             {
152                 this.Log(LogLevel.Warn, message, exception);
153             }
154         }
155 
156         public void WarnFormat(string format, params object[] args)
157         {
158             if (this.IsWarnEnabled)
159             {
160                 this.Log(LogLevel.Warn, format, args);
161             }
162         }
163 
164         public void WarnFormat(string format, Exception exception, params object[] args)
165         {
166             if (this.IsWarnEnabled)
167             {
168                 this.Log(LogLevel.Warn, string.Format(format, args), exception);
169             }
170         }
171 
172         #endregion
173 
174         #region  [ Error ]
175 
176         public void Error(string message)
177         {
178             if (this.IsErrorEnabled)
179             {
180                 this.Log(LogLevel.Error, message);
181             }
182         }
183 
184         public void Error(string message, Exception exception)
185         {
186             if (this.IsErrorEnabled)
187             {
188                 this.Log(LogLevel.Error, message, exception);
189             }
190         }
191 
192         public void ErrorFormat(string format, params object[] args)
193         {
194             if (this.IsErrorEnabled)
195             {
196                 this.Log(LogLevel.Error, format, args);
197             }
198         }
199 
200         public void ErrorFormat(string format, Exception exception, params object[] args)
201         {
202             if (this.IsErrorEnabled)
203             {
204                 this.Log(LogLevel.Error, string.Format(format, args), exception);
205             }
206         }
207         #endregion
208 
209         #region  [ Fatal ]
210 
211         public void Fatal(string message)
212         {
213             if (this.IsFatalEnabled)
214             {
215                 this.Log(LogLevel.Fatal, message);
216             }
217         }
218 
219         public void Fatal(string message, Exception exception)
220         {
221             if (this.IsFatalEnabled)
222             {
223                 this.Log(LogLevel.Fatal, message, exception);
224             }
225         }
226 
227         public void FatalFormat(string format, params object[] args)
228         {
229             if (this.IsFatalEnabled)
230             {
231                 this.Log(LogLevel.Fatal, format, args);
232             }
233         }
234 
235         public void FatalFormat(string format, Exception exception, params object[] args)
236         {
237             if (this.IsFatalEnabled)
238             {
239                 this.Log(LogLevel.Fatal, string.Format(format, args), exception);
240             }
241         }
242         #endregion
243 
244         #endregion
245 
246         #region [ 內部方法 ]  
247         /// <summary>  
248         /// 輸出普通日志  
249         /// </summary>  
250         /// <param name="level"></param>  
251         /// <param name="format"></param>  
252         /// <param name="args"></param>  
253         private void Log(LogLevel level, string format, params object[] args)
254         {
255             switch (level)
256             {
257                 case LogLevel.Debug:
258                     _Logger4net.DebugFormat(format, args);
259                     break;
260                 case LogLevel.Info:
261                     _Logger4net.InfoFormat(format, args);
262                     break;
263                 case LogLevel.Warn:
264                     _Logger4net.WarnFormat(format, args);
265                     break;
266                 case LogLevel.Error:
267                     _Logger4net.ErrorFormat(format, args);
268                     break;
269                 case LogLevel.Fatal:
270                     _Logger4net.FatalFormat(format, args);
271                     break;
272             }
273         }
274 
275         /// <summary>  
276         /// 格式化輸出異常信息  
277         /// </summary>  
278         /// <param name="level"></param>  
279         /// <param name="message"></param>  
280         /// <param name="exception"></param>  
281         private void Log(LogLevel level, string message, Exception exception)
282         {
283             switch (level)
284             {
285                 case LogLevel.Debug:
286                     _Logger4net.Debug(message, exception);
287                     break;
288                 case LogLevel.Info:
289                     _Logger4net.Info(message, exception);
290                     break;
291                 case LogLevel.Warn:
292                     _Logger4net.Warn(message, exception);
293                     break;
294                 case LogLevel.Error:
295                     _Logger4net.Error(message, exception);
296                     break;
297                 case LogLevel.Fatal:
298                     _Logger4net.Fatal(message, exception);
299                     break;
300             }
301         }
302         #endregion
303     }
304 
305     #region [ enum: LogLevel ]
306 
307     /// <summary>  
308     /// 日志級別  
309     /// </summary>  
310     public enum LogLevel
311     {
312         Debug,
313         Info,
314         Warn,
315         Error,
316         Fatal
317     }
318 
319     #endregion 
320 }
View Code

好了,類庫中的配置已經完成了,下面是調用方的配置

1、調用方可以是WinFrom,WPF,Web等可以直接運行的項目,右鍵---管理Nuget程序包添加log4net的包

2、需要調用的地方添加

Logger.Singleton.Debug("This is a debug file");

當然上面的代碼只是為了測試,具體用什么樣的錯誤級別和什么錯誤信息,需要自己手動輸入實現

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM