Logging SQL exceptions from database using log4net

918 Views Asked by At

I have a wcf service which calls a stored procedure in sql database. I use log4net for logging purpose.

If any sql exception is thrown from the database, I can get the sql exception properties like procedure name, error line, severity etc., from the exception object in the service.

But is there a way to directly log those properties in a file using log4net?.

1

There are 1 best solutions below

1
On

Follow these steps:

  1. Add reference to log4net dll
  2. Import the following namespaces using log4net; using log4net.Config;
  3. Add the following code to global declaring

    private static readonly ILog log =   LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
    
  4. Add this code to your constructor

    XmlConfigurator.Configure(new FileInfo(AppDomain.CurrentDomain.BaseDirectory + @"\Config\Log4Net.config"));
    
  5. Copy the following to your config file under configuration tag

<configSections>
          section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
       </configSections>
       <log4net debug="true">
        <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
          <file value="C:\\Temp\\errLog.txt" />
          <appendToFile value="true" />
          <rollingStyle value="Size" />
          <maxSizeRollBackups value="10" />
          <maximumFileSize value="10MB" />
          <staticLogFileName value="true" />
          <layout type="log4net.Layout.PatternLayout">
            <conversionPattern value="%-5p %d %5rms %-22.22c{1} %-18.18M - %m%n" />
          </layout>
        </appender>
        <root>
          <level value="DEBUG" />
          <level value= "ERROR" />
          <appender-ref ref="RollingLogFileAppender" />
        </root>
      </log4net>

  1. in the try...catch(Exception ex) add the following line

    log.Error(ex)