C# – Setting up a default log when Logger not found in Log4Net

.netc++log4netlogging

I am using Log4Net as the logging mechanism for an application of ours. Our configuration is contained in a config file and in our code we programatically invoke which of our several loggers (mostly using FileAppenders) we want to invoke. Recently I realized that one of our log files was not being populated, and I tracked it down to a string mismatch, between the name in our configuration file and the name we were programatically invoking in our code. Because the LogManager could not find the specified logger the root was returned, which for our config is not setup to meaningfully log anywhere.

My question is, is there a way to setup log4net to allow for using specific loggers, but that will fall back to a general logger if the specified logger is not found?

For example using a configuration file like this

<configuration>
<configSections>
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net" />
</configSections>

<log4net>
    <root>
        <level value="ALL" />
        <appender-ref ref="ConsoleAppender" />
    </root>

    <logger name="TestFileLogger">
        <level value="ALL" />
        <appender-ref ref="TestFileAppender" />
    </logger>

    <appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender">
        <layout type="log4net.Layout.PatternLayout">
            <param name="ConversionPattern" value="%d [%t] %-5p [%x] - %m%n" />
        </layout>
    </appender>

    <appender name="TestFileAppender" type="log4net.Appender.RollingFileAppender">
        <param name="File" value="TestLog" />
        <param name="DatePattern" value=".yyyyMMdd&quot;.log&quot;" />
        <param name="AppendToFile" value="true" />
    </appender>

</log4net>
</configuration>

And invoking the loggers in C# like this

var fileLogger = LogManager.GetLogger("TestFileLogger");
fileLogger.Info("This logs appropriately.");

var bogusLogger = LogManager.GetLogger("Bogus");
bogusLogger.Info("This should go to a general log. Bogus is not a recognized appender");

Is there a good way to log the messages from bogusLogger to some kind of general log file? My initial thought was to create a general file appender that is part of the root node, but this is very noisy as ALL log messages will be routed to this file. Is there a way to ONLY route messages that are not captured in another log file?

Best Solution

You could use LogManager.Exists("Bogus") to determine if the bogus-logger or your default implementation should be used.

You could create an extensionmethod on LogManager that could handle it for you.