Frequently Asked Questions

Summary: This document contains frequently asked questions about log4net.

(Shamelessly copied from the log4j FAQ)


What is log4net?

log4net is a tool to help the programmer output log statements to a variety of output targets.

In case of problems with an application, it is helpful to enable logging so that the problem can be located. With log4net it is possible to enable logging at runtime without modifying the application binary. The log4net package is designed so that log statements can remain in shipped code without incurring a high performance cost. It follows that the speed of logging (or rather not logging) is crutial.

At the same time, log output can be so voluminous that it quickly becomes overwhelming. One of the distinctive features of log4net is the notion of hierarchical loggers. Using these loggers it is possible to selectively control which log statements are output at arbitrary granularity.

log4net is designed with two distinct goals in mind: speed and flexibility. There is a tight balance between these two requirements.

Back to Top

Is log4net a reliable logging system?

No. log4net is not reliable. It is a best-effort and fail-stop logging system.

By fail-stop, we mean that log4net will not throw unexpected exceptions at run-time potentially causing your application to crash. If for any reason, log4net throws an uncaught exception, please send an email to the mailing list. Uncaught exceptions are handled as serious bugs requiring immediate attention.

Moreover, log4net will not revert to System.Console.Out or System.Console.Error when its designated output stream is not opened, is not writable or becomes full. This avoids corrupting an otherwise working program by flooding the user's terminal because logging fails. However, log4net will output a single message to System.Console.Error indicating that logging can not be performed.

Back to Top

What are the prerequisites for log4net?

log4net runs on many different frameworks and each framework has its own requirements. As a rule of thumb you will need an ECMA-335 compliant CLI runtime, for example, the Microsoft .NET runtime 1.0 (1.0.3705) or 1.1 (1.1.4322).

Not all frameworks are created equal and some features have been excluded from some of the builds. See the Framework Support document for more information.

Back to Top

Is there example code for using log4net?

There is a directory containing examples in log4net\examples. The examples are broken down by framework.

Back to Top

What are the features of log4net?

  • log4net is optimized for speed.
  • log4net is based on a named logger hierarchy.
  • log4net is fail-stop but not reliable.
  • log4net is thread-safe.
  • log4net is not restricted to a predefined set of facilities.
  • Logging behaviour can be set at runtime using a configuration file. Configuration files are in XML format.
  • log4net is designed to handle exceptions from the start.
  • log4net can direct its output to many sinks including: a file, the console, the NT EventLog or even e-mail.
  • log4net uses 5 levels, namely DEBUG, INFO, WARN, ERROR and FATAL.
  • The format of the log output can be easily changed by implementing a new layout class.
  • The target of the log output as well as the writing strategy can be altered by writing a new appender class.
  • log4net supports multiple output appenders per logger.

Back to Top

Is log4net thread-safe?

Yes, log4net is thread-safe.

Back to Top

What does log output look like?

The log output can be customized in many ways. Moreover, one can completely override the output format by implementing one's own ILayout

Here is an example output using PatternLayout with the conversion pattern %r [%t] %-5p %c{2} %x - %m%n

176 [main] INFO  examples.Sort - Populating an array of 2 elements in reverse order.
225 [main] INFO  examples.SortAlgo - Entered the sort method.
262 [main] DEBUG SortAlgo.OUTER i=1 - Outer loop.
276 [main] DEBUG SortAlgo.SWAP i=1 j=0 - Swapping intArray[0] = 1 and intArray[1] = 0
290 [main] DEBUG SortAlgo.OUTER i=0 - Outer loop.
304 [main] INFO  SortAlgo.DUMP - Dump of integer array:
317 [main] INFO  SortAlgo.DUMP - Element [0] = 0
331 [main] INFO  SortAlgo.DUMP - Element [1] = 1
343 [main] INFO  examples.Sort - The next log statement should be an error message.
346 [main] ERROR SortAlgo.DUMP - Tried to dump an uninitialized array.
467 [main] INFO  examples.Sort - Exiting main method.

The first field is the number of milliseconds elapsed since the start of the program. The second field is the thread outputting the log statement. The third field is the level of the log statement. The fourth field is the rightmost two components of the name of the logger making the log request. The fifth field (just before the '-') is the nested diagnostic context (NDC). Note the nested diagnostic context may be empty as in the first two statements. The text after the '-' is the message of the statement.

