we may come across a real-world problem where we may need to write a few log entries in one file and few to another file.
To achieve this, it is very simple in .Net using log4net.
Below are the few steps that we need to follow,
Changes required in Log4net.config file
Look for the below section of the XML tag, it can be in the application config file or in the Log4net file as it depends based on the initial configuration.
The below screenshot shows the full config section that needs to be changed.
As highlighted, here I have added a custom appender as well as a logger tag to the log4net section.
- To create a new log file, we must add the appender tag and define the type of it, here I have declared as Fileappender. We can also define as RollingFileAppender, it depends on requirement. Please check log4net documentation for more details on these terms. All subtags inside an appender tag is a must.
- The logger section is required to point the reference of the custom appender section. As shown in the screenshot, <appender-ref ref=”TSIP”/> will point to our custom appender. Keeping the value of additivity to false will make sure that the log entries written in the TSIP file won't be written in the main log file, i.e. root.log file in our case.
Changes required in the backend class file
- private static readonly ILog tmacLog = LogManager.GetLogger("TSIP"); // use this to log to TSIP.log file
- private static readonly ILog logger = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); // to log to main log file, i.e. root