Search code examples
logginglog4netlog4net-configurationjsnlog

Configure jsnlog.log4net log file path


My MVC application uses log4net for server logging and I just added jsnlog.log4net for javascript logging. I followed the official guide to configure it and it's working perfectly. And I didn't do any changes to log4net.config file.

Now both log4net and jsnlog use same txt file to log their logs. I need to separate there logs to two different files. So that I can easily identify server logs and javascript logs.

Here is my log4net.config file.

<?xml version="1.0" encoding="utf-8" ?>
<log4netConfiguration>
  <configSections>
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
  </configSections>
  <appSettings>
    <add key="log4net.Config" value="log4net.config" />
  </appSettings>
  <log4net>
    <appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
      <file type="log4net.Util.PatternString" value="C:\buttonwood_logs\buttonwood_web_log\buttonwood_log_%date{ddMMyyyy}.log" />
      <appendToFile value="true" />
      <rollingStyle value="Size" />
      <maxSizeRollBackups value="5" />
      <maximumFileSize value="5MB" />
      <datePattern value="yyyyMMdd" />
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%4t %d{ABSOLUTE} %-5p %m%n"/> 
      </layout>
    </appender>
    <root>
      <level value="INFO" />
      <appender-ref ref="RollingFileAppender" />
    </root>
  </log4net>
</log4netConfiguration>

Solution

  • To log to two files you need to have two appenders, and a logger for each one.

    As you've got a root element defined in your config, the easiest way is to set up a specific logger for your JavaScript code, and let everything else go to the existing appender:

    <!-- additivity=false means "don't inherit appenders from the root logger" -->
    <logger name="JSLogger" additivity="false"> 
      <level value="INFO" />
      <appender-ref ref="JSFileAppender" />
    </logger>
    

    Then set up the appender:

    <appender name="JSFileAppender" type="log4net.Appender.RollingFileAppender">
            <file type="log4net.Util.PatternString" 
                 value="C:\buttonwood_logs\jslog\buttonwood_log_%date{ddMMyyyy}.log" />
            … etc.
    

    When you create the logger in jsnlog then you must then reference it by name, e.g. GetLogger("JSLogger")