Back to Top

What are Loggers?

The notion of loggers lies at the heart of log4net's configuration. Loggers define a hierarchy and give the programmer run-time control on which statements are printed or not.

Loggers are assigned levels through the configuration of log4net. A log statement is routed through to the appender depending on its level and its logger.

Back to Top

How can I change log behaviour at runtime?

Logging behaviour can be set using configuration files which are parsed at runtime. Using configuration files the programmer can define loggers and set their levels.

Configuration files are specified in XML. See log4net.Config.DOMConfigurator for more details.

See the various log4net.Layout and log4net.Appender components for specific configuration options.

Back to Top

How do I completely disable all logging at runtime?

Setting the Threshold on the Hierarchy to Level OFF will disable all logging from that Hierarchy. This can be done in the log4net configuration file by setting the "threshold" attribute on the log4net configuration element to "OFF". For example:

<log4net threshold="OFF" />

Back to Top

What is the fastest way of (not) logging?

For some logger log, writing,

log.Debug("Entry number: " + i + " is " + entry[i]);

incurs the cost of constructing the message parameter, that is converting both integer i and entry[i] to a string, and concatenating intermediate strings. This, regardless of whether the message will be logged or not.

If you are worried about speed, then write

	log.Debug("Entry number: " + i + " is " + entry[i]);

This way you will not incur the cost of parameter construction if debugging is disabled for logger log. On the other hand, if the logger is debug enabled, you will incur the cost of evaluating whether the logger is enabled or not, twice: once in IsDebugEnabled and once in Debug. This is an insignificant overhead since evaluating a logger takes less than 1% of the time it takes to actually log a statement.

Back to Top

What is REALLY the FASTEST way of (not) logging?

So you don't think that the previous FAQ is really the fastest way of not logging? Well there is a faster way but it does have some drawbacks. Starting from:

	log.Debug("Entry number: " + i + " is " + entry[i]);

It is possible to further eliminate the calls to IsDebugEnabled so that the call is only made once per logger. If you are using one logger for each class then you can store the enabled state for the logger in a static variable in the class and then test against this variable:

public class FastLogger
	private static readonly ILog log = LogManager.GetLogger(typeof(FastLogger));
	private static readonly bool isDebugEnabled = log.IsDebugEnabled;

	public void MyMethod()
			log.Debug("Entry number: " + i + " is " + entry[i]);

So why exactly is this faster? Well to start with the IsDebugEnabled is not called for each log statement, it is called once per logger. Furthermore as the isDebugEnabled variable is private static readonly the JIT compiler can at run-time optimise out the if test altogether. This means that at runtime the JIT compiler won't even compile the logging statements into native code, i.e. all the logging just disappears.

So what is the downside to using this? Well one of the clever features of log4net is that you can change the logging configuration while your program is running. If you need to investigate an issue in your application, you don't have to stop the application, setup the logging and restart the application, you can change the logging configuration and the log4net will reload it (see ConfigureAndWatch APIs for more information). However if the JIT has compiled out all of the logging statements then they are gone and you can't get them back by reloading the configuration file. Effectively this means that the logging configuration can only be set when the application loads and it cannot be changed at runtime. It is up to you to decide if you need ultimate speed or need to be able to reload the logging configuration while the application is running.

Back to Top

Are there any suggested ways for naming loggers?

Yes, there are.

You can name logging loggers by locality. It turns out that instantiating a logger in each class, with the logger name equal to the fully-qualified name of the class, is a useful and straightforward approach of defining loggers. This approach has many benefits:

  • It is very simple to implement.
  • It is very simple to explain to new developers.
  • It automatically mirrors your application's own modular design.
  • It can be further refined at will.
  • Printing the logger automatically gives information on the locality of the log statement.

However, this is not the only way for naming loggers. A common alternative is to name loggers by functional areas. For example, the "database" logger, "remoting" logger, "security" logger, or the "XML" logger.

You may choose to name loggers by functionality and subcategorize by locality, as in "DATABASE.MyApp.MyClass" or "DATABASE.MyApp.MyModule.MyOtherClass".

You are totally free in choosing the names of your loggers. The log4net package merely allows you to manage your names in a hierarchy. However, it is your responsibility to define this hierarchy.

Note: by naming loggers by locality one tends to name things by functionality, since in most cases the locality relates closely to functionality.

