I have a util class with static function doSthAndLogIt()
.
Inside it I want to do something logging.
My question is, without passing the logger as param in doSthAndLogIt(Logger logger)
, is there a way to get the logger from the class that calls doSthAndLogIt()
?
More context:
public class UtilClz(){
// I don't want to use UtilClz's own logger, as caller's info will be lost
// Logger utilLogger = Logger.getLogger(UtilClz.class);
public static void doSthAndLogIt(Runnable runnable){
runnable.run();
//do logging
//callerLogger.info(...)
};
}
public class Caller(){
Logger callerLogger = Logger.getLogger(Caller.class);
public void doIt(){
UtilClz.doSthAndLogIt( () -> doSth() );
}
}
What I want to achieve, is to somehow get callerLogger
to log message in UtilClz::doSthAndLogIt
without passing callerLogger
in as function param
CodePudding user response:
Step 1: Get the caller class. To avoid duplication, see this Q&A: https://stackoverflow.com/a/45811032/2170192
Step 2: Get logger by the caller class.