P.K.
P.K.

Reputation: 1772

log4net is not logging exceptions to database, no errors displayed

Strange but my MVC4 application is not logging exception to database. When exception appears ExceptionHandlingAttribute is started, log entry should be created, but it's not. No errors for log4not are displayed in VS's debug window or Event Browser. Log4net configuration is run by command `log4net.Config.XmlConfigurator.Configure(); in Global.asax's method Application_Start.

How to make log4net to display a configuration error messages?

Code:

public class ExceptionHandlingAttribute : IExceptionFilter
    {
        public  void OnException(ExceptionContext filterContext)
        {
            log4net.ILog logger = log4net.LogManager.GetLogger(typeof(MvcApplication));
            logger.Error(filterContext.Exception.Message, filterContext.Exception);
            Debug.WriteLine(string.Format("Exception: {0}", filterContext.Exception.Message));
        }
    }

Configuration:

<?xml version="1.0" encoding="utf-8"?>
<!--
  For more information on how to configure your ASP.NET application, please visit
  http://go.microsoft.com/fwlink/?LinkId=152368
  -->
<configuration>
  <configSections>
    <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=4.4.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
  </configSections>
  <system.diagnostics />
  <connectionStrings>         
    <!--
    <add name="MembershipConnection"  ....

  </connectionStrings>
  <appSettings>
    <!-- app settings starts -->
    ...
    <add key="log4net.Internal.Debug" value="true"/>
  </appSettings>
  <system.web>

    <customErrors mode="On" />

    <globalization uiCulture="en-GB" culture="en-GB" />
    <compilation debug="true" targetFramework="4.0">
      <assemblies>
       ...
      </assemblies>
    </compilation>
    <authentication mode="Forms">
      <forms loginUrl="~/Account/LogIn" timeout="2880" />
    </authentication>
    <httpRuntime />
    <profile defaultProvider="DefaultProfileProvider">
      <providers>
       ...
      </providers>
    </sessionState>
    <pages controlRenderingCompatibilityVersion="4.0">
      <namespaces>
      ...
      </namespaces>
    </pages>
    <!--
    <siteMap defaultProvider="CustomSiteMapProvider" enabled="true">
      <providers>
        <clear/>
        <add name="CustomSiteMapProvider" type="MvcWebRole1.Controllers.CustomSiteMapProvider"/>
      </providers>
    </siteMap>
    -->
  </system.web>
  <system.webServer>
    <validation validateIntegratedModeConfiguration="false" />
    <staticContent>
      <mimeMap fileExtension=".json" mimeType="application/json" />
    </staticContent>
    <!-- turn off gzipped response-->
   <urlCompression doStaticCompression="false" doDynamicCompression="false" />
  </system.webServer>
  <runtime>
   ...
  </runtime>
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
      <parameters>
        <parameter value="v11.0" />
      </parameters>
    </defaultConnectionFactory>
  </entityFramework>
  <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=.\SQLEXPRESS;initial catalog=devDB;integrated security=true;" />

      <commandText value="INSERT INTO Logs ([Level], [Logger], [Message], [Exception], [AccountId], [TimeStamp]) VALUES (@log_level, @logger, @message, @exception, @account_id, @log_date)" />
      <parameter>
        <parameterName value="@log_level" />
        <dbType value="String" />
        <size value="30" />
        <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="255" />
        <layout type="log4net.Layout.ExceptionLayout" />
      </parameter>
      <parameter>
        <parameterName value="@exception" />
        <dbType value="String" />
        <size value="2000" />
        <layout type="log4net.Layout.ExceptionLayout" />
      </parameter>
      <parameter>
        <parameterName value="@account_id" />
        <dbType value="Int32" />
        <size value="32" />
        <layout type="log4net.Layout.PatternLayout">
          <conversionPattern value="%message" />
        </layout>
      </parameter>
      <parameter>
        <parameterName value="@log_date" />
        <dbType value="DateTime" />
        <layout type="log4net.Layout.RawTimeStampLayout" />
      </parameter>
    </appender>

    <!-- Set root logger level to DEBUG and its only appender to A1 -->
    <root>
      <level value="ALL" />
      <appender-ref ref="AdoNetAppender" />
    </root>
  </log4net>
</configuration>

Working SELECT code:

SELECT TOP 1000 [Id]
      ,[Level]
      ,[Logger]
      ,[Message]
      ,[Exception]
      ,[AccountId]
      ,[TimeStamp]
  FROM [devDB].[dbo].[Logs]

UPDATE 1)

log4net reinstalled to version "2.0.2" (nuget) => "1.2.12" but still is not working.

UPDATE 2) I fixed configuration file and now works, but not fully:).

When application is started locally and exceptions are simulated then logs are not created in databased but are kept somewhere:). When application is off, still no data in SQL log table. But When application is started again, logs appears in sql table. What is wrong:)?

SOLVED: I had to change buffer size from 100 to 1:), when buffer is not full, data are not saved:)

<log4net>
    <appender name="AdoNetAppender" type="log4net.Appender.AdoNetAppender">
      <bufferSize value="1" />

Upvotes: 1

Views: 1689

Answers (1)

alastairtree
alastairtree

Reputation: 4289

You can turn on internal debugging and see if the extra info tells you what the problem is.

<configuration>
   <appSettings>
      <add key="log4net.Internal.Debug" value="true"/>
   </appSettings>
</configuration>

See http://logging.apache.org/log4net/release/faq.html and How to track down log4net problems

Upvotes: 3

Related Questions