Friday 26 June 2020

Use log4net for all logging in c# application

Exception logging is hugely important within an application, not just to ensure we know when an error has occured but also to help use trace back the thread to help investigate where the error originated.
Our strategy is to use log4net for all our logging needs.
This page helps cover the follow areas
1. Setting up logging across the entire applications
2. Including 2 appenders so we can be notified when they occur and ensure a tracable debug log file is available.
Setting up your Applications for Logging
Reference log4net in your applications
in Global.asax under the start_application method include the following
    void Application_Start(object sender, EventArgs e)
    {
        // link up log4net configuration
        log4net.Config.XmlConfigurator.Configure();
    }
On the page where you wish to log information declare a new static variable in the class header
log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
Whenever you wish to now log an event in this class run one of the follow commands, ensure you include the exception when needed
log.Error("An unhandled exception occured", ex);
To ensure you catch all unhandled exceptions include the following in your Global.asax file. Remember to declare the log variable in the class too.
    void Application_Error(object sender, EventArgs e) 
    {
        // Code that runs when an unhandled error occurs
        // get last exception
        Exception ex = Server.GetLastError().GetBaseException();
        // log it
        log.Error("An unhandled exception occured", ex);
    }
Web.Config Settings
  <configSections>
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
  </configSections>
<log4net>
    <!-- The DebugFileAppender writes all messages to a log file-->
    <appender name="DebugFileAppender" type="log4net.Appender.RollingFileAppender">
      <file value="L:\[APPNAME]\Log.txt" /> <!-- These should be located on the "L" drive (if available) and stored under a folder named for the specific application -->      <datePattern value="'ApplicationLog.'yyyy-MM-dd'.txt'" />
      <staticLogFileName value="false" />
      <rollingStyle value="Composite" />
      <maxSizeRollBackups value="10" />
      <maximumFileSize value="5MB" />
      <appendToFile value="true" />
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%d [%t] %-5p %c %m%n" />
      </layout>
    </appender>    <!-- The EmailAppender sends an email when something matches the filters-->
    <appender name="EmailAppender" type="log4net.Appender.SmtpAppender">
      <evaluator type="log4net.Core.LevelEvaluator">
        <threshold value="DEBUG"/>
      </evaluator>
      <!--  The filters are processed in order:
            1) match the Inserted New User message
            2) match any WARN or higher messages
            3) reject everything else -->
      <filter type="log4net.Filter.StringMatchFilter">
        <stringToMatch value="Inserted a new user" />
        <acceptOnMatch value="true" />
      </filter>
      <filter type="log4net.Filter.LevelRangeFilter">
        <levelMin value="WARN" />
        <acceptOnMatch value="true" />
      </filter>
      <filter type="log4net.Filter.DenyAllFilter" />
      <!--  The SmtpAppender authenticates against the mail server, the buffersize of 10 provides 10 lines
            of context when an error happens. -->
      <subject value="[SEVERITY] [ENV] [APPNAME] - [EXCP_MSG]" />
      <to value="itteam@site.com" />
      <from value="noreply@site.com" />
      <smtpHost value="smtpmail.lu.sii.com" />
      <bufferSize value="10" />
      <lossy value="true" />
      <layout type="log4net.Layout.PatternLayout">
        <param name="ConversionPattern" value="%d [%t] %-5p %c %m%n" />
      </layout>
    </appender>
    <appender name="EventLogAppender" type="log4net.Appender.EventLogAppender" >
      <applicationName value="MyApp" />


     <layout type="log4net.Layout.PatternLayout">


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


      </layout>


    </appender>

    <root>
      <!-- add other appenders here and the log messages will be sent to every listed appender -->
      <appender-ref ref="DebugFileAppender" />
      <appender-ref ref="EmailAppender" />
    </root>
  </log4net>

No comments:

Post a Comment

Generate SQL script from entity framework using powershell/visual studio

to run the below command , start PowerShell in visual studio. Select the database project. In PowerShell:   Script-Migration this command wi...