Log4Net tutorial (my straightforward version)
After playing around with the Log4Net, this is my version of tutorial of Log4Net. (WinForm or console)
I have come across a few tutorials but it seems that most of them are either not working or missing out some details that could lead to further waste of time in searching. Hence, my version is here. (in case in future I need to refer back again)
1. Download latest Log4Net. Not the release version 1.1.1, it won't work in this tutorial. Actually, I haven't seen any tutorials works on 1.1.1 release with FileAppender, what an upset. You will need to download the 1.2.0 Beta8 or later.
2. Start a .NET WinForm application or console application.
3. Add reference to Log4Net.dll
4. Add codes below to AssemblyInfo.cs
[assembly: log4net.Config.DOMConfigurator(ConfigFile="Logging", ConfigFileExtension="config",Watch=false)]
5. Add these two lines into your class.
private static readonly ILog logger =
LogManager.GetLogger(typeof(YourClassName));
static YourClassName()
{
DOMConfigurator.Configure();
}
6. Then, right click on your project at the Solution Explorer.
- Add - Add New Item - Utility - Application Configuration File
You will see a App.Config appears before you.
7. Add in these lines into your App.Config
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
</configSections>
<log4net>
<appender name= "LogFileAppender" type="log4net.Appender.FileAppender">
<param name="File" value="LogTest2.txt" />
<param name="AppendToFile" value="true" />
<layout type="log4net.Layout.PatternLayout">
<param name="Header" value="[Header]\r\n" />
<param name="Footer" value="[Footer]\r\n" />
<param name="ConversionPattern" value="%d [%t] %-5p %c - %m%n" />
</layout>
</appender>
<root>
<level value="INFO" />
<appender-ref ref="LogFileAppender" />
</root>
</log4net>
</configuration>
8. Then, at any point where you want to log to the file, just place codes like e.g. below, depends on priority and purpose.
logger.Debug("Here is a debug log.");
logger.Info("... and an Info log.");
logger.Warn("... and a warning.");
logger.Error("... and an error.");
logger.Fatal("... and a fatal error.");
For further info on its usage, check the Log4Net project page.
(Content below quoted from http://www.vipan.com/htdocs/log4jhelp.html)
I have come across a few tutorials but it seems that most of them are either not working or missing out some details that could lead to further waste of time in searching. Hence, my version is here. (in case in future I need to refer back again)
1. Download latest Log4Net. Not the release version 1.1.1, it won't work in this tutorial. Actually, I haven't seen any tutorials works on 1.1.1 release with FileAppender, what an upset. You will need to download the 1.2.0 Beta8 or later.
2. Start a .NET WinForm application or console application.
3. Add reference to Log4Net.dll
4. Add codes below to AssemblyInfo.cs
[assembly: log4net.Config.DOMConfigurator(ConfigFile="Logging", ConfigFileExtension="config",Watch=false)]
5. Add these two lines into your class.
private static readonly ILog logger =
LogManager.GetLogger(typeof(YourClassName));
static YourClassName()
{
DOMConfigurator.Configure();
}
6. Then, right click on your project at the Solution Explorer.
- Add - Add New Item - Utility - Application Configuration File
You will see a App.Config appears before you.
7. Add in these lines into your App.Config
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
</configSections>
<log4net>
<appender name= "LogFileAppender" type="log4net.Appender.FileAppender">
<param name="File" value="LogTest2.txt" />
<param name="AppendToFile" value="true" />
<layout type="log4net.Layout.PatternLayout">
<param name="Header" value="[Header]\r\n" />
<param name="Footer" value="[Footer]\r\n" />
<param name="ConversionPattern" value="%d [%t] %-5p %c - %m%n" />
</layout>
</appender>
<root>
<level value="INFO" />
<appender-ref ref="LogFileAppender" />
</root>
</log4net>
</configuration>
8. Then, at any point where you want to log to the file, just place codes like e.g. below, depends on priority and purpose.
logger.Debug("Here is a debug log.");
logger.Info("... and an Info log.");
logger.Warn("... and a warning.");
logger.Error("... and an error.");
logger.Fatal("... and a fatal error.");
For further info on its usage, check the Log4Net project page.
(Content below quoted from http://www.vipan.com/htdocs/log4jhelp.html)
Useful Layouts
- Some layout classes are
TTCCLayout, HTMLLayout, PatternLayout, SimpleLayout
andXMLLayout
. - SimpleLayout and PatternLayout classes ignore Java
Throwable
errors and exceptions. HTMLLayout and XMLLayout handle them. SimpleLayout
consists of the priority of the log statement, followed by " - " and then the log message itself. For example:DEBUG - Hello world
PatternLayout
lets you specify the output format according to conversion patterns similar to the C language printf function. For example, PatternLayout with the conversion pattern%r [%t] %-5p %c - %m%n
will output something like:176 [main] INFO org.foo.Bar - Located nearest gas station.
- The first field is the number of milliseconds elapsed since the start of the program.
- The second field is the thread making the log request.
- The third field is the priority of the log statement.
- The fourth field is the name of the category associated with the log request.
- The text after the '-' is the message of the statement.
- You can insert any literal text within the conversion pattern.
- Conversion characters are:
- %m: Outputs your message.
- %p: Outputs the priority of the logging event.
- %r: Outputs the number of milliseconds elapsed since the start of the application until the creation of the logging event.
- %c: Outputs the category of the logging event. Example: For the category name "a.b.c", the pattern
%c{2}
will output "b.c".{2}
means "output last two components of the dot-separated category name". If no{n}
is there, full Category name is output by default. - %t: Outputs the name of the thread that generated the logging event.
- %x: Outputs the nested diagnostic context (NDC) associated with the thread that generated the logging event. Useful when multiple clients are handled by separate threads such as in Java servlets.
- %n: Outputs the platform-dependent newline character(s). Preferable to specifying "\n" or "\r\n" etc.
- %%: Outputs a single percent sign.
- WARNING: The patterns below will slow down the execution of your program somewhat. Avoid unless execution speed is not an issue.
- %d: Outputs the date of the logging event. The date conversion specifier may be followed by a date format specifier enclosed between braces. Example:
%d{HH:mm:ss,SSS}
or%d{dd MMM yyyy HH:mm:ss,SSS}
. If no date format specifier is given then ISO8601 format is assumed. The date format specifier admits the same syntax as the time pattern string of Java'sSimpleDateFormat
which is slow. For faster performance, use%d{ISO8601}
, %d{ABSOLUTE}, %d{RELATIVE} (millisecs since program start, fastest) or%d{DATE}
which use log4j'sISO8601DateFormat, AbsoluteTimeDateFormat, RelativeTimeDateFormat
andDateTimeDateFormat
date formatters respectively. - %l: Outputs source code location information. Shortcut for
%C.%M(%F:%L)
. - %C: Outputs the fully-qualified class name of the caller issuing the logging request. Example: For the class name "org.apache.xyz.SomeClass", the pattern
%C{1}
will output "SomeClass".{1}
means "output last one component of the fully-qualified class name". If no{n}
is there, full class name is output by default. - %M: Outputs the method name where the logging request was issued.
- %F: Outputs the file name where the logging request was issued.
- %L: Outputs the line number from where the logging request was issued.
- Optionally, use format modifiers between the percent sign and the conversion character to change the minimum field width, the maximum field width and text justification within a field.
- Use the minus sign (
-
) to left-justify within a field. Default is to right-justify (pad on left). - Use a positive integer to specify the minimum field width. If the data item requires fewer characters, it is padded with space(s) on either the left or the right until the minimum width is reached. If the data item is larger than the minimum field width, the field is expanded to accommodate the data.
- Use a period followed by a positive integer to specify the maximum field width. If the data item is longer than the maximum field, then the extra characters are removed from the beginning of the data item and not from the end. For example, it the maximum field width is eight and the data item is ten characters long, then the first two characters of the data item are dropped. This behavior deviates from the printf function in C where truncation is done from the end.
- Use the minus sign (
- Examples:
%20c
: Right-justify (by default) the category name within 20 spaces minimum.%-20c
: Left-justify the category name within 20 spaces minimum.%.30c
: If the category name is longer than 30 characters, truncate (from the beginning). No minimum width and therefore, no padding if shorter than 30 characters.%20.30c
: Right-justify if the category name is shorter than 20 characters. If category name is longer than 30 characters, then truncate from the beginning.%-20.30c
: Left-justify if the category name is shorter than 20 characters. If category name is longer than 30 characters, then truncate from the beginning.%r [%t] %-5p %c %x - %m\n
: This is essentially theTTCCLayout
.%-6r [%15.15t] %-5p %30.30c %x - %m\n
: Similar to theTTCCLayout
except that the relative time is right padded if less than 6 digits, thread name is right padded if less than 15 characters and truncated if longer, and the category name is left padded if shorter than 30 characters and truncated if longer.
- ADVANCED: You don't have to pass just Strings to log. You can pass your objects to the log method also. Implement
ObjectRenderer
to log a string representation of your object to the appender.
Comments