Subclassing java.util.logging.Formatter doesn't work

后端 未结 5 864
自闭症患者
自闭症患者 2021-01-06 16:23

I am using java.util.logging for logging (I don\'t want to use log4j or anything else).

This is my complete private logging.properties:

         


        
5条回答
  •  悲哀的现实
    2021-01-06 16:49

    You can set the formatter in the code itself on the FileHandler instance.

    import java.util.logging.FileHandler;
    import java.util.logging.Level;
    import java.util.logging.Logger;
    
    // please change name of your own choice
    Logger log = Logger.getLogger("CustomLogger"); 
    log.setUseParentHandlers(false);
    log.setLevel(Level.ALL);
    
    FileHandler handler = new FileHandler("[log_file_location]");
    handler.setFormatter(new CustomFormatter()); // set formatter
    log.addHandler(handler);
    
    log.info("test message");
    
    handler.close(); // close the handler at some later point in your application.
    

    The CustomFormatter class is defined as follows.

    import java.util.logging.Formatter;
    import java.util.logging.LogRecord;
    
    public class CustomFormatter extends Formatter {
    
        @Override
        public String format(LogRecord record) {
            StringBuffer buffer = new StringBuffer();
            buffer.append(record.getMessage());
            return buffer.toString();
        }
    
    }
    

    You can code in CustomFormatter to output the messages in any format you want. Hope this helps.

提交回复
热议问题