Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Log4net creating custom levels

I know its possible to use the built in levels with log4net INFO, WARN, ERROR and FATAL messages

Is it possible to create new ones?

like image 805
JL. Avatar asked Jul 19 '09 21:07

JL.


People also ask

How do I set up log4net logging levels?

You can specify in your log4net config which log4net logging levels you want to log. This is really valuable if you want to specify only certain levels to be logged to a specific log appender or to reduce logging in production. This allows you to log more or less data without changing your code.

How to extend from level to custom log level with Log4j?

You will have to create your own class which will extend from Level, Custom Log Levels with Apache Log4j 2. Log4j is a simple and flexible logging framework. Logging equips the developer with detailed context for application failures. With log4j it is possible to enable logging at runtime without modifying the application binary.

How do I define a custom log level in code?

To define a custom log level in code, use the Level.forName () method. This method creates a new level for the specified name. After a log level is defined you can log messages at this level by calling the Logger.log () method and passing the custom log level:

What is log4net?

Log4net is a logging utility for .NET applications. It’s based on log4j, which is for Java applications. Log4net is highly configurable, so you can use it in many scenarios. You can use it across many different types of apps and write to more than a dozen log destinations, from file to network.


1 Answers

This can be done with an extension method as outlined here: http://rageshkrishna.com/2011/01/21/AddingCustomLogLevelsToLog4net.aspx

Adding some extension methods makes it dead simple to start using the new log levels:

public static class SecurityExtensions
{
   static readonly log4net.Core.Level authLevel = new log4net.Core.Level(50000, "Auth");

   public static void Auth(this ILog log, string message)
   {
      log.Logger.Log(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType,
          authLevel, message, null);
   }

   public static void AuthFormat(this ILog log, string message, params object[] args)
   {
      string formattedMessage = string.Format(message, args);
      log.Logger.Log(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType,
          authLevel, formattedMessage, null);
   }

}

And that’s it – now I can start using my new “Auth” logging level on any instance of ILog like this:

SecurityLogger.AuthFormat("User logged in with id {0} from IP address {1}", id, Request.UserHostAddress);
like image 168
Matthew Lock Avatar answered Oct 24 '22 03:10

Matthew Lock