使用log4net將日誌文件輸出爲csv格式

  咱們在編寫程序時,會在程序運行過程當中記錄一些日誌。log4net做爲一款經久耐用的日誌組件,值得咱們信賴。在中小型公司中,每每沒有專業的日誌服務器來處理應用程序產生的日誌,而格式化很差的日誌文件又爲上線後日志的統計、分析、查找形成了困難。html

  Excel做爲一款經常使用的辦公軟件,用來處理一些中小數量級的數據仍是遊刃有餘的。若是log4net輸出的日誌可以直接導入Excel,那麼查詢和分析起來豈不是要快不少?服務器

  咱們有不少方法能夠實現這個功能,csv的優點是其文件格式比較簡單,能夠用任意的文本編輯器打開,並且解析起來比較方便。效果以下:app

 

  新建控制檯程序,引用log4net類庫這些步驟沒必要說,直接進入正題,咱們須要增長4個類文件 CsvTextWriter 、 NewFieldConverter 、 EndRowConverter 和 CsvPatternLayout。編輯器

CsvTextWriter.cside

複製代碼
 1 using System.IO;  2 using System.Text;  3 
 4 namespace CoderBusy.Log4Net.Layout  5 {  6     public class CsvTextWriter : TextWriter  7  {  8         private readonly TextWriter _textWriter;  9 
10         public CsvTextWriter(TextWriter textWriter) 11  { 12             _textWriter = textWriter; 13  } 14 
15         public override Encoding Encoding => _textWriter.Encoding; 16 
17         public override void Write(char value) 18  { 19  _textWriter.Write(value); 20             if (value == '"') 21  _textWriter.Write(value); 22  } 23 
24         public void WriteQuote() 25  { 26             _textWriter.Write('"'); 27  } 28  } 29 }
複製代碼

NewFieldConverter.cspost

複製代碼
 1 using System.IO;  2 using log4net.Util;  3 
 4 namespace CoderBusy.Log4Net.Layout  5 {  6     public class NewFieldConverter : PatternConverter  7  {  8         protected override void Convert(TextWriter writer, object state)  9  { 10             var ctw = writer as CsvTextWriter; 11             ctw?.WriteQuote(); 12 
13             writer.Write(','); 14 
15             ctw?.WriteQuote(); 16  } 17  } 18 }
複製代碼

EndRowConverter.cs測試

複製代碼
 1 using System.IO;  2 using log4net.Util;  3 
 4 namespace CoderBusy.Log4Net.Layout  5 {  6     public class EndRowConverter : PatternConverter  7  {  8         protected override void Convert(TextWriter writer, object state)  9  { 10             var ctw = writer as CsvTextWriter; 11 
12             ctw?.WriteQuote(); 13 
14  writer.WriteLine(); 15  } 16  } 17 }
複製代碼

CsvPatternLayout.csurl

複製代碼
 1 using System.IO;  2 using log4net.Core;  3 using log4net.Layout;  4 
 5 namespace CoderBusy.Log4Net.Layout  6 {  7     public class CsvPatternLayout : PatternLayout  8  {  9         public override void ActivateOptions() 10  { 11             AddConverter("newfield", typeof(NewFieldConverter)); 12             AddConverter("endrow", typeof(EndRowConverter)); 13             base.ActivateOptions(); 14  } 15 
16         public override void Format(TextWriter writer, LoggingEvent loggingEvent) 17  { 18             var ctw = new CsvTextWriter(writer); 19  ctw.WriteQuote(); 20             base.Format(ctw, loggingEvent); 21  } 22  } 23 }
複製代碼

  在書寫 log4net 的配置文件時,只要將 appender 的 layout 設置爲 CoderBusy.Log4Net.Layout.CsvPatternLayout ,且設置好日誌頭,日誌格式便可。注意,header後須要編寫換行字符,%newfield表明字段分隔符,%endrow表明一行結束。spa

