C # Log4Net for Logging

Posted by emceej on Wed, 17 Jul 2019 22:40:25 +0200

This paper mainly explains how to log with Log4Net and the advantages of logging in the process of program development.

  • It can provide a precise environment for application runtime, and it can help developers find the Bug in the application as soon as possible.
  • Once the Log output code is added to the program, the log information can be generated and output during the program running without manual intervention.
  • Log information can be exported to different places (console, file, etc.) for future research.

Official Notes on Log4Net:

The Apache log4net library is a tool to help the programmer output log statements to a variety of output targets. log4net is a port of the excellent Apache log4j™ framework to the Microsoft® .NET runtime. We have kept the framework similar in spirit to the original log4j while taking advantage of new features in the.NET runtime.

Apache log4net class library is a tool to help programmers output log status to multiple target platforms. Log4net is an excellent implementation of Apache log4jTM framework on Microsoft. Net platform. On the premise of maintaining the original log4j idea, the new features of. Net are utilized at the same time.

Log4Net is used in programs. It can be configured by configuration files or defined by program code. This article mainly explains how to realize it by configuration.

The configuration file structure is shown in the following figure:

Configuration files can be configured in App.config [compiled to generate the corresponding [program name]. exe.config], or in a separate xml file.

If you configure it in a separate xml file, you need to add a note to Assembly.cs, as follows:

[assembly: log4net.Config.DOMConfigurator(ConfigFile = "Log4NetConfig.xml", ConfigFileExtension = "xml", Watch = true)]

If you configure it in App.config, besides configuring log4net nodes, you also need to declare that you want to add a configSection node [the first element on the root node], as shown below.

  <configSections>
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
  </configSections>

The content of the generated log file is shown in the following figure:

-----------------------------------------------------------------------------------------

The code is as follows:

 1 using log4net;
 2 using System;
 3 using System.Collections.Generic;
 4 using System.Linq;
 5 using System.Text;
 6 using System.Threading.Tasks;
 7 
 8 [assembly: log4net.Config.XmlConfigurator(Watch = true)]
 9 namespace DemoLog4Net
10 {
11     /// <summary>
12     /// Logging
13     /// </summary>
14     public class LogHelper
15     {
16         /// <summary>
17         /// Log instance
18         /// </summary>
19         private static ILog logInstance=LogManager.GetLogger("testApp");
20 
21         public static void WriteLog(string message ,LogLevel level) {
22             switch (level) {
23                 case LogLevel.Debug:
24                     logInstance.Debug(message);
25                     break;
26                 case LogLevel.Error:
27                     logInstance.Error(message);
28                     break;
29                 case LogLevel.Fatal:
30                     logInstance.Fatal(message);
31                     break;
32                 case LogLevel.Info:
33                     logInstance.Info(message);
34                     break;
35                 case LogLevel.Warn:
36                     logInstance.Warn(message);
37                     break;
38                 default:
39                     logInstance.Info(message);
40                     break;
41             }
42         }
43     }
44 
45     public enum LogLevel {
46         Debug=0,
47         Error=1,
48         Fatal=2,
49         Info=3,
50         Warn=4
51     }
52 }

The standalone configuration files are as follows:

 1 <?xml version="1.0" encoding="utf-8" ?>
 2 <log4net>
 3   <root>
 4     <level value="DEBUG" />
 5     <appender-ref ref="LogFileAppender" />
 6     <appender-ref ref="ConsoleAppender" />
 7   </root>
 8   <logger name="testApp">
 9     <level value="DEBUG" />
10   </logger>
11   <appender name="LogFileAppender" type="log4net.Appender.FileAppender" >
12     <param name="File" value="${TMO}log-file.txt" />
13     <StaticLogFileName value="false"/>
14     <param name="AppendToFile" value="true" />
15     <layout type="log4net.Layout.PatternLayout">
16       <param name="Header" value="[Header]&#13;&#10;"/>
17       <param name="Footer" value="[Footer]&#13;&#10;"/>
18       <param name="ConversionPattern" value="%d [%t] %-5p %c [%x]  - %m%n"/>
19     </layout>
20     <filter type="log4net.Filter.LevelRangeFilter">
21       <param name="LevelMin" value="DEBUG" />
22       <param name="LevelMax" value="ERROR" />
23     </filter>
24   </appender>
25   <appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender" >
26     <layout type="log4net.Layout.PatternLayout">
27       <param name="ConversionPattern" value="%d [%t] %-5p %c [%x] - %m%n" />
28     </layout>
29   </appender>
30 </log4net>


Additional:

How to set environment variables:

 System.Environment.SetEnvironmentVariable("TMO", DateTime.Now.ToString("yyyyMMdd"));

Logging priority is shown in the following table:

 

level Permissible method Boolean attribute Priority
OFF     Highest
FATAL void Fatal(...); bool IsFatalEnabled;  
RROR void Error(...); bool IsErrorEnabled;  
WARN void Warn(...); bool IsWarnEnabled;  
INFO void Info(...); bool IsInfoEnabled;  
DEBUG void Debug(...); bool IsDebugEnabled;  
ALL     Lowest
 

 

 

 

 

 

 

 

 

Remarks:

log4net is indeed a widely used and simple logging framework. This article is just a brief description. We will continue to study other functions in the follow-up work.

Topics: C# xml Apache log4j encoding