Rolling log Files & removing old log files

前端 未结 6 2005
长发绾君心
长发绾君心 2021-02-07 03:15

I am working on a Java SOAP based webservice application where I am writing stdout to a text file as log for our reference. That file is growing enormously, so I need to check f

6条回答
  •  栀梦
    栀梦 (楼主)
    2021-02-07 03:45

    If you use java.util.logging.Logger, you can do it with FileHandler.

    Source: kodejava

    package org.kodejava.example.logging;
    
    import java.util.logging.Logger;
    import java.util.logging.FileHandler;
    import java.util.logging.SimpleFormatter;
    import java.io.IOException;
    
    public class RollingLogFile {
        //
        // Set a small log file size to demonstrate the rolling log files.
        //
        public static final int FILE_SIZE = 1024;
    
        public static void main(String[] args) {
            Logger logger = Logger.getLogger(RollingLogFile.class.getName());
    
            try {
                //
                // Creating an instance of FileHandler with 5 logging files
                // sequences.
                //
                FileHandler handler = new FileHandler("myapp.log", FILE_SIZE, 5, true);
                handler.setFormatter(new SimpleFormatter());
                logger.addHandler(handler);
                logger.setUseParentHandlers(false);
            } catch (IOException e) {
                logger.warning("Failed to initialize logger handler.");
            }
    
            logger.info("Logging information message.");
            logger.warning("Logging warning message.");
        }
    }
    

提交回复
热议问题