Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

java - How to manually roll over the logfile with JDK Logging

I have an application which uses JDK Logging with a logging.properties file which configures a number of older log-file via java.util.logging.FileHandler.count.

At certain points in the application I would like to trigger a manual rollover of the logfile to have a new logfile started, e.g. before a scheduled activity starts.

Is this possible with JDK Logging?

In Log4j I am using the following, however in this case I would like to use JDK Logging!

Logger logger = Logger.getRootLogger();
Enumeration<Object> appenders = logger.getAllAppenders();
while(appenders.hasMoreElements()) {
    Object obj = appenders.nextElement();
    if(obj instanceof RollingFileAppender) {
        ((RollingFileAppender)obj).rollOver();
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can trigger a rotation by creating a throw away FileHandler with a zero limit and no append.

new FileHandler(pattern, 0, count, false).close();

  1. Remove and close your existing FileHandler
  2. Create and close the rotation FileHandler.
  3. Create and add your FileHandler using your default settings.

Otherwise you can resort to using reflection:

        Method m = FileHandler.class.getDeclaredMethod("rotate");
        m.setAccessible(true);
        if (!Level.OFF.equals(f.getLevel())) { //Assume not closed.
            m.invoke(f);
        }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...