开发者

How do I prevent my logger from writing multiple instances of a log file?

I wrote a custom logger where the only addition is the following method:

public static synchronized Logger getLogger(String name) {
    try {
        boolean append = true;
        FileHandler handler = new FileHandler("tmp.log", append);
        Logger      log     = Logger.getLogger(name);
        log.addHandler(handler);
        return log;
    } catch (java.io.IOException ex) {
        //Logger.getLogger(LibraLogger.class.getName()).log(Level.SEVERE, null, ex);
    } catch (SecurityException ex) {
  开发者_StackOverflow社区      //Logger.getLogger(LibraLogger.class.getName()).log(Level.SEVERE, null, ex);
    }
    return Logger.getLogger(name);
}

It produces a series of log files tmp.log, tmp.log.1, tmp.log.2 etc.

How do I prevent this from happening?


In your logging.properties file check that the java.util.logging.FileHandler.limit is set to 0.

From the docs:

java.util.logging.FileHandler.limit specifies an approximate maximum amount to write (in bytes) to any one file. If this is zero, then there is no limit. (Defaults to no limit).

For a rotating set of files, as each file reaches a given size limit, it is closed, rotated out, and a new file opened. Successively older files are named by adding "0", "1", "2", etc into the base filename.

Another possibility is that you are trying to write to the same log file from multiple processes. If the logger detects that a file cannot be opened (It is locked by another process) it will create a new one, by adding the next free number to it.


@badcodenotreat I came across your original question because I had a similar problem and found @Romain Hippeau's solution to helpful too. Now to answer your other question :

" ..even tho the method is synchronized, the logger is detecting the file cannot be opened. Any ideas how to accomplish that?". ...

I implemented my FileHandler in its own separate class utilizing a singleton design pattern so that only one instance of the log file is created and is returned to my main logging application anytime that request is made. Hope that helps.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