log4net - 如何在AdoNetAppenderParameter.Layout上调用ActivateOptions

时间:2016-08-05 20:42:47

标签: log4net log4net-appender

我正在尝试动态配置log4net以将日志写入sql数据库。为此,我使用log4net库中的AdoNetAppender类。

我看到了appender的activateOptions,但没有看到Command Parameters

中定义的Layout
public override void ActivateOptions();

调用AdoNetAppender.ActivateOptions()将日志写入数据库,但将相同数据写入所有列,而不是将相应数据写入相应列

我认为这与布局上的ActiveOptions有关,但我没有看到ActivateOptions for Layout。

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

对于任何面临此问题的人。下面的解决办法诀窍:

public class CustomAdoNetAppender : AdoNetAppender
{
         //code omitted for simplicity
         //parameter using inherited layout
         AddParameter(new AdoNetAppenderParameter()
        {
            ParameterName = "@thread",
            DbType = System.Data.DbType.String,
            Size = 255,
            Layout = new CustomLayout2RawLayoutAdapter(new PatternLayout() { ConversionPattern = "%thread" })
        });
}

private class CustomLayout2RawLayoutAdapter : Layout2RawLayoutAdapter
    {
        private readonly PatternLayout _layout;
        public CustomLayout2RawLayoutAdapter(PatternLayout layout)
            : base(layout)
        {
            _layout = layout;
        }

        public void ActivateOptions()
        {
            _layout.ActivateOptions();
        }
    }

 public override void ActivateOptions()
    {
        base.ActivateOptions();

        if (m_usePreparedCommand)
        {
            foreach (AdoNetAppenderParameter item in m_parameters)
            {
                if (item.Layout is CustomLayout2RawLayoutAdapter)
                    (item.Layout as CustomLayout2RawLayoutAdapter).ActivateOptions();
            }
        }
    }