Java logger that automatically determines caller's class name

后端 未结 21 874
礼貌的吻别
礼貌的吻别 2020-12-07 17:53
public static Logger getLogger() {
    final Throwable t = new Throwable();
    final StackTraceElement methodCaller = t.getStackTrace()[1];
    final Logger logger          


        
21条回答
  •  忘掉有多难
    2020-12-07 18:10

    The MethodHandles class (as of Java 7) includes a Lookup class that, from a static context, can find and return the name of the current class. Consider the following example:

    import java.lang.invoke.MethodHandles;
    
    public class Main {
      private static final Class clazz = MethodHandles.lookup().lookupClass();
      private static final String CLASSNAME = clazz.getSimpleName();
    
      public static void main( String args[] ) {
        System.out.println( CLASSNAME );
      }
    }
    

    When run this produces:

    Main
    

    For a logger, you could use:

    private static Logger LOGGER = 
      Logger.getLogger(MethodHandles.lookup().lookupClass().getSimpleName());
    

提交回复
热议问题