Java registration through several classes

I would like to enter my application consisting of several classes. I would like to have one .txt log file at the end. So I make one static instance of the log, and I made FileHandler for it in the same class. Since I would like to have one file, I set the second argument to true in FileHandler to be able to add a log file while 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 other registrars. I know that I have to specify one registrar for each class. Therefore, I only do logger (without FileHandler) for each class. But all registrars refer to the same class (not for the class where I created the registrar). For example:

 public class Test1 { static Logger logger; public Test1()throws IOException { logger = Logger.getLogger(MyLogging.class.getName()); } 

Although logging has been done, I'm not sure if this is the right solution. Can you give me some tips on how to record through multiple classes using java.util.logging?

+7
java logging java.util.logging
source share
1 answer

In the MyLogging class, create a private constructor instead of public , and you will 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, of all your classes, you can only log in to the log method, as shown 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 } 
+7
source share