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:
- <!-- LOG4NET CONFIGURATION -->
- <configSections>
- <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" /> </configSections>
- <log4net></log4net>
- <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.
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using log4net;
- using Log4Mongo;
- namespace Log4Net_Wrapper {
- public class Wrapper {
- public readonly ILog log4NetAdapter;
- public Wrapper(string className) {
- this.log4NetAdapter = LogManager.GetLogger(className);
- }
- public void LogDebug(string message) {
- this.log4NetAdapter.Debug(message);
- }
- public void LogDebug(string message, Exception exception) {
- this.log4NetAdapter.Debug(message, exception);
- }
- public void LogError(string message) {
- this.log4NetAdapter.Error(message);
- }
- public void LogError(string message, Exception exception) {
- this.log4NetAdapter.Error(message, exception);
- }
- public void LogFatal(string message) {
- this.log4NetAdapter.Fatal(message);
- }
- public void LogFatal(string message, Exception exception) {
- this.log4NetAdapter.Fatal(message, exception);
- }
- public void LogInfo(string message) {
- this.log4NetAdapter.Info(message);
- }
- public void LogInfo(string message, Exception exception) {
- this.log4NetAdapter.Info(message, exception);
- }
- public void LogWarning(string message) {
- this.log4NetAdapter.Warn(message);
- }
- public void LogWarning(string message, Exception exception) {
- this.log4NetAdapter.Warn(message, exception);
- }
- }
- }
Step 4
WEbconfig File,
- <?xml version="1.0" encoding="utf-8"?>
- <!--
-
- For more information on how to configure your ASP.NET application, please visit
-
- http:
-
- -->
- <configuration>
- <!-- LOG4NET CONFIGURATION -->
- <configSections>
- <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" /> </configSections>
- <system.web>
- <compilation debug="true" targetFramework="4.5" />
- <httpRuntime targetFramework="4.5" /> </system.web>
- <log4net>
- <!-- FOR MONGO DB ERROR LOG -->
- <appender name="LogMongoDBAppender" type="Log4Mongo.MongoDBAppender, Log4Mongo">
- <connectionString value="mongodb://localhost:27017/Mongo_Database" />
- <collectionName value="logs" />
- <field>
- <name value="timestamp" />
- <layout type="log4net.Layout.RawTimeStampLayout" /> </field>
- <field>
- <name value="level" />
- <layout type="log4net.Layout.PatternLayout" value="%level" /> </field>
- <field>
- <name value="thread" />
- <layout type="log4net.Layout.PatternLayout" value="%thread" /> </field>
- <field>
- <name value="logger" />
- <layout type="log4net.Layout.PatternLayout" value="%logger" /> </field>
- <field>
- <name value="message" />
- <layout type="log4net.Layout.PatternLayout" value="%message" /> </field>
- </appender>
- <!-- FOR SQL DB ERROR LOG-->
- <appender name="LogAdoNetAppender" type="log4net.Appender.AdoNetAppender">
- <bufferSize value="1" />
- <connectionType value="System.Data.SqlClient.SqlConnection, System.Data, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
- <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" />
- <commandType value="StoredProcedure" />
- <commandText value="dbo.USP_LOG" />
- <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>
- <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="4000" />
- <layout type="log4net.Layout.PatternLayout">
- <conversionPattern value="%message" /> </layout>
- </parameter>
- <parameter>
- <parameterName value="@exception" />
- <dbType value="String" />
- <size value="2000" />
- <layout type="log4net.Layout.ExceptionLayout" /> </parameter>
- </appender>
- <!-- LOGGER -->
- <!-- FOR SQL LOG -->
- <logger name="SQLCls">
- <level value="ALL" />
- <appender-ref ref="LogAdoNetAppender" /> </logger>
- <!-- FOR MONGO LOG -->
- <logger name="MongoCls">
- <level value="ALL" />
- <appender-ref ref="LogMongoDBAppender" /> </logger>
- </log4net>
- <runtime>
- <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
- <dependentAssembly>
- <assemblyIdentity name="log4net" publicKeyToken="669e0ddf0bb1aa2a" culture="neutral" />
- <bindingRedirect oldVersion="0.0.0.0-2.0.7.0" newVersion="2.0.7.0" /> </dependentAssembly>
- </assemblyBinding>
- </runtime>
- </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.
- Which Page data you want to log in which database.
- Run time configurable to change log of Database from web config.
- For SQL - > < logger name = "SQLCls" > For Mongo - > < logger name = "MongoCls" > Class: Consume_Wrapper
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.UI;
- using System.Web.UI.WebControls;
- namespace Log4Net_Wrapper {
- public partial class Consume_Wrapper: System.Web.UI.Page {
- protected void Page_Load(object sender, EventArgs e) {
- Wrapper obj = new Wrapper("MongoCls");
- obj.LogInfo("mogo info");
- obj.LogDebug("mongo debugged");
- Wrapper obj1 = new Wrapper("SQLCls");
- obj1.LogWarning("sql warning");
- obj1.LogFatal("fatal error");
- }
- }
- }
OUTPUT Snapshot
- CREATE PROC [dbo].[USP_TBL_LOG](
-
- @log_date datetime,
-
- @thread nvarchar(255),
-
- @log_level nvarchar(50),
-
- @logger nvarchar(50),
-
- @message nvarchar(4000),
-
- @exception nvarchar(2000))
-
- as
-
- BEGIN
-
- INSERT INTO TBL_LOG
-
- (LOG_DATE, THREAD, LOG_LEVEL, LOGGER, MESSAGE, EXCEPTION)
-
- VALUES
-
- (@log_date, @thread, @log_level, @logger, @message, @exception)
-
- END