001/* 002 * Copyright 2012-2018 the original author or authors. 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016 017package org.springframework.boot.logging.java; 018 019import java.io.PrintWriter; 020import java.io.StringWriter; 021import java.util.Date; 022import java.util.logging.Formatter; 023import java.util.logging.LogRecord; 024 025import org.springframework.boot.logging.LoggingSystemProperties; 026 027/** 028 * Simple 'Java Logging' {@link Formatter}. 029 * 030 * @author Phillip Webb 031 */ 032public class SimpleFormatter extends Formatter { 033 034 private static final String DEFAULT_FORMAT = "[%1$tY-%1$tm-%1$td %1$tH:%1$tM:%1$tS.%1$tL] - %8$s %4$s [%7$s] --- %3$s: %5$s%6$s%n"; 035 036 private final String format = getOrUseDefault("LOG_FORMAT", DEFAULT_FORMAT); 037 038 private final String pid = getOrUseDefault(LoggingSystemProperties.PID_KEY, "????"); 039 040 private final Date date = new Date(); 041 042 @Override 043 public synchronized String format(LogRecord record) { 044 this.date.setTime(record.getMillis()); 045 String source = record.getLoggerName(); 046 String message = formatMessage(record); 047 String throwable = getThrowable(record); 048 String thread = getThreadName(); 049 return String.format(this.format, this.date, source, record.getLoggerName(), 050 record.getLevel().getLocalizedName(), message, throwable, thread, 051 this.pid); 052 } 053 054 private String getThrowable(LogRecord record) { 055 if (record.getThrown() == null) { 056 return ""; 057 } 058 StringWriter stringWriter = new StringWriter(); 059 PrintWriter printWriter = new PrintWriter(stringWriter); 060 printWriter.println(); 061 record.getThrown().printStackTrace(printWriter); 062 printWriter.close(); 063 return stringWriter.toString(); 064 } 065 066 private String getThreadName() { 067 String name = Thread.currentThread().getName(); 068 return (name != null) ? name : ""; 069 } 070 071 private static String getOrUseDefault(String key, String defaultValue) { 072 String value = null; 073 try { 074 value = System.getenv(key); 075 } 076 catch (Exception ex) { 077 // ignore 078 } 079 if (value == null) { 080 value = defaultValue; 081 } 082 return System.getProperty(key, value); 083 } 084 085}