複製代碼
<layout type="CoderBusy.Log4Net.Layout.CsvPatternLayout,CoderBusy.Log4Net">
        <header value="Time,Thread,Level,Logger,Message,Exception&#13;&#10;" />
        <conversionPattern value="%date{yyyy-MM-dd HH:mm:ss}%newfield%thread%newfield%level%newfield%logger%newfield%message%newfield%exception%endrow" />
      </layout>
複製代碼

  我爲初學者準備了一個log4net的配置文件。這個配置文件會將日誌在控制檯和csv文件中同時輸出,天天一個CSV文件(本地時間),且控制檯中,不一樣的日誌級別會有不一樣的顏色。 .net

複製代碼
 1 <?xml version="1.0" encoding="utf-8"?>
 2 
 3 <configuration>
 4   <configSections>
 5     <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
 6   </configSections>
 7   <log4net xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
 8     <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
 9       <param name="File" value="Logs/" />
10       <param name="AppendToFile" value="True" />
11       <param name="MaxSizeRollBackups" value="10" />
12       <param name="StaticLogFileName" value="false" />
13       <param name="DatePattern" value="yyyy-MM-dd&quot;.csv&quot;" />
14       <param name="RollingStyle" value="Date" />
15       <layout type="CoderBusy.Log4Net.Layout.CsvPatternLayout,CoderBusy.Log4Net">
16         <header value="Time,Thread,Level,Logger,Message,Exception&#13;&#10;" />
17         <conversionPattern 18           value="%date{yyyy-MM-dd HH:mm:ss}%newfield%thread%newfield%level%newfield%logger%newfield%message%newfield%exception%endrow" />
19       </layout>
20     </appender>
21 
22     <appender name="ColoredConsoleAppender" type="log4net.Appender.ColoredConsoleAppender">
23       <mapping>
24         <level value="ERROR" />
25         <foreColor value="Red" />
26       </mapping>
27       <mapping>
28         <level value="INFO" />
29         <foreColor value="Green" />
30       </mapping>
31 
32       <layout type="log4net.Layout.PatternLayout">
33         <conversionPattern value="# %date{HH:mm:ss} [%thread] %-5level %logger #%newline%message%newline" />
34       </layout>
35       <filter type="log4net.Filter.LevelRangeFilter">
36         <param name="LevelMin" value="DEBUG" />
37         <param name="LevelMax" value="FATAL" />
38       </filter>
39     </appender>
40 
41     <root>
42       <!-- OFF < FATAL < ERROR < WARN < INFO < DEBUG < ALL -->
43       <level value="ALL" />
44       <appender-ref ref="RollingLogFileAppender" />
45       <appender-ref ref="ColoredConsoleAppender" />
46     </root>
47   </log4net>
48 </configuration>
複製代碼

  配合以上配置,測試一下功能。

複製代碼
 1 using System;  2 using log4net;  3 using log4net.Config;  4 
 5 [assembly: XmlConfigurator(ConfigFile = "log4net.config")]  6 
 7 namespace CoderBusy.Log4Net.Tests  8 {  9     internal class Program 10  { 11         public static void Main(string[] args) 12  { 13             var log = LogManager.GetLogger("Default"); 14             log.Debug("Message", new Exception("Test Exception")); 15             log.Info("Hello World."); 16             log.WarnFormat("A={0} B={1}", "\"123123", Environment.NewLine); 17  Console.ReadLine(); 18  } 19  } 20 }
複製代碼

Logs文件夾中,生成的csv文件內容以下:

Time,Thread,Level,Logger,Message,Exception
"2016-08-25 23:13:19","9","DEBUG","Default","Message","System.Exception: Test Exception
"
"2016-08-25 23:13:19","9","INFO","Default","Hello World.",""
"2016-08-25 23:13:19","9","WARN","Default","A=""123123 B=
",""




  輸出字段被使用雙引號包裹,且消息體中的雙引號被重複輸出。這樣的結果代表咱們的程序是正常的。本文的代碼能夠在 http://pan.baidu.com/s/1hr4EOPu 下載,謝謝閱讀,並祝你成功。

 

 

 

出處:https://www.cnblogs.com/Soar1991/p/5808788.html

相關文章
相關標籤/搜索