我使用AdoNetAppender激活了log4net,将日志存储在Sql Server数据库中。
执行后,我看到所有参数(DateTime除外)都填充了消息值。
我自己在代码中创建了适配器(没有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;
}
答案 0 :(得分:0)
我弄清楚是怎么回事。我总是得到消息的原因是因为它使用了PatternLayout类中配置的默认ConversionPattern
public const string DefaultConversionPattern = "%message%newline";
看起来在代码中设置ConversionPattern属性没有任何影响。 您需要通过PatternLayout类的构造函数提供模式。
databaseAppender.AddParameter(new AdoNetAppenderParameter
{
ParameterName = "@level",
DbType = System.Data.DbType.String,
Size = 50,
Layout = (IRawLayout)layoutConverter.ConvertFrom(new PatternLayout("%-5p"))
});