Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing a logger between classes

Tags:

java

logging

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?

like image 313
Omertron Avatar asked Oct 12 '10 14:10

Omertron


1 Answers

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

like image 52
mkvcvc Avatar answered Sep 29 '22 21:09

mkvcvc