3
votes

I have a log4net file appender configured that all my log files should use:

<appender name="FileAppender" type="log4net.Appender.RollingFileAppender">
    <file type="log4net.Util.PatternString" value="..\Logs\"/>
    <appendToFile value="true"/>
    <datePattern type="log4net.Util.PatternString" value="yyyyMMdd'.Log'"/>
    <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="[%date][%-5level][%logger] %message%newline"/>
    </layout>
</appender>

The directory and date pattern is hard-coded. I have different loggers that should use the exact same configuration, but just with a different folder name.

For now, I ended up copying and pasting each block into a new appender, but is there a way to configure log4net to 'share' a common appender's settings?

2

2 Answers

0
votes

This is not possible unless you configure log4net programmatically.

0
votes

At least part of the config does need to be accomplished programmatically:

Call this before Configure():

    log4net.GlobalContext.Properties["SysLogFileName"] = syslogFileName;

Use this to update:

    public static void ChangeSyslogFile(string syslogFileName)
    {
        var hier = log4net.LogManager.GetRepository() as Hierarchy;
        if (hier == null)
        {
            Console.WriteLine("Unable to change Syslog filename, null hierarchy");
            return;
        }
        var sysLogAppender =
            (RollingFileAppender) hier.GetAppenders().
                                      First(appender => appender.Name.Equals("SimulatedSysLogFile", 
                                          StringComparison.InvariantCultureIgnoreCase));

        if (null == sysLogAppender)
        {
            Console.WriteLine("Unable to change Syslog filename, appender not found");
            return;
        }
        sysLogAppender.File = syslogFileName;
        sysLogAppender.ActivateOptions(); 
    }

This is my config:

  <appender name="SimulatedSysLogFile" type="log4net.Appender.RollingFileAppender">                 
    <file type="log4net.Util.PatternString" value="%property{SysLogFileName}" />
    <appendToFile value="true" />
    <lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
    <maximumFileSize value="10MB" />
    <maxSizeRollBackups value="10" />
    <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%date{M/dd/yyyy h:mm:ss tt} %message %newline" />
    </layout>
</appender>