EPiWiki.se  - EPiServer notes shared with others

Create a log message programmatically

How to use EPiServers CMS log functionality to create your own log messages.

Create a logger

Start adding log4net as a reference for yor project.

using log4net;

public class MyClass
   private static readonly ILog _log = LogManager.GetLogger(typeof(MyClass));

Write a debug message to the log

if (_log.IsDebugEnabled)
   _log.Debug("Test logger");

Design tips: Always check if the logger is enabled before doing a lot of stuff.
Otherwise the debug code is going to slow your application down even if it’s not enabled.

Write an error message to the log

catch (MyException ex)
   _log.Error("Can't execute test code, because", ex);

Design tips: Never leave a catch block empty, if the exception is handled some
other way please write a comment about this in the block.

Log levels

It is easy to create log messages in EPiServer, use the correct log levels and you site will be a lot easier to troubleshoot
DEBUG – Debug level to examine one functionality in deep a lot of messages for each request
INFO – Information logging done by functionality that isn't logged for each request
WARN – Errors that the application can handle. The recommended mode of an EPiServer installation in production
ERRORS – Errors that the application can not handle and are displayed to the end user
FATAL – Errors that will cause a application crash
Some functionality in EPiServer doesn't follow those roles with can makes the generated log unreadable. But a error log in production should be readable and not growing to much. Log4net can be configured to exclude those messages in the EPiServerLog.config file.

Version author:
Mattias Lövström

EPiServer version