简体   繁体   中英

How can I simplify the creation of class-level loggers?

Is there a way in Java to find out which class I'm in without referencing an object? I need the current class name from a static point. Here is an example:

public class MyClass {
  // is this possible?
  private static final String myClassName = ???;

  // not like this
  void someMethod(){
    String className = this.getClass();
  }

  // or this
  private static final String myClassName = MyClass.class;

}

The overall problem is logging. The logger of the project I'm working on needs the class name and is supposed to be declared like this:

private static final Logger LOGGER = LogHelper.getLogger(MyClass.class);

If there is a more generic way, it would be easier to copy the logger.

I need this code in multiple classes, and it would be nice to just copy the code instead of always replacing "MyClass.class" every time.

Unfortunately, different approaches wouldn't be compatible with the conventions of this project.

Some compilers like eclipse lets you do it, for exsamples look this page:

http://www.ibm.com/developerworks/opensource/tutorials/os-eclipse-code-templates/

and use this in your new template:

private static final Logger LOGGER = LogHelper.getLogger(${primary_type_name}.class

To put it simply, there likely isn't a simpler or more generic approach to doing this. While I'm uncertain of the exact logger library you're using, the main fact remains that you must supply the class that you want to log to the logger.

It does mean extra typing, but there's no realistic approach that is simpler, easier to understand, or safer - anything that's overly complex and uses a lot of reflection to extract the class name would need to be tested to ensure that it always returns the correct class, which is substantially more effort than simply using MyClass.class .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM