Java logging through multiple classes

后端 未结 1 1813
遇见更好的自我
遇见更好的自我 2021-02-14 15:34

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

相关标签:
1条回答
  • 2021-02-14 16:03

    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
        }
    
    0 讨论(0)
提交回复
热议问题