Log4net自定义ADO Appender(无配置):数据不会进入数据库

时间:2013-04-24 20:48:56

标签: c# oracle log4net log4net-appender

使用log4net(C#)和Oracle,我正在尝试创建一个自定义ADO Appender,这样我就不需要使用配置文件了。我的代码到目前为止

public static void CreateAppender()
{
    var hierarchy = (Hierarchy)LogManager.GetRepository();
    hierarchy.Root.RemoveAllAppenders();

    var ADOAppender = new AdoNetAppender();
   AddDateTimeParameterToAppender(ADOAppender, ":log_date", "log4net.Layout.RawTimeStampLayout");
   AddStringParameterToAppender(ADOAppender, ":thread", 255, "%thread");
   AddStringParameterToAppender(ADOAppender, ":log_level", 50, "%level");
   AddStringParameterToAppender(ADOAppender, ":logger", 255, "%logger");
   AddStringParameterToAppender(ADOAppender, ":message", 30000, "%message");

   ADOAppender.ConnectionType =
            "System.Data.OracleClient.OracleConnection, System.Data.OracleClient, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";

   ADOAppender.CommandText =
            "INSERT INTO Log (Datetime,Thread,Log_Level,Logger,Message) VALUES (:log_date, :thread, :log_level, :logger, :message)";

   ADOAppender.ConnectionString = "data source=[db];User ID=[id];Password=[pass]";

   ADOAppender.BufferSize = 1;

  ADOAppender.ActivateOptions();

  log4net.Config.BasicConfigurator.Configure(ADOAppender);
}

public static void AddDateTimeParameterToAppender(AdoNetAppender appender, string paramName, string conversionPattern)
{
       var param = new AdoNetAppenderParameter { ParameterName = paramName, DbType = System.Data.DbType.DateTime, Layout = new Layout2RawLayoutAdapter(new PatternLayout(conversionPattern)) };
   appender.AddParameter(param);
}

public static void AddStringParameterToAppender(AdoNetAppender appender, string paramName, int size, string conversionPattern)
{
   var param = new AdoNetAppenderParameter
   {
      ParameterName = paramName,
      DbType = System.Data.DbType.String,
      Size = size,          
      Layout = new Layout2RawLayoutAdapter(new PatternLayout(conversionPattern))
   };
appender.AddParameter(param);

}

我没有得到任何异常,但没有数据插入数据库。我几乎肯定它与参数有关,因为当我将所有值设置为null时,它可以工作。

有谁看到我做错了什么?我用谷歌搜索了很多,但我找到的所有例子都没有使用过ADO Appender。感谢

2 个答案:

答案 0 :(得分:1)

我有过与ADONetAppender相似的经历。你打开了内部log4net调试吗?我不记得我的问题的具体细节,但在打开调试后,我能够弄明白。

http://logging.apache.org/log4net/release/faq.html#internalDebug

另外,我确信你有,但确保你的项目中有'XmlConfigurator'行。

详细信息: Log4Net not writing to the database

答案 1 :(得分:0)

Tobyb,谢谢你的回复,我弄清楚我做错了什么。添加DateTime参数时,我需要将布局设置为Layout2RawLayoutAdapter RawTimeStampLayout()。我需要将Layout = new Layout2RawLayoutAdapter(new PatternLayout(conversionPattern))替换为Layout = new RawTimeStampLayout()。我更新的AddDateTimeParameterToAppender方法如下所示..

public static void AddDateTimeParameterToAppender(AdoNetAppender appender, string paramName)
{
    var param = new AdoNetAppenderParameter
    {
        ParameterName = paramName, 
        DbType = System.Data.DbType.DateTime,
        Layout = new RawTimeStampLayout()
    };

    appender.AddParameter(param);
}