在类之间传递记录器 [英] Passing a logger between classes
问题描述
我的项目中有两个类,我想将记录器从主类传递给子类,并让子类使用父级的记录器设置。
I have two classes in my project that I would like to pass the logger from the main class to the sub-class and have the sub-class utilise the parent's logger settings.
子类是一个单独的泛型类(即不与主类绑定),如果没有提供,则必须能够创建自己的记录器。
The sub-class is a separate, generic class (i.e. not tied to the main class) and must be able to create it's own logger if there isn't one provided.
主类创建一个记录器,添加一个控制台处理程序,文件处理程序和日志格式化程序,我希望子类能够临时覆盖日志格式化程序的日志消息然后当主类时恢复,恢复为它的日志格式化程序。
The main class creates a logger, adds a console handler, file handler and log formatter, and I would like the sub-class to be able to temporarily override the log formatter for it's log messages and then when the main class resumes, revert to it's log formatter.
我试图将记录器添加到子类中,或者根据需要创建一个新的记录器,但我收到多条消息在屏幕上和日志文件中(似乎是将处理程序附加到主类而不是覆盖它)。
I've tried to lass the logger to the sub-class, or create a new one if required, but I get multiple messages on screen and in the log file (it seems to be appending the handlers to the main class rather than over-riding it).
我将如何进行此操作?
How would I go about doing this?
推荐答案
我会假设你是你唱java.util.logging包。在这种情况下,无论何时何地使用Logger.getLogger(someString),您都将获得相同的Logger实例。
I will assume you are using java.util.logging package. In that case, whenever and wherever you use Logger.getLogger(someString) you will get the same Logger instance.
例如:如果在Main类中使用Logger log = Logger.getLogger(myLogger); ,您可以使用Logger.getLogger(myLogger);
For example: if in Main class you use Logger log = Logger.getLogger("myLogger"); , you can get the same logger in any other class by using Logger.getLogger("myLogger");
这篇关于在类之间传递记录器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!