Use log4net to output log files in csv format, log4netcsv
Some logs are recorded during the program running. As a durable log component, log4net is trustworthy. In small and medium enterprises, there is often no professional log server to process logs generated by applications, and poorly formatted log files make it difficult to collect, analyze, and search logs after they are launched.
As a common office software, Excel can process small and medium orders of magnitude data. If the logs output by log4net can be directly imported into Excel, isn't query and analysis much faster?
We have many ways to implement this function. The advantage of csv is that its file format is relatively simple, it can be opened in any text editor, and it is easier to parse. The effect is as follows:
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 => _ 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. cs
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. cs
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 }
When writing the log4net configuration file, you only need to set the layout of the appender to CoderBusy. Log4Net. Layout. CsvPatternLayout, and set the log header and log format. Note: line breaks must be written after the header. % newfield represents the field separator, and % endrow represents the end of a line.
<layout type="CoderBusy.Log4Net.Layout.CsvPatternLayout,CoderBusy.Log4Net">
I have prepared a log4net configuration file for beginners. This configuration file outputs logs in the console and csv files at the same time. a csv file (local time) is generated every day, and different log levels have different colors on the console.
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".csv"" />14 <param name="RollingStyle" value="Date" />15 <layout type="CoderBusy.Log4Net.Layout.CsvPatternLayout,CoderBusy.Log4Net">16
Use the above configuration to test the function.
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 Program10 {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 }
In the Logs folder, the generated csv file is as follows:
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=
",""
The output field is enclosed by double quotation marks, and the double quotation marks in the message body are repeatedly output. This result indicates that our program is normal. The code for this article can be downloaded in http://pan.baidu.com/s/1hr4EOPu. Thank you for reading and wish you success.