程序化Log4Net配置复制条目

时间:2012-08-20 21:45:02

标签: c# log4net

我想以编程方式(因为文件路径是在运行时生成的)为SQL语句创建单独的日志文件。我的代码看起来像这样

  public static void InitializeLogger(FileInfo logFile, FileInfo sqlLogFile, 
             Level threshhold, string layout = PATTERN_LAYOUT, bool rolling = true)
    {
        var hierarchy = (Hierarchy)LogManager.GetRepository();
        var appender = CreateAppender(true, layout, APPENDER_NAME, logFile, threshhold);
        hierarchy.Root.AddAppender(appender);

        var sqlAppender = CreateAppender(rolling, layout, SQL_APPENDER_NAME, sqlLogFile, Level.Info);

        var sqlLogger = (Logger)LogManager.GetLogger(SQL_LOGGER_NAME).Logger;
        sqlLogger.RemoveAllAppenders();
        sqlLogger.AddAppender(sqlAppender);
        sqlLogger.Level = Level.Info;
    }

    private static FileAppender CreateAppender(bool rolling, string layout, string appenderName, FileInfo fileInfo, Level threshhold)
    {
        FileAppender result;
        if (rolling)
        {
            result = new RollingFileAppender
                     {
                         AppendToFile = true,
                         ImmediateFlush = true,
                         Name = appenderName,
                         Layout = new PatternLayout(layout),
                         Threshold = threshhold,
                         File = fileInfo.FullName,
                         RollingStyle = RollingFileAppender.RollingMode.Date,
                         StaticLogFileName = true
                     };
        }
        else
        {
            result = new FileAppender
                     {
                         AppendToFile = true,
                         ImmediateFlush = true,
                         Name = appenderName,
                         Layout = new PatternLayout(layout),
                         Threshold = threshhold,
                         File = fileInfo.FullName
                     };
        }
        result.ActivateOptions();
        return result;
    }

    public static void LogSQL(this ILog logger, string sql)
    {
        var sqlLogger = LogManager.GetLogger(SQL_LOGGER_NAME);
        sqlLogger.InfoFormat("Sql: {0}", sql);
    }

问题是LogSQL似乎记录到两个日志文件。有什么建议吗?

2 个答案:

答案 0 :(得分:8)

ColeW的回答是正确的。要防止调用调用层次结构中的所有appender,请通过设置Additivity标志来禁用继承的appender。

以编程方式,如下所示:

((log4net.Repository.Hierarchy.Logger)log.Logger).Additivity = false; 

答案 1 :(得分:1)