Logging with multiple parameters

后端 未结 3 914
你的背包
你的背包 2021-02-07 00:49

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

3条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-02-07 01:14

    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

提交回复
热议问题