Log4Net For Logging Into SQL And MongoDB

This article is mainly for advanced techies who already have a basic knowledge of Log4Net Logging system. You can get a basic knoweledge of it from the following articles.

  • http://www.c-sharpcorner.com/UploadFile/db2972/error-logging-using-log4net-in-web-application/
  • http://www.c-sharpcorner.com/UploadFile/33b051/how-to-use-log4net-in-mvc-to-track-error/ 
Quick Brief

There are different packages available which can be easily available through nuGet (open source collection of package manager).

For .NET : log4net(assembly file)

For MongoDB : Log4Mongo(assembly file)

Kindly take reference before proceeding ahead

5 Simples STEPS are needed to implement

Step 1

Update the AssemblyInfo.cs File in the Properties folder

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

Why is this done?

Because the advantages of doing this are that the code is initialized in advance of your main code, here it is done at app.config file by default.

Type 2 - [assembly: log4net.Config.XmlConfigurator (ConfigFile = "Log4Net.config", Watch = true)]

Here we can create our own custom config file just like app.config and set the path as defined above.

Step 2

Update the config File

Inside of configSections we can define our own custom (section) tag and then can use them as shown below:

  1. <!-- LOG4NET CONFIGURATION -->  
  2. <configSections>  
  3.     <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" /> </configSections> //Create Tag Syntax  
  4. <log4net></log4net> //External Custom File As mentioned in STEP1  
  5. <log4net configSource=”mycustom_appender.config”></ log4net>  

Step 3

Calling and consuming log4net reference as shown below:

This is a common WRAPPER CLASS which will be called from all projects. You can convert this into .dll and take reference by keeping it at GAC for multiple projects.

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using log4net;  
  6. using Log4Mongo;  
  7. namespace Log4Net_Wrapper {  
  8.     public class Wrapper {  
  9.         public readonly ILog log4NetAdapter;  
  10.         public Wrapper(string className) {  
  11.             this.log4NetAdapter = LogManager.GetLogger(className);  
  12.         }  
  13.         public void LogDebug(string message) {  
  14.             this.log4NetAdapter.Debug(message);  
  15.         }  
  16.         public void LogDebug(string message, Exception exception) {  
  17.             this.log4NetAdapter.Debug(message, exception);  
  18.         }  
  19.         public void LogError(string message) {  
  20.             this.log4NetAdapter.Error(message);  
  21.         }  
  22.         public void LogError(string message, Exception exception) {  
  23.             this.log4NetAdapter.Error(message, exception);  
  24.         }  
  25.         public void LogFatal(string message) {  
  26.             this.log4NetAdapter.Fatal(message);  
  27.         }  
  28.         public void LogFatal(string message, Exception exception) {  
  29.             this.log4NetAdapter.Fatal(message, exception);  
  30.         }  
  31.         public void LogInfo(string message) {  
  32.             this.log4NetAdapter.Info(message);  
  33.         }  
  34.         public void LogInfo(string message, Exception exception) {  
  35.             this.log4NetAdapter.Info(message, exception);  
  36.         }  
  37.         public void LogWarning(string message) {  
  38.             this.log4NetAdapter.Warn(message);  
  39.         }  
  40.         public void LogWarning(string message, Exception exception) {  
  41.             this.log4NetAdapter.Warn(message, exception);  
  42.         }  
  43.     }  
  44. }  

Step 4

