java/sql-dk/src/info/globalcode/sql/dk/logging/ColorfulConsoleFormatter.java
branchv_0
changeset 55 f5ed7c4efacc
child 59 5f745ae795a8
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/java/sql-dk/src/info/globalcode/sql/dk/logging/ColorfulConsoleFormatter.java	Wed Dec 25 00:43:06 2013 +0100
@@ -0,0 +1,75 @@
+/**
+ * SQL-DK
+ * Copyright © 2013 František Kučera (frantovo.cz)
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+package info.globalcode.sql.dk.logging;
+
+import info.globalcode.sql.dk.ColorfulPrintWriter;
+import static info.globalcode.sql.dk.ColorfulPrintWriter.TerminalColor;
+import static info.globalcode.sql.dk.ColorfulPrintWriter.TerminalStyle;
+import static info.globalcode.sql.dk.Functions.rpad;
+import java.io.StringWriter;
+import java.util.logging.Formatter;
+import java.util.logging.Level;
+import java.util.logging.LogRecord;
+
+/**
+ *
+ * @author Ing. František Kučera (frantovo.cz)
+ */
+public class ColorfulConsoleFormatter extends Formatter {
+
+	@Override
+	public String format(LogRecord r) {
+		StringWriter sw = new StringWriter();
+		try (ColorfulPrintWriter out = new ColorfulPrintWriter(sw)) {
+			printLevel(out, r.getLevel());
+			printMessage(out, r);
+			printThrowable(out, r.getThrown());
+			out.println();
+		}
+		return sw.toString();
+	}
+
+	private void printLevel(ColorfulPrintWriter out, Level l) {
+		TerminalColor color = TerminalColor.Magenta;
+		TerminalStyle style;
+
+		if (l == Level.SEVERE) {
+			color = TerminalColor.Red;
+		} else if (l == Level.WARNING) {
+			color = TerminalColor.Yellow;
+		}
+
+		out.print(color, rpad(l.getLocalizedName() + ": ", 10));
+	}
+
+	private void printMessage(ColorfulPrintWriter out, LogRecord r) {
+		out.print(formatMessage(r));
+	}
+
+	private void printThrowable(ColorfulPrintWriter out, Throwable t) {
+		if (t != null) {
+			out.print(": ");
+			out.print(TerminalColor.Red, t.getClass().getSimpleName());
+			String message = t.getLocalizedMessage();
+			if (message != null) {
+				out.print(": ");
+				out.print(message);
+			}
+		}
+	}
+}