15

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?

JL.
  • 78,954
  • 126
  • 311
  • 459

4 Answers4

29

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);
Martin Valgur
  • 5,793
  • 1
  • 33
  • 45
Matthew Lock
  • 13,144
  • 12
  • 92
  • 130
  • 7
    Thank you for being the only answer to this question that isn't just a link. – Shelby115 Sep 13 '16 at 19:15
  • 6
    For those wondering about Levels, here is paraphrased list of levels from log4net 2.07: Off int.MaxValue, Log4Net_Debug 120000, Emergency 120000, Fatal 110000, Alert 100000, Critical 90000, Severe 80000, Error 70000, Warn 60000, Notice 50000, Info 40000, Debug 30000, Fine 30000, Trace 20000, Finer 20000, Verbose 10000, Finest 10000 – user3085342 Mar 16 '18 at 12:56
1

It's quite a few years old now, but this thread discusses what you are looking to do.

William
  • 13,332
  • 13
  • 60
  • 73
  • 7
    Link dead but available on [the internet archive](https://web.archive.org/web/20130528024223/http://www.l4ndash.com/Log4NetMailArchive/tabid/70/forumid/1/postid/14714/view/topic/Default.aspx) – stuartd Aug 18 '14 at 10:55
  • 3
    And a few years later... both links are dead. Yay for link rot! – WernerCD Nov 29 '17 at 14:43
1

I'm using this to implement Verbose and/or Trace levels:

Log4net, how to log a verbose message?

Community
  • 1
  • 1
0

I stand corrected. It's possible in log4j as well - I've just never done it:

https://logging.apache.org/log4j/1.2/faq.html#custom-level

I would not have known unless I'd seen William's response and checked again.

duffymo
  • 305,152
  • 44
  • 369
  • 561