12

I have some webservices in my application and i want to log them to diferent files, based on the webservice name. For that i am creating loggers with

myLogger = Logger.getLogger(logKey);

I am wondering if i should cache these loggers to avoid creating them for every call, or can i ignore the overhead.

Nuno Furtado
  • 4,548
  • 8
  • 37
  • 57

2 Answers2

23

Loggers are already cached by log4j using the default log repository (Hierarchy). In other words, it's just a hashtable lookup.

However, in my experience you tend to make the logger static, so it only ends up being called once per class anyway.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • Wouldn't making the logger static prevent you from changing its level at runtime (through an MBean for example)? In theory not, but I thought that was the case with java logging. – Nicolas C Apr 21 '09 at 10:03
  • I don't *think* so. I think the level stuff is checked dynamically, rather than being frozen in the constructed logger. – Jon Skeet Apr 21 '09 at 11:32
  • Here's the link to the respective caching code in log4j-core: https://github.com/apache/logging-log4j2/blob/4ed4d281ff5775ba4cd5bdf3c61854cc6fab8657/log4j-core/src/main/java/org/apache/logging/log4j/core/LoggerContext.java#L500-L520 – sschuberth Aug 17 '22 at 14:15
9

This method Logger.getLogger(logKey) looks in logger cache for a logger with the name passed in logKey. If it doesn't exist it creates one. First call for a logger name, a Logger will be created but later calls will get it from cache so you don't need to handle this in your code.

Bhushan Bhangale
  • 10,921
  • 5
  • 43
  • 71