Click here to Skip to main content
15,887,347 members
Articles / Programming Languages / XML

Log4net: Skeleton of (app/web).config File

Rate me:
Please Sign up or sign in to vote.
4.67/5 (3 votes)
21 Oct 2018CPOL5 min read 10.3K   94   15   1
In this article, I am going to detail application configuration file setup for log4net.

Introduction

In log4net first article, Log4net: How to setup and use at first time, I explained very basic steps to setup and use log4net for logging.

In this article, I am going to detail a very basic structure of app.config/web.config file for log4net.

Config Section for Log4net

You already know that after adding log4net.dll in application type project, you will be adding config-section for log4net in configuration file as follows:

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

Sample App.config

And this is a sample of app.config file to clearly understand log4net config-setup:

C#
<log4net>
   <appender name="B_SampleRollingAppenderTest" type="log4net.Appender.RollingFileAppender">
     <param name="CountDirection" value="1"/>
     <param name="threshold" value="DEBUG"/>
     <datePattern>_dd_MMMM_yyyy_dddd_HH_mm</datePattern>
     <dateTimeStrategy type="log4net.Appender.RollingFileAppender+LocalDateTime"/>
     <maximumFileSize>100KB</maximumFileSize>
     <preserveLogFileNameExtension>true</preserveLogFileNameExtension>
     <rollingStyle>date</rollingStyle>
     <file type="log4net.Util.PatternString" value="%envFolderPath{Desktop}\RahulLog.txt"/>
     <immediateFlush>true</immediateFlush>
     <param name="layout" type="log4net.Layout.PatternLayout">
       <param name="conversionPattern">
         MyLoggerName: %stacktracedetail{5},%newline  %identity
         %newline [AppDomain_a] = %2.4a . %newline [AppDomainFull] = %2.4appdomain .
         %newline [AppSetting1] = %2.4appsetting . %newline [AppSetting2] = %AppSetting .
         %newline [AppSetting3] = %appSetting . %newline [LocalDate_d] = %2.4d .
         %newline [LocalDate_Full] = %2.4date . %newline [EnvironmentFolderPath] = %2.4envFolderPath .
         %newline [Environment] = %env . %newline [Identity_u] = %2.4u .
         %newline [Identity_Full] = %2.4identity . %newline [Literal] = %literal .
         %newline [New-Line_Full] = %newline . %newline [New-Line_n] = %n .
         %newline [ProcessId] = %2.4processid . %newline [Property_P] = %P .
         %newline [Property_Full] = %2.4property . %newline [Property_Plural] = %2.4properties .
         %newline [Property_X] = %2.4X . %newline [Property_mdc] = %2.4mdc .
         %newline [RandomString] = %2.4random . %newline [User_w] = %2.4w .
         %newline [User_Full] = %2.4username . %newline [Utc_Time1] = %2.4utcdate .
         %newline [Utc_Time2] = %2.4utcDate . %newline [Utc_Time3] = %2.4UtcDate .
         %newline [AspNet-Cache_Data] = %aspnet-cache .
         %newline [AspNetContextData] = %aspnet-context .
         %newline [AspNetRequest] = %aspnet-request . %newline [AspNetSession] = %aspnet-session .
         %newline [Logger_c] = %2.4c . %newline [Logger_Full] = %2.4logger .
         %newline [TypeName_C] = %2.4C . %newline [TypeName_class] = %2.4class .
         %newline [TypeName_type] = %2.4type . %newline [Exception] = %2.4exception. %newline %newline
         %newline %2.4exception{message} %newline --> %2.4exception{source}
         %newline --> %2.4exception{stacktrace} %newline --> %2.4exception{targetsite}
         %newline --> %2.4exception{helplink}  . %newline [File_F] = %2.4F .
         %newline File_Full] = %2.4file . %newline [Location_l] = %2.4l .
         %newline [Location_Full] = %2.4location . %newline [LineNumber_L] = %2.4L .
         %newline [LineNumber_line] = %2.4line . %newline [Message_m] = %2.4m .
         %newline [Message_message] = %2.4message . %newline [Method_M] = %2.4M .
         %newline [Method_Method] = %2.4method . %newline [LogLevel_p] = %2.4p .
         %newline [LogLevel_Level] = %2.4level . %newline [RelativeTime_r] = %2.4r .
         %newline [RelativeTime_timestamp] = %2.4timestamp . %newline [StackTrace] = %2.4stacktrace .
         %newline [Thread_t] = %2.4t . %newline [Thread_Full] = %2.4thread .
         %newline [NDC_x] = %2.4x . %newline [NDC_Full] = %2.4ndc .
         %newline [stacktracedetail] = %2.4stacktracedetail .
       </param>
     </param>
     <lockingModel type="log4net.Appender.FileAppender+MinimalLock"/>
   </appender>
   <appender name="EventLogAppender_A" type="log4net.Appender.EventLogAppender">
     <param name="threshold" value="DEBUG"/>
     <category value="1"/>
     <applicationName  type="log4net.Util.PatternString">%2.4appsetting{Name1}</applicationName>
     <mapping>
       <eventLogEntryType value="Error"/>
       <level value="Error"/>
     </mapping>
     <mapping>
       <eventLogEntryType value="Warning"/>
       <level value="Warn"/>
     </mapping>
     <mapping>
       <eventLogEntryType value="Information"/>
       <level value="Info"/>
     </mapping>
     <mapping>
       <eventLogEntryType value="SuccessAudit"/>
       <level value="Debug"/>
     </mapping>
     <mapping>
       <eventLogEntryType value="FailureAudit"/>
       <level value="Fatal"/>
     </mapping>
     <eventId>23</eventId>
     <logName type="log4net.Util.PatternString">Rahul1</logName>
     <layout type="log4net.Layout.DynamicPatternLayout">
       <header value="%newline**** Trace Opened Local:
       %date{yyyy-MM-dd HH:mm:ss.fff} UTC: %utcdate{yyyy-MM-dd HH:mm:ss.fff} ****%newline"/>
       <footer value="**** Trace Closed %date{yyyy-MM-dd HH:mm:ss.fff} ****%newline"/>
       <conversionPattern value="%newline Logged Message : %message"/>
     </layout>
     <securityContext type="log4net.Util.WindowsSecurityContext">
       <credentials>user</credentials>
       <domainName>Domain</domainName>
       <password>welcom@123</password>
       <userName>TESTUser</userName>
     </securityContext>
   </appender>
   <root>
     <level value="DEBUG"/>
     <appender-ref ref="B_SampleRollingAppenderTest"/>
   </root>
 </log4net>

