以编程方式改变log4net的fileappender

时间:2013-11-29 05:02:24

标签: c# .net log4net

我正在尝试使用log4net设置日志记录,在wpf应用程序中没有log4net的经验

取自this SO answer,我有

public partial class App : Application
{
    private static readonly ILog Log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
    protected override void OnStartup(StartupEventArgs e)
    {
        XmlConfigurator.Configure();
        base.OnStartup(e);

        //Set data directory
        string baseDir = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData) + @"\BlowTrial";
        if (!Directory.Exists(baseDir))
        {
            Directory.CreateDirectory(baseDir);
        }

        //Set logging
        foreach (var appender in LogManager.GetRepository().GetAppenders())
        {
            var fileAppender = appender as FileAppender;
            if (fileAppender != null)
            {
                fileAppender.File = fileAppender.File.Replace("|DataDirectory|", baseDir);
                     ...

LogManager.GetRepository().GetAppenders()中没有元素,尽管app.config在配置节点中具有以下内容:

<configSections>
  <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,Log4net"/>
</configSections>
<log4net>
<root>
  <level value="DEBUG"/>
  <appender-ref ref="LogFileAppender"/>
  <appender-ref ref="ColoredConsoleAppender"/>
</root>
<appender name="LogFileAppender" type="log4net.Appender.RollingFileAppender">
  <param name="File" value="|DataDirectory|\log.txt"/>
  <param name="AppendToFile" value="true"/>
  <rollingStyle value="Size"/>
  <maxSizeRollBackups value="10"/>
  <maximumFileSize value="1MB"/>
  <staticLogFileName value="false"/>
  <layout type="log4net.Layout.PatternLayout">
    <conversionPattern value="%date [%thread] %-5level %logger: %message%newline"/>
  </layout>
</appender>
<appender name="ColoredConsoleAppender" type="log4net.Appender.ConsoleAppender">
  <layout type="log4net.Layout.PatternLayout">
    <conversionPattern value="%date [%thread] %-5level %logger: %message%newline"/>
  </layout>
</appender>
</log4net>

我想知道为什么appender“LogFileAppender”不是LogManager.GetRepository().GetAppenders()方法中的元素,以及我如何更改文件的名称?

感谢您的专业知识

1 个答案:

答案 0 :(得分:2)

RollingFileAppender在初始化时使用XmlConfigurator.Configure();)在内部执行一些操作,这会导致|DataDirectory|\log.txt在尝试检索路径时抛出System.ArgumentException的路径。如果需要更多详细信息here,可以查看如何调试log4net。

根据this answer,由于你正在使用特殊的文件夹路径,你可以在app.config中指定它,而不用担心从代码中设置路径:

<param name="File" type="log4net.Util.PatternString" value="%envFolderPath{CommonApplicationData}\\BlowTrial\\log.txt"/>