Back to Top

How do I get the fully-qualified name of a class in a static block?

You can easily retrieve the fully-qualified name of a class in a static block for class X, with the statement typeof(X).Name. Note that X is the class name and span an instance. However because the LogManager.GetLogger method is overloaded to take an instance of Type as well as string usually only the type of the class is required.

Here is the suggested usage template:

public class Foo
	private static readonly ILog log = LogManager.GetLogger(typeof(Foo));
	... other code

An equivalent and more portable solution, though slightly longer, is to use the declaring type of the static constructor.

public class Foo
	private static readonly ILog log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
	... other code

Note: the .NET Compact Framework 1.0 does not support System.Reflection.MethodBase.GetCurrentMethod().

Back to Top

Can the log output format be customized?

Yes. You can implement the ILayout interface to create you own customized log format, or you can extend the LayoutSkeleton class which provides a default implementation of the ILayout interface. Appenders can be parameterized to use the layout of your choice.

Back to Top

Can the outputs of multiple client request go to different log files?

Many developers are confronted with the problem of distinguishing the log output originating from the same class but different client requests. They come up with ingenious mechanisms to fan out the log output to different files. In most cases, this is not the right approach.

It is simpler to use a nested diagnostic context (NDC). Typically, one would NDC.Push() client specific information, such as the client's hostname, ID or any other distinguishing information when starting to handle the client's request. Thereafter, log output will automatically include the nested diagnostic context so that you can distinguish logs from different client requests even if they are output to the same file.

See the NDC and the PatternLayout classes for more information.

Back to Top

What are the configurable options for an appender?

log4net uses public properties to configure components such as Appenders, Layouts, Loggers etc.

Thus, any writable public property in on the appender corresponds to a configurable option. For example, in RollingFileAppender the public int MaxSizeRollBackups { set; } property corresponds to the MaxSizeRollBackups option.

Layouts options are also defined by their writable properties. Same goes for most other log4net components.

Back to Top

Logger instances seem to be create only. Why isn't there a method to remove logger instances?

It is quite nontrivial to define the semantics of a "removed" logger which is still referenced by the user.

Back to Top

Is it possible to direct log output to different appenders by level?

Yes it is. Setting the Threshold option of any appender extending AppenderSkeleton, (most log4net appenders extend AppenderSkeleton) will filter out all log events with a lower level than the value of the threshold option.

For example, setting the threshold of an appender to DEBUG will also allow INFO, WARN, ERROR and FATAL messages to log along with DEBUG messages. (DEBUG is the lowest level). This is usually acceptable as there is little use for DEBUG messages without the surrounding INFO, WARN, ERROR and FATAL messages. Similarly, setting the threshold of an appender to ERROR will filter out DEBUG, INFO and ERROR messages but not FATAL messages.

This policy usually best encapsulates what the user actually wants to do, as opposed to her mind-projected solution.

Back to Top

How do I get multiple process to log to the same file?

The FileAppender holds a write lock on the log file while it is logging. This prevents other processes from writing to the file, therefore it is not possible to have multiple processes log directly to the same log file, even if they are on the same machine.

You may have each process log to a RemotingAppender. The receiving RemoteLoggingServerPlugin (or IRemoteLoggingSink) can receive all the events and send them to a single log file.

Back to Top

If I have many processes across multiple hosts (possibly across multiple time zones) logging to the same file using the method above, what happens to timestamps?

The timestamp is created when the logging event is created. That is so say, when the Debug, Info, Warn, Error or Fatal method is invoked. This is unaffected by the time at which they may arrive at a remote server. Since the timestamps are stored in UTC format inside the event, they all appear in the same time zone as the host creating the logfile. Since the clocks of various machines may not be synchronized, this may account for time interval inconsistencies between events generated on different hosts.

Back to Top

Is there a way to get log4net to automatically reload a configuration file if it changes?

Yes. The DOMConfigurator supports automatic reloading through the ConfigureAndWatch APIs. See the API documentation for more details.

Back to Top

Why should I donate my extensions to log4net back to the project?

Contrary to the GNU Public License (GPL) the Apache Software License does not make any claims over your extensions. By extensions, we mean totally new code that invokes existing log4net classes. You are free to do whatever you wish with your proprietary log4net extensions. In particular, you may choose to never release your extensions to the wider public.

