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 info.globalcode.sql.dk.logging;
20 import info.globalcode.sql.dk.ColorfulPrintWriter;
21 import static info.globalcode.sql.dk.ColorfulPrintWriter.TerminalColor;
22 import static info.globalcode.sql.dk.ColorfulPrintWriter.TerminalStyle;
23 import static info.globalcode.sql.dk.Functions.rpad;
24 import java.io.StringWriter;
25 import java.util.logging.Formatter;
26 import java.util.logging.Level;
27 import java.util.logging.LogRecord;
31 * @author Ing. František Kučera (frantovo.cz)
33 public class ColorfulConsoleFormatter extends Formatter {
35 private boolean printStacktrace = false;
38 public String format(LogRecord r) {
39 StringWriter sw = new StringWriter();
40 try (ColorfulPrintWriter out = new ColorfulPrintWriter(sw)) {
41 printLevel(out, r.getLevel());
43 printThrowable(out, r);
49 private void printLevel(ColorfulPrintWriter out, Level l) {
50 TerminalColor color = TerminalColor.Magenta;
52 if (l == Level.SEVERE) {
53 color = TerminalColor.Red;
54 } else if (l == Level.WARNING) {
55 color = TerminalColor.Yellow;
58 out.print(color, rpad(l.getLocalizedName() + ": ", 10));
61 private void printMessage(ColorfulPrintWriter out, LogRecord r) {
62 out.print(formatMessage(r));
65 private void printThrowable(ColorfulPrintWriter out, LogRecord r) {
66 Throwable t = r.getThrown();
69 out.print(TerminalColor.Red, t.getClass().getSimpleName());
70 String message = t.getLocalizedMessage();
71 if (message != null) {
75 if (printStacktrace) {
77 out.setForegroundColor(TerminalColor.Yellow);
78 out.setStyle(TerminalStyle.Dim);
79 t.printStackTrace(out);
85 public boolean isPrintStacktrace() {
86 return printStacktrace;
89 public void setPrintStacktrace(boolean printStacktrace) {
90 this.printStacktrace = printStacktrace;