1

I use the following code snippet to create an slf4j Logger object

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

and copy it to a new class when I'm working on it, but from time to time I'll forget to change the class name, and create a Logger object for MyClass in a class called YourClass, which leads to confusing statements in the logs.

I know the recommendation for getting the name of a class is to use MyClass.class.getName(), but is there a generic snippet I can use to instantiate a Logger that can be copied to new classes without needing any changes?

Joseph McCarthy
  • 897
  • 2
  • 19
  • 41
  • A better idea would be to edit the new class template on your IDE to include a logger with the proper classname. – Kayaman Mar 26 '18 at 15:50
  • 1
    Don't do this... https://stackoverflow.com/a/936724/6253321 – cpp beginner Mar 26 '18 at 15:50
  • 1
    No. Not in a static context. You could potentially setup a generator in your IDE for it though. For example, in Eclipse, you might do a custom template and something like `private static final Logger logger = Logger.getLogger(${enclosing_type});` – Elliott Frisch Mar 26 '18 at 15:51
  • 1
    You can use [Lombok](https://projectlombok.org/)'s logging annotations like `@Slf4j` to automatically generate the logging field for you based on the class name. – Erwin Bolwidt Mar 26 '18 at 15:52
  • Lombok's annotations would be my choice too, if you really find your copy-paste method to be that error prone. – Michael Mar 26 '18 at 15:56
  • Thanks, I like the template solution for its simplicity, and I hadn't heard of Lombok's annotations, so I'll check that out. @Michael it's not a massive problem, I'd estimate it happens in abuot one in every 50 classes I work on, but that's still enough to make me look for a solution – Joseph McCarthy Mar 27 '18 at 12:56

0 Answers0