Java logging through multiple classes
Asked Answered
C

1

12

I would like to log in my application which consist of several classes. I would like to have one .txt log file at the end. Therefore I make one static logger instance and I made a FileHandler for it in one class. Because I would like to have one file, I set the second argument for true in the FileHandler to be able to append the log file during logging.

public class MyLogging {
    static Logger logger;
    public Handler fileHandler;
    Formatter plainText;

    public MyLogging() throws IOException{
        //instance the logger
        logger = Logger.getLogger(MyLogging.class.getName());
        //instance the filehandler
        fileHandler = new FileHandler("myLog.txt",true);
        //instance formatter, set formatting, and handler
        plainText = new SimpleFormatter();
        fileHandler.setFormatter(plainText);
        logger.addHandler(fileHandler);

    }

After that, I created the other loggers. I know that I have to instance one logger per class. Therefore I only make the logger (w/o FileHandler) for each class. But all of the loggers referencing for one class (not for the class, where I have created the logger). E.g:

public class Test1 {
    static Logger logger;

    public Test1()throws IOException {

        logger = Logger.getLogger(MyLogging.class.getName());
    }

Although the logging was performed, I am not sure that this is the right solution. Can you give me some advises how to make logging through multiple the classes with the java.util.logging?

Cirrocumulus answered 23/12, 2013 at 6:8 Comment(1)
I'm confused. You should have one log file at the end without using only one Logger instance.Dundee
M
12

In MyLogging class, make the constructor private instead of public , and you need the following methods:

private static Logger getLogger(){
    if(logger == null){
        try {
            new MyLogging();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return logger;
}
public static void log(Level level, String msg){
    getLogger().log(level, msg);
    System.out.println(msg);
}

The log method is static, so it can be called from any class using the class name.

So from all your classes, you can log just be invoking log method as below:

public class Test1 {
    //static Logger logger; //no need to create an object for logging

    public Test1()throws IOException {

         MyLogging.log(Level.INFO, MyLogging.class.getName()); //call log method using classname
    }
Machado answered 23/12, 2013 at 8:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.