问题
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)
回答1:
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.
回答2:
I am not sure about the exact overhead when using LoggerFactory but I doubt it will affect your application performance. So simply use static or non static as you see fit.
What should be the benefit of using @Inject. The LoggerFactory already provides and abstraction from the concrete impl. In any case it will be a lot slower than the LoggerFactory.
The syntax is more concise when you use @Inject that is true. But imagine you use the class in a test. Then you have to setup the injection to get logging. With the normal LoggerFactory it also works nicely in tests. If java had a generic mechanism for @Inject it would work great but as it is the setup is more difficult.
来源:https://stackoverflow.com/questions/10345109/whats-the-overhead-of-creating-a-slf4j-loggers-in-static-vs-non-static-context