In this tutorial, you will learn how to write log messages within a website powered by Episerver CMS. Episerver uses Log4Net as its default log handler. The benefit of using Log4Net to write custom logs for a developer is that you can also use it with very minimal configuration. It is far easier to use Log4Net compared to building a custom solution yourself, or, importing additional bloat from Nuget 📜
To start using Log4Net, all you have to do is enable a custom log appender in config and then write some code to log a message, everything else is done for you. To get started using Log4Net you will need to make a few tweaks to a file calledEPiServerLog.config
(found in your webroot). This is where all the logging configuration lives. At the end of that file, you should see a section that looks similar to the code snippet below. To enable Log4Net on your site in a custom log file, you can define a customer lof appender. The config should look like this :
Next, register the appender:
That's all there is to it, Log4Net is now configured for your site.. simple hey? The next step is sending your log messages to Log4Net to the handler. First, you need to add a reference to the package in your class:
Your next step is to declare the logger. This can be done as an instance field in your class:
In the code above, there are two examples of how to call Log4NET. One version will use the custom log appender we defined. The other uses reflection to tell Log4Net the class name to log. This will be logged in the default Episerver logs. This code will allow you to write cleaner code. If you rename the class, you don't have to remember to update the logging code! I normally add this code into a base class so I only define my logging code once avoiding duplication, however, it's up to you. If you want to log an error, send any exceptions you may trap to Log4Net like this:
This code snippet is pretty simple,. You call Log4Net rather than throwing the exception. I also find the Logger.Info()
method pretty useful at times and I recommend that you do some research on it. Now you have your system up and running how do you read these exceptions? Within your webroot, you should now have a file called 'MyCustomLog.txt' in App_Data
. In Episerver, the default is to log all warnings (set in the EPiServerLog.config
file). I normally only set my logger to log fatal and errors as the warning level is too verbose. For reference, you can use FATAL
, ERROR
, WARN
, INFO
, or DEBUG
. That's all there is to it. Happy Coding 🤘