Log4net不会使用AdoNetAppender MVC在数据库中注册

时间:2018-11-05 12:07:42

标签: sql asp.net-mvc log4net adonetappender

我是log4net记录器的新手,我正在尝试使用AdoNetAppender创建记录器以将日志保存到数据库中。

当我使用简单布局

<conversionPattern value="%date [%thread] %-5level %logger - %message%newline" />

并保存到数据库:

<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>

它成功保存到数据库;问题是我需要注册更多详细信息(位置,方法,行),但无法将其保存在数据库中。

为此,我使用了以下配置:

    <layout type="log4net.Layout.PatternLayout">
   <conversionPattern value="%date [%thread] %-5level %logger %location 
    %method %line - %message %newline" />
   </layout>

对于数据库插入:

    <commandText value="INSERT INTO Log( [Date],[Thread],[Level],[Logger], 
    [Locaotion],[Method],[Line],[Message],[Exception]) 
                    VALUES (@log_date, @thread, @log_level, 
    @logger,@location @method, @line,  @message, @exception)" />
     <parameter>
  <parameterName value="@location" />
  <dbType value="String" />
  <size value="255" />
  <layout type="log4net.Layout.PatternLayout">
    <conversionPattern value="%location" />
  </layout>
  </parameter>

 <parameter>
<parameterName value="@method" />
<dbType value="String" />
<size value="255" />
<layout type="log4net.Layout.PatternLayout">
    <conversionPattern value="%method" />
  </layout>
 </parameter>

<parameter>
<parameterName value="@line" />
<dbType value="String" />
<size value="50" />
<layout type="log4net.Layout.PatternLayout">
    <conversionPattern value="%line" />
</layout>
</parameter>

我的C#代码:

private static ILog log = LogManager.GetLogger(typeof(HomeController));
//private static readonly ILog log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

如何将完整的错误详细信息保存在数据库中?

1 个答案:

答案 0 :(得分:1)

我得到的错误是我忘记了数据库插入代码中的(,),而我在全局中添加了Application_Error

conversionPattern代码:

    <layout type="log4net.Layout.PatternLayout">
    <conversionPattern value="%date [%thread] %-5level %logger [%location] [%method] [%line] - %message %newline" />
  </layout>

数据库插入代码:

  <commandText value="INSERT INTO Log( [Date],[Thread],[Level],[Logger],[Location],[Method],[Line],[Message],[Exception]) 
                              VALUES (@log_date, @thread, @log_level, @logger, @location, @method, @line, @message, @exception)" />

以及全局代码:

    private static readonly ILog log = LogManager.GetLogger(typeof(MvcApplication));

    private void Application_Error(Object sender, EventArgs e)
    {
        var ex = Server.GetLastError().GetBaseException();

        log.Error("App_Error", ex);
    }