Log4net不会使用`AdoNetAppender`写入数据库

时间:2017-06-05 06:55:36

标签: log4net adonetappender

我使用AdoNetAppender将日志写入数据库 连接很好,因为我看到记录器已连接到数据库 此外,如果我在连接中更改数据库名称,我可以在log4net跟踪中看到错误,因此连接良好,但数据库表仍然是空的。

这是配置文件:

<log4net>
<appender name="AdoNetAppender" type="log4net.Appender.AdoNetAppender">
  <bufferSize value="100" />
  <connectionType value="System.Data.SqlClient.SqlConnection, System.Data, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
  <connectionString value="data source=(localdb)\MSSQLLocalDB;initial catalog=LogsAffiliatePortal;integrated security=true;persist security info=True;" />
  <commandText value="INSERT INTO Log ([Date],[Thread],[Level],[Logger],[Message],[Exception]) VALUES (@log_date, @thread, @log_level, @logger, @message, @exception)" />
  <parameter>
    <parameterName value="@log_date" />
    <dbType value="DateTime" />
    <layout type="log4net.Layout.RawTimeStampLayout" />
  </parameter>
  <parameter>
    <parameterName value="@thread" />
    <dbType value="String" />
    <size value="255" />
    <layout type="log4net.Layout.PatternLayout">
      <conversionPattern value="%thread" />
    </layout>
  </parameter>
  <parameter>
    <parameterName value="@log_level" />
    <dbType value="String" />
    <size value="50" />
    <layout type="log4net.Layout.PatternLayout">
      <conversionPattern value="%level" />
    </layout>
  </parameter>
  <parameter>
    <parameterName value="@logger" />
    <dbType value="String" />
    <size value="255" />
    <layout type="log4net.Layout.PatternLayout">
      <conversionPattern value="%logger" />
    </layout>
  </parameter>
  <parameter>
    <parameterName value="@message" />
    <dbType value="String" />
    <size value="4000" />
    <layout type="log4net.Layout.PatternLayout">
      <conversionPattern value="%message" />
    </layout>
  </parameter>
  <parameter>
    <parameterName value="@exception" />
    <dbType value="String" />
    <size value="2000" />
    <layout type="log4net.Layout.ExceptionLayout" />
  </parameter>
</appender>

  <root>
    <level value="ALL" />
    <appender-ref ref="AdoNetAppender" />
  </root>
  </log4net>

以下是我如何使用日志:

public class Global : HttpApplication
{
   private static readonly ILog log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

    void Application_Start(object sender, EventArgs e)
    {

      var configFile = ConfigurationManager.AppSettings.Get("MyLog4NetConfigFile");
         if (!string.IsNullOrEmpty(configFile))
          {

             var f = HostingEnvironment.ApplicationPhysicalPath  +Environment.ExpandEnvironmentVariables(configFile);
                    XmlConfigurator.Configure(new FileInfo(f));
         }

                log.Debug("yes");
                log.Error("test");
    }
}

1 个答案:

答案 0 :(得分:0)

一个常见问题是您希望有一条日志消息,但log4net正在缓冲。将bufferSize更改为1:

<bufferSize value="1" />

将直接记录所有消息。