Question

I'm Writing a utility for logging using logback with slf4j, Since i'm new to logback i need to know if i can write logging statement with user defined log level from calling class something like we use in java logging as

   LOGGER.log(Level.FINEST,"Message");

So is it possible to implement that in logback. I came across logback API and found something like LOGGER.isEnabledFor(loggerLevel). Can that be used for mentioned purpose and how to implement it.

import org.slf4j.LoggerFactory;
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;

public class LogUtil {

protected static final Logger LOGGER = (Logger)LoggerFactory.getLogger("LOGUTIL");  


    public void logMethodEntrance(String className,String methodName,Level loggerLevel){
        if(LOGGER.isEnabledFor(loggerLevel)){
                    //Something like below?
                    //LOGGER.log(loggerLevel,"Entering Method-"+methodName+" of class - "+className);           
        }       
    }
}

And i tried the log statements and i'm getting below error

public void logMethodEntrance(String className,String methodName,Level loggerLevel){
        if(LOGGER.isEnabledFor(loggerLevel)){
            //LOGGER.debug("Entering Method-"+methodName+" of class - "+className);
            LOGGER.log(null, null,loggerLevel.toInt(), "Just Message", null, null);
        }       
    }

Error:

Exception in thread "main" java.lang.IllegalArgumentException: 20000 not a valid level value at ch.qos.logback.classic.Level.fromLocationAwareLoggerInteger(Level.java:267) at ch.qos.logback.classic.Logger.log(Logger.java:787) at com.vsi.commonutil.logging.LogUtil.logMethodEntrance(LogUtil.java:29) at com.vsi.commonutil.test.LogUtilTest.testforlogging(LogUtilTest.java:22) at com.vsi.commonutil.test.LogUtilTest.main(LogUtilTest.java:43)

Was it helpful?

Solution

I just found the how the answer to my question by using Level.toLocationAwareLoggerInteger(loggerLevel)

LOGGER.log(null,logUtil.getClass().getName(), Level.toLocationAwareLoggerInteger(loggerLevel), "Entering into a method - MyMethod", argArray, t)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top