In java.util.logging, what is the global logger for?

孤街醉人 提交于 2019-11-29 11:11:09

The "global" Logger object is provided as a convenience to developers who are making casual use of the Logging package. Developers who are making serious use of the logging package (for example in products) should create and use their own Logger objects, with appropriate names, so that logging can be controlled on a suitable per-Logger granularity. Developers also need to keep a strong reference to their Logger objects to prevent them from being garbage collected.

From here (don't look at the fact that the field is deprecated, I just wanted to point you to a valid explanation).

Normally, when enabling logging in an application, you define more granular loggers, usually per Java packages or classes.

If you do not want to do that, you can use this global logger, which will handle all logging statements, no matter the library, package or class they are contained in.

I believe that main question not "why do we have global logger", but 'why do we have class specified loggers and use getLogger() method and why we use it like - Logger.getLogger("package.className");'

Answer is that we use class named loggers for convenience, e.g. you want to log some specific class, and you want to use debug level on this class and info level on others classes, to see debug messages only from this class, you can adjust logging properties to debug only this class.

Also you can have some abstract class and there could be some logger in it, and you may don't want to use same logger in all inherited classes, you may want to override logger in your inherited class and use some specific level for it.

I believe this is very useful. And answer to you question, if you have small project, and you don't want to use class named loggers, and use only one global logger, then you can use this Logger by running Logger.getGlobal();

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!