Muhammad Danish Khan
Muhammad Danish Khan

Reputation: 459

Logging for some classes into single file and for some classes into their respective log file using java.util.Logging

(I want to log for some classes into single file and for some classes into their respective log file.)

(I don't want to use any library like log4j or slf4j please don't recommend these.)

The problem i have is

Until now Every class have it's own log file and i have implemented using Java.util.logging. But now there is a requirement for some classes that they should log to one file.

I know how log to one file but the main thing is that the functionality i have written for all classes to write to it's respective log file. I don't want to duplicate that code as the classes writing their logs to single file will use the same methods.

As for logging into same file i need one object of logger which i can achieve through static keyword.

This is the whole class which has been written

 public class LogHelper {

private static String   logPath             = "/Users/Desktop/checklog";

private static Logger           logger;
private String          callingMethodName;
private static FileHandler      fileHandler;

public LogHelper() {
    super();
}

public LogHelper(String loggerName, String callingMethodName) {
    logger = Logger.getLogger(loggerName);
    this.callingMethodName = callingMethodName;
}

public String getPrefix(String method) {
    String prefix = new StrBuilder(callingMethodName).append(".").append(method).append(": ").toString();
    return prefix;
}

public void logDebug(String message) {
    logger.logp(Level.ALL, "", "", message);
}

public void logError(String message) {
    logger.logp(Level.SEVERE, "", "", message);
}


public void logWarn(String message) {
    logger.logp(Level.WARNING, "", "", message);
}

public void logInfo(String message) {
    logger.info(message);
}

public void logTrace(String message) {
    logger.trace(message);
}

public static void setFileHandler(String fileName) throws IOException {
    try {
        String filePath = new StringBuffer().append(System.getProperty("user.dir")).append(File.separator).append("logs").append(File.separator).toString();
        FileUtils.forceMkdir(new File(filePath));
        FileHandler fileHandler = new FileHandler(new StringBuffer(filePath).append(fileName).append(".log").toString(), true);
        System.out.println("setFileHandler() File Path :" + filePath);
        logger.addHandler(fileHandler);
        SimpleFormatter formatter = new SimpleFormatter();
        fileHandler.setFormatter(formatter);
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}


public static void closeFileHander() {
    try {
        if (fileHandler != null) {
            logger.removeHandler(fileHandler);
            fileHandler.flush();
            fileHandler.close();
        }
    } catch (Exception ex) {

    }
}


}

I want to utilize this class so that some classes are able to write to Single file and some are able to write to their own respective files.

Ok For time being i have resolved it like this.

I have created static object of this class and then add a new static method which will return this object but before returning it will set the logger for it.

so i added these lines in class written above.

private static LogHelper logHelper;

public static LogHelper getHelper(String loggerName,String fileName){
    if(logHelper == null){
         logHelper = new LogHelper();
    }

    logHelper.logger = Logger.getLogger(loggerName);
    logHelper.setFileHandler(fileName);

    return logHelper;
}

Now i can use it in all classes which will write their logs to one file.

Upvotes: 0

Views: 1892

Answers (1)

diginoise
diginoise

Reputation: 7620

The loggers (instances of java.util.logging.Logger class) are in namespace hierarchy as defined by the names you give the Logger.getLogger(String name).

Therefore you could have one logger attached to com., another one attached to com.consolelogging. and yet another one attached to com.filelogging. names.

I think in your case you create each logger as per fully qualified name of the class thereby ensuring that each class has its own logger.

You could simply create a number of root level loggers without any children attached to it via namespacing, and pump the output for each of these loggers to separate files.

In other words, each class where you call Logger.gerLogger("file_one") will log to the same file as defined by the appender defined for this logger.

Also it is very inefficient (and obstructs analysis) to have each class log to a separate file, but if these are your requirements, then so be it.

Hope this helps.

Upvotes: 1

Related Questions