Now there is a parent tag log4net and inside this log4net tag, one root tag and one or many appender tags will be added.

So let’s start first with log4net tag.

<log4net> tag

This is actually a root tag for log4net setup in config file. We define all appenders and one child tag named root inside it.

Attributes

I am talking about its main attribute threshold here, which is used mostly.

Threshold

This attribute is used to define log-level based filtering on log messages like which level of log messages should be written to target and which should be ignored simply.

Common behavior of this property for all possible values:

Log-Level Possible Values
Possible Value Internal Value Behavior
ALL -2147483648 Log each log message of any level.
VERBOSE 10000
FINEST 10000
TRACE 20000 Log messages of level TRACE or above.
FINER 20000 Log messages of level FINAR or above.
FINE 30000 Log messages of level FINE or above.
DEBUG 30000 Log messages of level DEBUG or above.
INFO 40000 Log messages of level INFO or above.
NOTICE 50000 Log messages of level NOTICE or above.
WARN 60000 Log messages of level WARN or above.
ERROR 70000 Log messages of level ERROR or above.
SEVERE 80000 Log messages of level SEVERE or above.
CRITICAL 90000 Log messages of level CRITICAL or above.
ALERT 100000 Log messages of level ALERT or above.
FATAL 110000 Log messages of level FATAL or above.
EMERGENCY 120000 Log messages of level EMERGENCY or above.
OFF 2147483647 Disable logging at all.

You can log messages with level other than popular levels (DEBUG, INFO, WARN, ERROR, FATAL) by below implementation in SampleLog4NetLogger class:

C#
public void Log(Level logLevel, object message, Exception exceptionData)
        {
            log4NetReal.Logger.Log(null, logLevel, message, exceptionData);
        }

How to Set It in app.config

We define threshold on log4net tag like below:

C#
<log4net threshold="ALL">

Image 1

<appender> Tag

This is the tag, by which, we define/configure an instance of any type of appender.

How to Set It in app.config

XML
<appender name="B_SampleRollingAppenderTest" type="log4net.Appender.RollingFileAppender">
      <param name="CountDirection" value="1"/>
      <param name="threshold" value="DEBUG"/>
      <maximumFileSize>100KB</maximumFileSize>
      <preserveLogFileNameExtension>true</preserveLogFileNameExtension>
      <rollingStyle>size</rollingStyle>
      <file type="log4net.Util.PatternString" value="..\..\Logs\RahulLog.txt"/>
      <immediateFlush>true</immediateFlush>
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%newline Logged Message : %message %newline "/>
      </layout>
      <lockingModel type="log4net.Appender.FileAppender+MinimalLock"/>
    </appender>

