Logging with multiple parameters

Gash87 picture Gash87 · Apr 8, 2013 · Viewed 97.5k times · Source

I am currently working on a program wherein, I must write all output to a log file.

I need to write a log method, that should give an output with a level, a message, an object value, another message, an integer value, another message and another integer value, in the same order as I have specified. I can't seem to find a log method that does this. I am using Java.util.logging. Is this possible?

Answer

Rohit picture Rohit · Apr 8, 2013

I assume you need the log format in the below format FINE,Message1,object.GetValue(),Message2,1,Message3,2

You need to create an output message format

logger.log(Level.INFO, "{0},{1},{2},{3},{4},{5}",new Object[]{Message1,object.getValue(),Message2,1,Message3,2});

Now you need to create a custom formatter which by extending Formatter class

public class DataFormatter extends Formatter {

@Override
public synchronized String format(LogRecord record) {
    String formattedMessage = formatMessage(record);
    String throwable = "";
    String outputFormat = "%1$s, %2$s \n %3$s"; //Also adding for logging exceptions
    if (record.getThrown() != null) {
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        pw.println();
        record.getThrown().printStackTrace(pw);
        pw.close();
        throwable = sw.toString();
    }
    return String.format(outputFormat,record.getLevel().getName(),formattedMessage,throwable);
}
}

Now set the newly created formatter

    for(int i=0;i<logger.getHandlers().length;i++)
        logger.getHandlers()[i].setFormatter(new DataFormatter());