In today's tutorial, you will learn how to set up a second Log4Net appender and logging information to it.
When we install Episerver, the Log4Net package also gets installed. Having a pre-configured Log4Net file means that writing errors and information toa log file information is simple.
As your website grows, only having a single log file can be problematic.. especially when you need to fix errors quickly. In a lot of situations, it sometimes makes more sense to create separate log files to differentiate between errors in your custom codes logs and errors within Episerver, to make life easier. Imagine, when your website goes down and you need to find the cause of the issue fast, from experience if you log every single issue and error into one single log file it can become too verbose and difficult to track things down.
By splitting your logging into different files, you have a greater sense of control. In most projects, people forget to do this until it's too late, so I would strongly recommend thinking about this sooner rather than later.
Setting Up Logging
When you install Episerver in your webroot you should see a file called 'EPiServerLog.config'. This is where all the Log4Net configuration is stored. The first thing we need to do is open this file up and take a peek inside. The first thing you should see is the default appender that Episerver uses, in the appender section, called 'errorFileLogAppender'. To log to a second file we need to copy the whole appender definition and give it another name, like so:
The file tag defines where the new text file will be written to and what it will be called. In the filter section, we have set the logging to display errors and information statements. You can change this to whatever you need.
After we have an appender defined, we need to define a Logger so Log4Net can start writing to it. If you scroll down the file, you should come to a section that defines the Logger. Within this file, you need to create one for the appender above.
This is telling Log4Net that when we make a call to write to the CustomLogAppender logger, use the appender we defined above. In here we also define the logging level, this can be All, Debug, Info or Error. Using All can hurt performance so I would recommend using 'Error' by default.
This is everything we need to do, to configure Lo4Net. The next step is to start using it. To write to the new log file we just need to tell Log$Net which appender to use when we define the ILog instance.
Being able to split your log information into different files can make troubleshooting a lot easier. To do this we need to configure Log4Net. In the 'EPiServerLog.config' we define a new appender and register it with Log4NEt, we then pass the registration name into Log4Net when we define an instance to it in code, to start logging to a different file. It really is that simple!