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?
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.
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.
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:
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With