java/copy-image-resizer/src/cz/frantovo/copyImageResizer/logging/ColorfulConsoleFormatter.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 cz.frantovo.copyImageResizer.logging.ColorfulPrintWriter.TerminalColor;
21 import cz.frantovo.copyImageResizer.logging.ColorfulPrintWriter.TerminalStyle;
22 import java.io.StringWriter;
23 import java.util.logging.Formatter;
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 ColorfulConsoleFormatter extends Formatter {
34 private boolean printStacktrace = false;
37 public String format(LogRecord r) {
38 StringWriter sw = new StringWriter();
39 try (ColorfulPrintWriter out = new ColorfulPrintWriter(sw)) {
40 printLevel(out, r.getLevel());
42 printThrowable(out, r);
48 private void printLevel(ColorfulPrintWriter out, Level l) {
49 TerminalColor color = TerminalColor.Magenta;
51 if (l == Level.SEVERE) {
52 color = TerminalColor.Red;
53 } else if (l == Level.WARNING) {
54 color = TerminalColor.Yellow;
57 out.print(color, rpad(l.getLocalizedName() + ": ", 10));
60 private void printMessage(ColorfulPrintWriter out, LogRecord r) {
61 out.print(formatMessage(r));
64 private void printThrowable(ColorfulPrintWriter out, LogRecord r) {
65 Throwable t = r.getThrown();
68 out.print(TerminalColor.Red, t.getClass().getSimpleName());
69 String message = t.getLocalizedMessage();
70 if (message != null) {
74 if (printStacktrace) {
76 out.setForegroundColor(TerminalColor.Yellow);
77 out.setStyle(TerminalStyle.Dim);
78 t.printStackTrace(out);
84 public boolean isPrintStacktrace() {
85 return printStacktrace;
88 public void setPrintStacktrace(boolean printStacktrace) {
89 this.printStacktrace = printStacktrace;
92 private static String rpad(String s, int n) {
94 return String.format("%1$-" + n + "s", s);