Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Log4j Logging for custom Log levels in Java

Tags:

java

log4j

I have written class for custom logging level i.e. INIT

import org.apache.log4j.Logger;
import org.apache.log4j.Level;

public class InitLoggingLevel extends Level {

    public static final String INITLOGGING_LEVEL = "INITLOGGING";
    public static final Level INIT_LOGGING = new InitLoggingLevel(
        DEBUG_INT - 4, INITLOGGING_LEVEL, 7);

    protected InitLoggingLevel(int level, String levelStr, int syslogEquivalent){
        super(level, levelStr, syslogEquivalent);
    }
}

Now what are changes I need to make in log4j.properties and how I am going to use this INIT logging level in My Java class?

like image 758
mayur_mitkari Avatar asked Oct 07 '22 02:10

mayur_mitkari


1 Answers

You have to:

  1. Override the method toLevel(String logArgument) like this:

    public static Level toLevel(String logArgument) {
        if (logArgument != null && logArgument.toUpperCase().equals("INITLOGGING")) {
            return INIT_LOGGING;
        }
        return (Level) toLevel(logArgument);
    }
    
  2. Write a configuration line in the log4j.properties like this:

    log4j.logger.[MY_CATEGORY]=INITLOGGING#your-package.InitLoggingLevel

That's all!

P.S.: The '#' syntax is described in org.apache.log4j.helpers.OptionConverter source class.

like image 56
Luca Scarpinati Avatar answered Oct 10 '22 03:10

Luca Scarpinati