java/copy-image-resizer/src/cz/frantovo/copyImageResizer/logging/SimpleFormatter.java
3 * Copyright © 2013 František Kučera (frantovo.cz)
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation, either version 3 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program. If not, see <http://www.gnu.org/licenses/>.
18 package cz.frantovo.copyImageResizer.logging;
20 import java.io.PrintWriter;
21 import java.io.StringWriter;
22 import java.text.SimpleDateFormat;
23 import java.util.Date;
24 import java.util.logging.Level;
25 import java.util.logging.LogRecord;
28 * For console/terminal log output. Log messages are printed in brief and colorful form.
30 * @author Ing. František Kučera (frantovo.cz)
32 public class SimpleFormatter extends AbstractFormatter {
34 private static final ThreadLocal<SimpleDateFormat> dateFormatter = new ThreadLocal<SimpleDateFormat>() {
37 protected SimpleDateFormat initialValue() {
38 return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
44 public String format(LogRecord r) {
45 StringBuilder sb = new StringBuilder();
47 printTimestamp(sb, new Date(r.getMillis()));
49 printLevel(sb, r.getLevel());
53 printThrowable(sb, r);
59 private void printSeparator(StringBuilder out) {
63 private void printTimestamp(StringBuilder out, Date date) {
64 out.append(dateFormatter.get().format(date));
67 private void printLevel(StringBuilder out, Level l) {
69 if (l == Level.SEVERE) {
70 out.append(rpad("ERROR", 10));
71 } else if (l == Level.INFO) {
72 out.append(rpad("OK", 10));
74 out.append(rpad(l.getName(), 10));
78 private void printMessage(StringBuilder out, LogRecord r) {
79 String message = formatMessage(r);
80 // convert to single-line message
81 message = message.replaceAll("\\\\", "\\\\"); // escape backslashes
82 message = message.replaceAll("\\n", "\\n"); // escape line ends
86 private void printThrowable(StringBuilder out, LogRecord r) {
87 Throwable t = r.getThrown();
89 out.append(t.getClass().getSimpleName());
90 String message = t.getLocalizedMessage();
91 if (message != null) {
95 if (isPrintStacktrace()) {
97 StringWriter sw = new StringWriter();
98 t.printStackTrace(new PrintWriter(sw));
99 out.append(sw.toString());