WEbconfig File,

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <!--  
  3.   
  4. For more information on how to configure your ASP.NET application, please visit  
  5.   
  6. http://go.microsoft.com/fwlink/?LinkId=169433  
  7.   
  8. -->  
  9. <configuration>  
  10.     <!-- LOG4NET CONFIGURATION -->  
  11.     <configSections>  
  12.         <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" /> </configSections>  
  13.     <system.web>  
  14.         <compilation debug="true" targetFramework="4.5" />  
  15.         <httpRuntime targetFramework="4.5" /> </system.web>  
  16.     <log4net>  
  17.         <!-- FOR MONGO DB ERROR LOG -->  
  18.         <appender name="LogMongoDBAppender" type="Log4Mongo.MongoDBAppender, Log4Mongo">  
  19.             <connectionString value="mongodb://localhost:27017/Mongo_Database" />  
  20.             <collectionName value="logs" />  
  21.             <field>  
  22.                 <name value="timestamp" />  
  23.                 <layout type="log4net.Layout.RawTimeStampLayout" /> </field>  
  24.             <field>  
  25.                 <name value="level" />  
  26.                 <layout type="log4net.Layout.PatternLayout" value="%level" /> </field>  
  27.             <field>  
  28.                 <name value="thread" />  
  29.                 <layout type="log4net.Layout.PatternLayout" value="%thread" /> </field>  
  30.             <field>  
  31.                 <name value="logger" />  
  32.                 <layout type="log4net.Layout.PatternLayout" value="%logger" /> </field>  
  33.             <field>  
  34.                 <name value="message" />  
  35.                 <layout type="log4net.Layout.PatternLayout" value="%message" /> </field>  
  36.         </appender>  
  37.         <!-- FOR SQL DB ERROR LOG-->  
  38.         <appender name="LogAdoNetAppender" type="log4net.Appender.AdoNetAppender">  
  39.             <bufferSize value="1" />  
  40.             <connectionType value="System.Data.SqlClient.SqlConnection, System.Data, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />  
  41.             <connectionString value="data source=000.000.00.00; initial catalog=SQL_databasename;integrated security=false; persist security info=True;User ID=userid@123;Password=pwd@123" />  
  42.             <commandType value="StoredProcedure" />  
  43.             <commandText value="dbo.USP_LOG" />  
  44.             <parameter>  
  45.                 <parameterName value="@log_date" />  
  46.                 <dbType value="DateTime" />  
  47.                 <layout type="log4net.Layout.RawTimeStampLayout" /> </parameter>  
  48.             <parameter>  
  49.                 <parameterName value="@thread" />  
  50.                 <dbType value="String" />  
  51.                 <size value="255" />  
  52.                 <layout type="log4net.Layout.PatternLayout">  
  53.                     <conversionPattern value="%thread" /> </layout>  
  54.             </parameter>  
  55.             <parameter>  
  56.                 <parameterName value="@log_level" />  
  57.                 <dbType value="String" />  
  58.                 <size value="50" />  
  59.                 <layout type="log4net.Layout.PatternLayout">  
  60.                     <conversionPattern value="%level" /> </layout>  
  61.             </parameter>  
  62.             <parameter>  
  63.                 <parameterName value="@logger" />  
  64.                 <dbType value="String" />  
  65.                 <size value="255" />  
  66.                 <layout type="log4net.Layout.PatternLayout">  
  67.                     <conversionPattern value="%logger" /> </layout>  
  68.             </parameter>  
  69.             <parameter>  
  70.                 <parameterName value="@message" />  
  71.                 <dbType value="String" />  
  72.                 <size value="4000" />  
  73.                 <layout type="log4net.Layout.PatternLayout">  
  74.                     <conversionPattern value="%message" /> </layout>  
  75.             </parameter>  
  76.             <parameter>  
  77.                 <parameterName value="@exception" />  
  78.                 <dbType value="String" />  
  79.                 <size value="2000" />  
  80.                 <layout type="log4net.Layout.ExceptionLayout" /> </parameter>  
  81.         </appender>  
  82.         <!-- LOGGER -->  
  83.         <!-- FOR SQL LOG -->  
  84.         <logger name="SQLCls">  
  85.             <level value="ALL" />  
  86.             <appender-ref ref="LogAdoNetAppender" /> </logger>  
  87.         <!-- FOR MONGO LOG -->  
  88.         <logger name="MongoCls">  
  89.             <level value="ALL" />  
  90.             <appender-ref ref="LogMongoDBAppender" /> </logger>  
  91.     </log4net>  
  92.     <runtime>  
  93.         <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">  
  94.             <dependentAssembly>  
  95.                 <assemblyIdentity name="log4net" publicKeyToken="669e0ddf0bb1aa2a" culture="neutral" />  
  96.                 <bindingRedirect oldVersion="0.0.0.0-2.0.7.0" newVersion="2.0.7.0" /> </dependentAssembly>  
  97.         </assemblyBinding>  
  98.     </runtime>  
  99. </configuration>  

Step 5

Consume it by Injecting Different class (SQLCls, MongoCls) as shown above

Here you are injecting Classes (Concept of Dependency injection) which class you want to use for logging.

  1. Which Page data you want to log in which database.
  2. Run time configurable to change log of Database from web config.
  1. For SQL - > < logger name = "SQLCls" > For Mongo - > < logger name = "MongoCls" > Class: Consume_Wrapper  
  2. using System;  
  3. using System.Collections.Generic;  
  4. using System.Linq;  
  5. using System.Web;  
  6. using System.Web.UI;  
  7. using System.Web.UI.WebControls;  
  8. namespace Log4Net_Wrapper {  
  9.     public partial class Consume_Wrapper: System.Web.UI.Page {  
  10.         protected void Page_Load(object sender, EventArgs e) {  
  11.             Wrapper obj = new Wrapper("MongoCls");  
  12.             obj.LogInfo("mogo info");  
  13.             obj.LogDebug("mongo debugged");  
  14.             Wrapper obj1 = new Wrapper("SQLCls");  
  15.             obj1.LogWarning("sql warning");  
  16.             obj1.LogFatal("fatal error");  
  17.         }  
  18.     }  
  19. }  

OUTPUT Snapshot

  
  1. CREATE PROC [dbo].[USP_TBL_LOG](  
  2.   
  3. @log_date datetime,  
  4.   
  5. @thread nvarchar(255),  
  6.   
  7. @log_level nvarchar(50),  
  8.   
  9. @logger nvarchar(50),  
  10.   
  11. @message nvarchar(4000),  
  12.   
  13. @exception nvarchar(2000))  
  14.   
  15. as  
  16.   
  17. BEGIN  
  18.   
  19. INSERT INTO TBL_LOG  
  20.   
  21. (LOG_DATE, THREAD, LOG_LEVEL, LOGGER, MESSAGE, EXCEPTION)  
  22.   
  23. VALUES  
  24.   
  25. (@log_date, @thread, @log_level, @logger, @message, @exception)  
  26.   
  27. END   
 
Ebook Download
View all
SQL Jobs
Read by 0 people
Download Now!
Learn
View all