2

我想以编程方式(因为文件路径是在运行时生成的)为 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 似乎记录到两个日志文件。有什么建议么?

4

2 回答 2

8

ColeW 的答案是正确的。为了防止调用调用层次结构中的所有附加程序,请通过设置 Additivity 标志来禁用继承的附加程序。

以编程方式,如下所示:

((log4net.Repository.Hierarchy.Logger)log.Logger).Additivity = false; 
于 2014-03-14T14:37:47.173 回答
1

您应该尝试将可加性设置为 false。

http://logging.apache.org/log4net/release/sdk/log4net.Repository.Hierarchy.Logger.Additivity.html

于 2012-08-21T01:16:46.540 回答