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