log4net %property does not work

2019-06-27 09:08发布

问题:

I have a small test project with the following code:

class Program
{
    static void Main(string[] args)
    {
        log4net.GlobalContext.Properties["logFileName"] = "log.txt";
        log4net.Config.XmlConfigurator.Configure(new System.IO.FileInfo("log4net.xml"));

        log4net.ILog logger = log4net.LogManager.GetLogger("Tests");

        logger.Debug("Test message");
    }
}

My log4net.xml config file has the following content:

<?xml version="1.0" encoding="utf-8" ?>
<log4net>
    <appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
        <file value="%property{logFileName}" />
        <appendToFile value="true" />
        <rollingStyle value="Size" />
        <maxSizeRollBackups value="10" />
        <maximumFileSize value="100KB" />
        <staticLogFileName value="true" />
        <layout type="log4net.Layout.PatternLayout">
            <conversionPattern value="%utcdate{ISO8601} [%level][%logger] %message%newline" />
        </layout>
    </appender>
    <root>
        <level value="ALL" />
        <appender-ref ref="RollingFileAppender" />
    </root>
</log4net>

My question is why does log4net create file with name %property{logFileName} and doesn't substitutes it with log.txt?

log4net library is taken from NuGet (Id:log4net Version:2.0.3).

回答1:

Please use this in your xml config

<file type="log4net.Util.PatternString" value=".\%property{logFileName}" />