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

后端 未结 2 1245
情话喂你
情话喂你 2020-12-29 04:14

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

private static final Logger log = LoggerFactory.getLogger(MyClass.class);
相关标签:
2条回答
  • 2020-12-29 04:57

    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.

    0 讨论(0)
  • 2020-12-29 05:02

    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.

    0 讨论(0)
提交回复
热议问题