我使用 AdoNetAppender 激活 log4net 以将日志存储在 Sql Server 数据库中。
执行后,我看到所有参数(日期时间除外)都填满了消息值。
我确实在代码中自己创建了适配器(没有 xml 配置),所以我假设我可能忘记调用一种方法来使模式映射工作?
var root = ((Hierarchy)LogManager.GetRepository()).Root;
root.AddAppender(this.CreateDBAppender());
root.Repository.Configured = true;
this.log = LogManager.GetLogger("MyLogger");
private IAppender CreateDBAppender()
{
...
RawLayoutConverter layoutConverter = new RawLayoutConverter();
var databaseAppender = new AdoNetAppender
{
Name = "MyLogger",
ConnectionString = "...",
CommandText = @"INSERT INTO [Log] ([DateTime], [Exception], [Host], [Level], [Logger], [Message], [Severity], [Thread])
VALUES (@logdate, @exception, @host, @level, @logger, @message, @severity, @thread)",
CommandType = System.Data.CommandType.Text,
ConnectionType = "System.Data.SqlClient.SqlConnection"
};
databaseAppender.AddParameter(new AdoNetAppenderParameter
{
ParameterName = "@logdate",
DbType = System.Data.DbType.DateTime,
Layout = new RawTimeStampLayout()
});
databaseAppender.AddParameter(new AdoNetAppenderParameter
{
ParameterName = "@message",
DbType = System.Data.DbType.String,
Size = 4000,
Layout = (IRawLayout)layoutConverter.ConvertFrom(new PatternLayout
{
ConversionPattern = "%m"
})
});
databaseAppender.AddParameter(new AdoNetAppenderParameter
{
ParameterName = "@host",
DbType = System.Data.DbType.String,
Size = 50,
Layout = (IRawLayout)layoutConverter.ConvertFrom(new PatternLayout
{
ConversionPattern = "%property{host}"
})
});
databaseAppender.AddParameter(new AdoNetAppenderParameter
{
ParameterName = "@level",
DbType = System.Data.DbType.String,
Size = 50,
Layout = (IRawLayout)layoutConverter.ConvertFrom(new PatternLayout
{
ConversionPattern = "%level"
})
});
//// more parameters ...
databaseAppender.ActivateOptions();
return databaseAppender;
}