In today's tutorial, you will learn how to set up a Log4Net appender and write the code required to write custom logs into it, all within an Episerver CMS powered website. Having a good logging strategy is essential when fixing live production issues. Episerver CMS ships with the Log4Net package with its own log appenders.
The problem with adding your custom logs into the general-purpose one is that it can be harder to track down issues. Often it is simpler to just create a custom log to make finding your own messages quicker. 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. If you want to learn how to write logs into their own files. this is the article for you 🔥🔥🔥
Setting Up Logging
In your webroot, you should see a file called EPiServerLog.config
. This is where all the Log4Net configuration is stored. To create a custom log appender you will need to update this file. After opening the file, the first thing you should see is the default appender that Episerver uses. In the appender
section, you should see an appender called errorFileLogAppender
. The easiest way to create a second appender is to copy the existing appender definition and give it another name, like this:
You need to update the definition with three things. You need to define where the log file will be written on the server. You need to define the name of the file. Finally, in the filter section, you need to set the logging level. I am using errors and information logs, change this to whatever you need. After we have an appender definition 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
. As above, copy the existing one and rename it!
This configuration is telling Log4Net that when we make a call to write to the CustomLogAppender
logger, use the appender we defined above. Here we also define the logging level, this can be All,
Debug
, Info
or Error
. Using All
can hurt performance so be warned! This is everything we need to do, to configure Log4Net. The next step is to start writing logs into it. To write to the new log file we just need to tell Log4Net which appender to use when we define the ILog
instance:
After running this code, you should now see a log in your new log file 💥
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. To write to the log file, add the appended name when defining an ILog
instance. It really is that simple! Happy Coding 🤘