tags:

views:

64

answers:

2

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?

+1  A: 

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.

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");

cbaby
So I don't need to pass the logger and set the logger instance?e.g.private void setLogger(Logger logger) {this.logger = logger;}
Omertron
Ok, so I've done that, changed the method to accept the string name of the logger. Now I need to redirect the main class's logFormatter to my local class's formatter, but that now "overwrites" the main class's formatter
Omertron
Well, you could "save" the original (Main) logger formatter, for instance as a sub-class field, and set it back when you're done using it in sub-class. I would say its safe enough if there is no parallelism. However, the recommended practice is that all classes should use there own logger and get their own instances by using Logger.getLogger(LocalClass.class.getName()).
cbaby
Ok, I understand that, but how would I then use another class's filehandler to write to that (physical) log file?
Omertron
Both of your loggers would "inherit" handlers from the root logger. So all you need to do is add file handler to your root logger. This would also mean that all your future loggers will use that same file handler (unless you use setUserParentHandlers(false) on them).
cbaby
A: 

This is what I have so far:

public void setLogger(String loggerName) {
    MySubClass.logger = Logger.getLogger(loggerName);

    for (Handler handler : logger.getHandlers()) {
        handler.setFormatter(tmdbFormatter);
    }
    logger.setUseParentHandlers(true);
    logger.setLevel(Level.ALL);
}
Omertron