1

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

wayne
  • 598
  • 3
  • 15

1 Answers1

0

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.

Alex Shesterov
  • 26,085
  • 12
  • 82
  • 103
  • I think if I call `Logger.getLogger(Caller.class)` 10 times, only one logger instance is created, so there's no performance issue? – wayne Sep 24 '21 at 14:10
  • Exactly, if the logger (for a specific class) was already created, `Logger.getLogger()` will return the existing instance. – Alex Shesterov Sep 24 '21 at 14:29