Change log4net logging level programmatically


Hi,

We had one requirement in which we wanted to change the logging level of log4net programmatically based on the value passed.

Suppose this is how we have configured log4net in our application.


<?xml version="1.0"?>
<configuration>
 <configSections>
 <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
 </configSections>
 <log4net>
 <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
 <file value="TestLog.txt"/>
 <appendToFile value="true"/>
 <rollingStyle value="Composite"/>
 <datePattern value="yyyyMMdd"/>
 <maxSizeRollBackups value="10"/>
 <maximumFileSize value="10MB"/>
 <layout type="log4net.Layout.PatternLayout">
 <conversionPattern value="[%d{yyyy-MM-dd HH:mm:ss}] [%p] [%c:%L] - %m%n"/>
 </layout>
 </appender>
 <root>
 <level value="DEBUG"/>
 <appender-ref ref="RollingLogFileAppender"/>
 </root>
 </log4net>
<startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/></startup></configuration>

The sample code for changing the log level


namespace SampleLogApp
{
 using System.Reflection;

using log4net;
 using log4net.Core;
 using log4net.Repository;
 using log4net.Repository.Hierarchy;
 using log4net.Config;

public partial class Form1 : Form
 {

 private static readonly ILog logger = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
 private List<Person> lstPerson;

 public Form1()
 {
 InitializeComponent();
 // configure the log4net logging
 XmlConfigurator.Configure();
 }

private void btnStartLogging_Click(object sender, EventArgs e)
 {
 foreach(Person person in lstPerson)
 {
 // set the logging type depending on person
 SetLoggingLevel(person.LogType);
 logger.Debug("Debug: " + person.FullName);
 logger.Info("Info: " + person.FullName);
 logger.Warn("Warn: " + person.FullName);
 logger.Error("Error: " + person.FullName);
 }
 }

private void Form1_Load(object sender, EventArgs e)
 {
 lstPerson = new List<Person>();
 lstPerson.Add(new Person() { FullName = "Abhinav Ranjan", LogType = "Debug" });
 lstPerson.Add(new Person() { FullName = "Nirav Pancholi", LogType = "Info" });
 lstPerson.Add(new Person() { FullName = "Shobhit Bhatnagar", LogType = "Error" });
 }

/// <summary>
 /// Sets the logging level.
 /// </summary>
 /// <param name="logType">Type of the log.</param>
 private static void SetLoggingLevel(string logType)
 {
 Logger currentLogger = (Logger)logger.Logger;
 currentLogger.Level = currentLogger.Hierarchy.LevelMap[logType];
 }
 }
}

The output in TestLog.txt

[2012-04-16 00:17:27] [DEBUG] [SampleLogApp.Form1:39] – Debug: Abhinav Ranjan
[2012-04-16 00:17:27] [INFO] [SampleLogApp.Form1:40] – Info: Abhinav Ranjan
[2012-04-16 00:17:27] [WARN] [SampleLogApp.Form1:41] – Warn: Abhinav Ranjan
[2012-04-16 00:17:27] [ERROR] [SampleLogApp.Form1:42] – Error: Abhinav Ranjan
[2012-04-16 00:17:27] [INFO] [SampleLogApp.Form1:40] – Info: Nirav Pancholi
[2012-04-16 00:17:27] [WARN] [SampleLogApp.Form1:41] – Warn: Nirav Pancholi
[2012-04-16 00:17:27] [ERROR] [SampleLogApp.Form1:42] – Error: Nirav Pancholi
[2012-04-16 00:17:27] [ERROR] [SampleLogApp.Form1:42] – Error: Shobhit Bhatnagar

The helpful post

http://geekswithblogs.net/rakker/archive/2007/08/22/114900.aspx

Hope it helps.

Author: Nishant Rana

I love working in and sharing everything about Microsoft.NET technology !

Please share your thoughts

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Power Spark

Power Spark By Shrangarika

Van Carl Nguyen

Exploration of Power Platform

My Trial

It is my experience timeline.

Power⚡Thomas

Sharing my knowledge and experience about the Microsoft Power Platform.

Arpit Power Guide

a guide to powering up community

Welcome to the Blog of Paul Andrew

Sponsored by Cloud Formations Ltd

Deriving Dynamics 365

Deriving Solutions and features on Power Platform/Dynamics 365

The CRM Ninja

Thoughts & musings from a Dynamics 365 Ninja!

D CRM Explorer

Learn about Microsoft Dynamics CRM Power Platform customization and implementation and other cool stuffs

Stroke // Jonas Rapp

I know pre-stroke. I will improve who I was.

Power Melange

Power Melange By Shalinee

Clavin's Blog

Power Automate - Power Apps - SharePoint Online - Azure - Nintex - K2 - Artificial Intelligence

Sat Sangha Salon

An Inquiry in Being

The Indoencers

The Influencers & Influences of Indian Music

Monika Halan's blog

Hand's-free money management

D365 Demystified

A closer look at Microsoft Dynamics 365.

Microsoft Mate (msftmate) - Andrew Rogers

Experienced consultant primarily focused on Microsoft Dynamics 365 and the Power Platform

Knowhere365

Specific topics by Django Lohn on the whole Microsoft365 Stack

Manmit Rahevar's Blog

One Stop Destination for Microsoft Technology Solutions

MG

Naturally Curious

Brian Illand

Power Platform and Dynamics 365

Steve Mordue MVP

A Microsoft Business Applications MVP

Subwoofer 101

Bass defines your home theater

SQLTwins by Nakul Vachhrajani

SQL Server tips and experiences dedicated to my twin daughters.

Everything D365

Discovering Azure DevOps and D365 Business Applications

Tech Wizard

Lets do IT Spells

XRM Tricks (Power Platform & Dynamics CRM )

Power Platform & Dynamics CRM

CRM TIPS BY PRM

Mail to crmtipsbyprm@gmail.com for queries and suggestions

nijos.dev

Giving back to the community what I have learned

xrm CRM Dynamics

Dynamics CRM Technical & Functional Info

Dynamics 365 Blogs - Explained in unique way

Sometimes you need to look at things from different perspective.

CRM Keeper

Dynamics 365 Customer Engagement, CRM, Microsoft CRM, Dynamics CRM