This log output method is to output the log at the time of batch execution, and it is not recommended because there are log rote etc. in WEB application etc. It is better to use Log4j obediently.
However, in a system where Log4j cannot be used for some reason (I don't know if it is included in the first place), I was told "Logs can be System.out.println ()" and thought "Wait a minute", so I will summarize it. .. Ordinary people don't use it.
public class BatchLogFomatter extends SimpleFormatter {
public String format(LogRecord logRecord) {
final StringBuffer stringBuffer = new StringBuffer();
//Date format
//This batch wasn't supposed to be a thread-sensitive batch,
//I'm worried about putting it in a class variable, so write it in format
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
stringBuffer.append(dateFormat.format(new Date(logRecord.getMillis())));
stringBuffer.append(" ");
Level level = logRecord.getLevel();
//For some reason, FINE and below are not displayed, so just set FINE and below for the time being.
//The names are changed to CONF, INFO, WARN, ERROR.
//Display settings (DEBUG)=Let's say CONF.
if (level == Level.FINEST) {
stringBuffer.append("FINEST");
} else if (level == Level.FINER) {
stringBuffer.append("FINER ");
} else if (level == Level.FINE) {
stringBuffer.append("FINE ");
} else if (level == Level.CONFIG) {
stringBuffer.append("CONF");
} else if (level == Level.INFO) {
stringBuffer.append("INFO ");
} else if (level == Level.WARNING) {
stringBuffer.append("WARN ");
} else if (level == Level.SEVERE) {
stringBuffer.append("ERROR ");
}
stringBuffer.append(" ");
//The class name will be entered (I don't know what it is here)
stringBuffer.append(logRecord.getLoggerName());
stringBuffer.append(" - ");
//Message is displayed
stringBuffer.append(logRecord.getMessage());
//Don't forget the line breaks.
stringBuffer.append("\n");
// 2017-10-05 18:52:57.592 INFO hoge.FugaBatch -Start batch execution
//I get a log like
return stringBuffer.toString();
}
}
public class LogTest {
static final Logger logger = Logger.getLogger(LogTest.class.getName());
static {
ConsoleHandler handler = new ConsoleHandler();
//Change log level
//Even if it is ALL, the following FINE does not come out ...
handler.setLevel(Level.ALL);
handler.setFormatter(new BatchLogFomatter());
logger.addHandler(handler);
//If this is not included, the log will be duplicated
logger.setUseParentHandlers(false);
}
public static void main (String[] args) {
logger.info("Get out with INFO");
}
}
Since it is a batch execution, the log file is always separated, so do not worry about the details I try to output only the log. Is there a better way to get a log?
Recommended Posts