Image 2

As this tag defines the instance of specific type of appender, so there are 2 mandatory attributes available on this tag:

1. Type

This attribute is used to define appender type for instantiation. We define namespace qualified full name of appender class in it.

Common behavior of this property for all possible values:

Possible Value Behavior
log4net.Appender. AdoNetAppender Used to define appender instance of type AdoNetAppender
log4net.Appender. AnsiColorTerminalAppender Used to define appender instance of type AnsiColorTerminalAppender
log4net.Appender. AspNetTraceAppender Used to define appender instance of type AspNetTraceAppender
log4net.Appender. BufferingForwardingAppender Used to define appender instance of type BufferingForwardingAppender
log4net.Appender. ColoredConsoleAppender Used to define appender instance of type ColoredConsoleAppender
log4net.Appender. ConsoleAppender Used to define appender instance of type ConsoleAppender
log4net.Appender. DebugAppender Used to define appender instance of type DebugAppender
log4net.Appender. EventLogAppender Used to define appender instance of type EventLogAppender
log4net.Appender. FileAppender Used to define appender instance of type FileAppender
log4net.Appender. ForwardingAppender Used to define appender instance of type ForwardingAppender
log4net.Appender. LocalSyslogAppender Used to define appender instance of type LocalSyslogAppender
log4net.Appender. ManagedColoredConsoleAppender Used to define appender instance of type ManagedColoredConsoleAppender
log4net.Appender. MemoryAppender Used to define appender instance of type MemoryAppender
log4net.Appender. NetSendAppender Used to define appender instance of type NetSendAppender
log4net.Appender. OutputDebugStringAppender Used to define appender instance of type OutputDebugStringAppender
log4net.Appender. RemoteSyslogAppender Used to define appender instance of type RemoteSyslogAppender
log4net.Appender. RemotingAppender Used to define appender instance of type RemotingAppender
log4net.Appender. RollingFileAppender Used to define appender instance of type RollingFileAppender
log4net.Appender. SmtpAppender Used to define appender instance of type SmtpAppender
log4net.Appender. SmtpPickupDirAppender Used to define appender instance of type SmtpPickupDirAppender
log4net.Appender. TelnetAppender Used to define appender instance of type TelnetAppender
log4net.Appender. TraceAppender Used to define appender instance of type TraceAppender
log4net.Appender.UdpAppender Used to define appender instance of type UdpAppender

2. Name

This property is used to define name of appender instance. It could be any string value. Name of each instance should be unique in that app.config file.

Common behavior of this property for all possible values:

Possible Value Behavior

Any string value

Name is used to refer to the appender instance. It should be unique in that app.config file.

<root> tag

<root> tag is used to define all active appenders for logging and apply log-level based filter on all those active appenders uniformly.

Inside <root> tag, we define below child tags:

Appender-ref:

As we can define n-number of instances of more than one type of appender (provided by log4net) inside <log4net> tag, this property is used to define only active appender instances to be considered for logging each incoming message.

There could be one or more than one <appender-ref> tags inside <root> tag to represent each active appender instance individually.

Appender instances which are defined inside <log4net> tag, but not declared in <root> tag won’t be executed at all.

Common behavior of this property for all possible values:

Possible Value Behavior
Any appender instance name This appender instance will be considered for logging messages.

How to Set It in app.config

XML
<root> <level value="DEBUG"/> 
<appender-ref ref="SampleRollingAppenderTest"/> 
<appender-ref ref="B_SampleRollingAppenderTest"/> </root>

Image 3

Level

This property is used to define log-level filtering on log messages for only active appender instances defined inside <root> tag.

Common behavior of this property for all possible values:

It’s possible values and behavior are already defined in <log4net> threshold section above. (Refer to the table captioned "Log-Level Possible Values" above).

How to Set It in app.config

XML
<root>
      <level value="DEBUG"/>
      <appender-ref ref="SampleRollingAppenderTest"/>
      <appender-ref ref="B_SampleRollingAppenderTest"/>
</root>

Image 4

So, this is the very basic structure of configuration file for log4net setup.

Points of Interest

By exploring log4net, I tried to explore the basic structure of configuration for log4net. As there are many things done in this file for the same, so detailing all these helps me to remember such complex things for a long time.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
India India
I am software developer working on majorly C# programming language. I have good amount of experience of working on WPF, log4net, Prism for WPF, SQL, Reflection.


Comments and Discussions

 
QuestionEncrypted Password in App.config/log4net.xml file Pin
Member 1559777012-Apr-22 0:01
Member 1559777012-Apr-22 0:01 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.