Home > database >  Java: Logging: Custom Formatter
Java: Logging: Custom Formatter

Time:12-31

I wrote a simple Custom Formatter for my logging that prints a DateTime in the specified format. Everything works fine, but the datetime doesn't get printed in my log file. Below is my CustomFormatter.java:

CustomFormatter.java:

public class CustomFormatter extends Formatter {

                SimpleDateFormat sdf;

                public CustomFormatter() {
                        sdf = new SimpleDateFormat("MM-dd-yyyy HH:mm:ss");
                }

                public String format(LogRecord rec) {
                        StringBuffer buf = new StringBuffer(1000);
                        buf.append(formatMessage(rec));
                        return buf.toString();
                }

                public String getHead(Handler h) {
                        return (sdf.format(new java.util.Date())   ": \t");
                }

                public String getTail(Handler h) {
                        return "\n";
                }
        }

Im my main class, I initialize my logger as:

Main.java:

private static Logger logger = Logger.getLogger("org.somecompany.someproject");

public static void main(String[] args){
    try{
        String _pattern = "myLogger.log.%g";
        int numLogFiles = 10;
        int fileSize = 1000000;
        boolean appendToFile = true;
        FileHandler fh = new FileHandler(pattern, fileSize, numLogFiles, appendToFile);

        fh.setFormatter(new CustomFormatter());
        logger.addHandler(fh);
        logger.setLevel(Level.ALL);
    } catch(IOException i) { System.out.println("Unable to init logger");}

    logger.info("Begin");

    logger.info("Line 1");

    logger.info("Line 2");

    logger.info("End");

    fh.close();
    fh = null;
}

The log file should have a datetime printed at the beginning of each line and it isn't. Any help is appreciated.

CodePudding user response:

I think you misunderstand the purpose of getHead() and getTail().

Those methods are not called per log entry - getHead() is called once before the Handler (FileHandler) logs the first entry and getTail() is called once before the Handler (FileHandler) closes the log stream.

This is used for example in the XMLFormatter to create a valid XML file (where there must be an XML start tag before the first log entry and an XML end tag after the last log entry to be valid XML).

If you look closely at the created log file this is exactly what happens: the log file creates a timestamp at the start and ends with a newline.


Note that adding time stamps to your log entries doesn't require writing a CustomFormatter. Properly configuring a SimpleFormatter is enough for your purpose.

  • Related