Search code examples
c#common.logging

How can I understand if a logger exists in common logging?


I use Common.Logging in my application and I created a separate logger to write some debug info.

I can retrieve my logger using

LogManager.GetLogger("MyCustomLogger");

However, if this logger is not found I get the root one. I wish that if the logger is not found, nothing will be logged. I cannot remove the root logger because of the structure of my application.

How can I achieve this behavious using Common.Logging?

The config is

<common>
    <logging>
      <factoryAdapter type="Common.Logging.Log4Net.Log4NetLoggerFactoryAdapter, Common.Logging.Log4net1213">
        <!-- Common Logging assumes that log4net is initialized -->
        <arg key="configType" value="EXTERNAL"/>
      </factoryAdapter>
    </logging>
  </common>

  <log4net>
    <appender name="FileAppender" type="log4net.Appender.RollingFileAppender">
      <file value="Log/debug.txt"/>
      <appendToFile value="true"/>
      <maximumFileSize value="10000KB"/>
      <rollingStyle value="Size"/>
      <maxSizeRollBackups value="5"/>
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%d{yyyy-MM-dd HH:mm:ss.fff} [%t] %-5p %c - %m%n"/>
      </layout>
    </appender>

    <appender name="MyCustomLogAppender" type="log4net.Appender.RollingFileAppender">
      <file value="Log/queries.txt" />
      <appendToFile value="true" />
      <maximumFileSize value="50000KB" />
      <rollingStyle value="Size" />
      <maxSizeRollBackups value="5" />
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%d{yyyy-MM-dd HH:mm:ss.fff} [%t] %-5p %c - %m%n" />
      </layout>
    </appender>
    <!-- levels: DEBUG, INFO, WARN, ERROR, FATAL -->
    <root>
      <level value="DEBUG"/>
      <appender-ref ref="FileAppender"/>
    </root>

    <logger name="MyCustomLog" additivity="false">
      <level value="DEBUG" />
      <appender-ref ref="MyCustomLogAppender" />
    </logger>
  </log4net>

Solution

  • I got the same problem. I wanted to return if the specified logger was not configured.

    The solution I found :

    private static ILog _log;
    
    protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
    
        if (LogManager.Exists("MyCustomLoggerName") == null)
            return;
    
        if (_log == null)
            _log = LogManager.GetLogger("MyCustomLoggerName");
    
        ... 
    }
    

    I couldn't declare private static readonly ILog _log = LogManager.GetLogger("MyCustomLoggerName"); because then LogManager.Exists("MyCustomLoggerName") returned something...

    In the log4net.config file, I set additivity="false" for this logger.