We are very careful not to change the log4net client API so that newer log4net releases are backward compatible with previous versions. We are a lot less scrupulous with the internal log4net API. Thus, if your extension is designed to work with log4net version n, then when log4net release version n+1 comes out, you will probably need to adapt your proprietary extensions to the new release. Thus, you will be forced to spend precious resources in order to keep up with log4net changes. This is commonly referred to as the "stupid-tax". By donating the code and making it part of the standard distribution, you save yourself the unnecessary maintenance work.

If your extensions are useful then someone will eventually write an extension providing the same or very similar functionality. Your development effort will be wasted.

Unless the proprietary log4net extension is business critical, there is little reason for not donating your extensions back to the project.

Back to Top

What should I keep in mind when contributing code?

  1. Stick to the existing indentation style even if you hate it.

    Alternating between indentation styles makes it hard to understand the source code. Make it hard on yourself but easier on others.

  2. Thoroughly test your code.

    There is nothing more irritating than finding the bugs in debugging (i.e. logging) code.

  3. Keep it simple, small and fast.

    It's all about the application not about logging.

  4. Did I mention sticking with the indentation style?

Back to Top

How do I enable log4net internal debugging?

  • To enable log4net's internal debug programmatically you need to set the log4net.helpers.LogLog.InternalDebugging property to true. Obviously the sooner this is set the more debug will be produced.

  • Internal debugging can also be enabled by setting a value in the application's configuration file (not the log4net configuration file, unless they log4net config is in the application's config file). The log4net.Internal.Debug application setting must be set to the value true. For example:

    <?xml version="1.0" encoding="utf-8" ?>
    		<add key="log4net.Internal.Debug" value="true"/>

    This setting is read immediatly on startup an will cause all internal debugging messages to be emmitted.

  • To enable internal debugging from a configuration file, the debug attribute on the log4net configuration element can be set to the value true. For example:

    <log4net debug="true">
    	... configuration ...

    Using this method does require that your configuration file is located and loaded, otherwise the attribute will not be read. If you need to debug the process of locating the configuration file then use one of the other methods for enabling debugging.

Internal debugging messages are witten to the console and to the System.Diagnostics.Trace system. If the application does not have a console the messages logged there will be lost. Note that an application can redirect the console stream by setting the System.Console.Out. The Trace system will by default send the message to an attached debugger (where the messages will appear in the output window). If the process does not have a debugger attached then the messages are sent to the system debugger. A utility like DebugView from may be used to capture these messages.

Back to Top

How fast do bugs in log4net get fixed?

As fast as they get reported ;-)

Back to Top

What is the history of log4net?

log4net is a port of the popular log4j logging library. The initial port was done in July 2001, since then we have tried to remain in the spirit of the original log4j.

Back to Top

How do I report bugs?

Report bugs via email to the mailing list.

Please specify the version of log4net and the framework you are using. It is helpful to include log configurations files if any, plus source code. A short example reproducing the problem is very much appreciated.

Back to Top

Where can I find the latest distribution of log4net?

The log4net project is hosted at Sourceforge.

Back to Top

Why doesn't the EventLogAppender work?

If you are not getting events delivered to the event log this usually indicates a permissions problem. Basically if the event log does not exist the EventLogAppender tries to create it, but you need local administrator permissions to create event logs (just to write into the right bit of the registry). You don't need administrator permissions to log to an existing event log, but it must exist. If you are using the event log from a web application or service using the event log can be a little tricky.

A web application will run as the user account ASPNET. This account deliberately has few permissions to reduce the chances of someone hacking into the web server. While the account has permission to write to the event log it does not have permission to create event sources (registry create and write access), which are needed to write to the event log.

There are a couple of solutions:

  1. Make the ASPNET user a member of the Administrators group. This will work because the user will then have the required permissions. This is not recommended for production use.

  2. As the event source only needs to be created once for the machine, create an installer and configure it to create the event source. The installer will need to be run as Administrator (don't they all). See System.Diagnostics.EventLogInstaller in the Microsoft .NET Framework SDK for an example of how to create a simple event log installer.

Back to Top

Why can't I log to a FileAppender from a web application?

The web application runs as a special user account on the web server called ASPNET. This account has restricted permissions to protect the web server from attacks. By default this account may not have permission to write to the file system. Make sure that the ASPNET account has permission to create and write to files in the directory chosen for logging.

Back to Top