What's the overhead of creating a SLF4J loggers in static vs. non-static contexts?

Kawu picture Kawu · Apr 27, 2012 · Viewed 14.2k times · Source

I've always used the following pattern to construct (SLF4J) loggers:

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

This has worked so far, but I was wondering about the static context at some point and the need to pass in the concrete class literal all the time instead of just using a non-static logger like

private final Logger log = LoggerFactory.getLogger(getClass());

This has basically been asked (and answered) before here for LOG4J

Should logger be private static or not

and here

Should be logger always final and static?

I realize final is basically mandatory, so I'm left wondering how high the overhead of using SLF4J's in non-static context actually is.

Q:

Is there any significant practical overhead of using

private final Logger log = LoggerFactory.getLogger(getClass());

over

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

in the average (web) app? (no need to "discuss" high-end, heavy-load webapps here)


Note, I'm ultimately planning to use an even nicer approach using CDI to obtain an SLF4J logger like

@Inject private final Logger log;

as described here http://www.seamframework.org/Weld/PortableExtensionsPackage#H-TtLoggerttInjection, but I need to know about the logger caching first.

Sub question: is it even possible to use?:

@Inject private static final Logger log;

(just beginning with CDI to be honest)

Answer

Ceki picture Ceki · May 4, 2012

The overhead for non-static (instance) logger variables should be negligible unless many, say 10000 or more, instantiations occur. The key word here is negligible. If many (>10000) objects are instantiated, the impact will probably be measurable but still be low.

More specifically, an instance logger increases the memory footprint by one reference (64 bits) per object instance. On the CPU side, the cost is one hash look up per instance, i.e. the cost of looking up the appropriate logger in a hash table (small). Again, both costs should be negligible unless many many objects are created.

This question is also discussed in the SLF4J FAQ.