Log4Net not writing to the database

20,484

Solution 1

I would recommend turning on Log4Net debugging:

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

That may point you in the right direction if there's an error that's occurring behind the scenes. The output will be directed to the console output in the IDE or in the command line.

Solution 2

  1. Check if log4net.dll is placed in the same folder as your application.
  2. Try to enable log4net self-logging, maybe it'll help to find out:

    <configuration>
     <appSettings>
      <add key="log4net.Internal.Debug" value="true"/>
     </appSettings>
     <system.diagnostics>
      <trace autoflush="true">
       <listeners>
        <add name="textWriterTraceListener"
             type="System.Diagnostics.TextWriterTraceListener"
             initializeData="C:\tmp\log4net.txt" />
       </listeners>
      </trace>
     </system.diagnostics>
    </configuration>
    

See also the official log4net FAQ.

Solution 3

I ran into a similar issue yesterday, Log4Net was just not writing to the database. I copied the configuration from another existing appender that successfully writes logs to the database. My solution was to run SQL Server Profiler to try and catch what was happening. Profiler showed that the INSERT statements were being sent by Log4Net, but it was failing on the SQL Server side. Manually running the INSERT statement in SQL Server Management Studio showed me exactly what was wrong with it, in my case, it was inserting NULL into a column that didn't accept NULL.

Solution 4

per the ADONetAppender config example:

<commandText value="INSERT INTO dbo.Log4Net 
    ([Date],[Thread],[Level],[Logger],[Message]) 
    VALUES (@log_date, @thread, @log_level, @logger, @message)"/>

This uses the ADO.NET parameterized query format, so you need to use that syntax. Additionally, you may not want to use integrated security for the db connection (esp. if you are running a web site or a service). For your file appender, I recommend a fully qualified path, and make sure it is writeable by the logger.

I assume you have already created the table in the specified database?

NOTE I recommend setting the trace appender in Debug mode too, to make sure you are actually logging stuff.

Solution 5

Add this line in the AssemblyInfo.cs file

[assembly: log4net.Config.XmlConfigurator(Watch = true)]

As the official configuration manual states "The log4net configuration can be configured using assembly-level attributes rather than specified programmatically", which I found as a more clear approach. Some people might find my answer as a more straightforward.

Source: https://logging.apache.org/log4net/release/manual/configuration.html

Share:
20,484
Admin
Author by

Admin

Updated on July 17, 2022

Comments

  • Admin
    Admin almost 2 years

    I've checked the connection string (I got it from the server explorer).

    I've checked the commandText in log4net config.

    I've checked the database permissions (integrated security is fine and works outside of the log4net class).

    I've checked the repository's configured property (it is configured, it finds the config file fine).

    I've also checked that the fields defined in the config file match the attributes (field size etc.) of the table in the database.

    Any ideas?

    When I'm debugging it seems to be hitting all the right methods at all the right times, with no exceptions raised.

    <log4net>
    
      <appender name="ADONetAppender" type="log4net.Appender.ADONetAppender">
        <bufferSize value="1" />
        <connectionType value="System.Data.SqlClient.SqlConnection, System.Data, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
        <connectionString value="" />
        <commandText value="INSERT INTO dbo.Log4Net ([Date],[Thread],[Level],[Logger],[Message]) VALUES ('01-01-2001', 'test', 'test', 'test', 'test')"/>
        <!--<commandText value="INSERT INTO dbo.Log4Net ([Date],[Thread],[Level],[Logger],[Message],[Exception],[MachineName],[CultureId],[SourcePage],[Details],[Method]) VALUES (@log_date, @thread, @log_level, @logger, @message, @exception, @MachineName, @CultureId, @SourcePage, @Details, @Method)" />-->
        <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>
    
    ...more parameters
    
        <securitycontext type="log4net.Util.WindowsSecurityContext">
          <credentials value="Process">
          </credentials>
        </securitycontext>
      </appender>
    
      <appender name="FileAppender" type="log4net.Appender.FileAppender">
        <param name="File" value="LogTest.txt"/>
        <param name="AppendToFile" value="true"/>
        <layout type="log4net.Layout.PatternLayout">
          <param name="ConversionPattern" value="%d [%t] %-2p %c [%x] - %m%n"/>
        </layout>
      </appender>
    
      <root>
        <appender-ref ref="ADONetAppender"/>
        <appender-ref ref="FileAppender"/>
      </root>
    
    </log4net>
    

    It's writing to neither appender.

  • Admin
    Admin almost 12 years
    Thanks a lot. Table is created yes. I will move away from integrated security once I can get a new set of db credentials set up but I've noted that thanks. I've changed the file appender's file property to a fully qualified one - still no log. By writeable - I'm assuming you mean permission to write to that disk? How do I check this? Thanks again.
  • Admin
    Admin almost 12 years
    I've just tried this. I found no bugs but it still didn't work - and it really slowed down the web app.
  • Jeremy Holovacs
    Jeremy Holovacs almost 12 years
    well whatever security context you're running the assembly under will need write access to the folder. This should be NT-based file permissions.
  • Admin
    Admin almost 12 years
    Just done this. No log4net.txt created. So I'm assuming there's nothing to log.
  • beaudetious
    beaudetious almost 12 years
    It's just a troubleshooting step and certainly only used for debugging for a short time. I was hoping you'd find an error message or something this way.
  • Admin
    Admin almost 12 years
    It's a very useful step to be honest, I appreciate you posting it - definitely will be of use in the future!
  • Theo
    Theo over 10 years
    I know this is old but wanted to say thinks -- without this, I wouldn't have been able to catch the error!
  • superachu
    superachu over 7 years
    the system.diagnostics helped me to find the issue. One of the parameters were missing to have the "parameter" tag declared, and adding so worked as expected.
  • Admin
    Admin about 7 years
    Nice way to debug!
  • Liam Laverty
    Liam Laverty almost 7 years
    Is there any way to get this information from software running in production? ~90% of the time my config works, but it'll miss ~10% of the logs
  • Gilles Gouaillardet
    Gilles Gouaillardet over 6 years
    can you please elaborate and explain if this answers the question and how it improves a previously accepted answer ?
  • Dimitri
    Dimitri over 6 years
    As the official configuration manual states "The log4net configuration can be configured using assembly-level attributes rather than specified programmatically", which I found as a more clear approach. Some people might find my answer as a more straightforward. Source: logging.apache.org/log4net/release/manual/configuration.html
  • Gilles Gouaillardet
    Gilles Gouaillardet over 6 years
    thanks @Dimitri ! would you mind editing your answer instead of posting the explanations in a comment ? that will make things much easier for future readers
  • Dimitri
    Dimitri over 6 years
    @GillesGouaillardet, done, thanks for your comments.
  • Yogesh Jindal
    Yogesh Jindal over 6 years
    system.diagnostics will go under configuration node. Thanks, it works.
  • Maximiliano Cesán
    Maximiliano Cesán over 5 years
    what you dont undertand of a title "Database?"