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, version 3 of the License.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
17 package info.globalcode.sql.dk.logging;
19 import info.globalcode.sql.dk.Constants;
20 import java.util.logging.ConsoleHandler;
21 import java.util.logging.Handler;
22 import java.util.logging.Level;
23 import java.util.logging.Logger;
26 * Configures logging subsystem.
27 * Usage: java -Djava.util.logging.config.class=info.globalcode.sql.dk.logging.LoggerInitializer …
29 * @author Ing. František Kučera (frantovo.cz)
31 public class LoggerInitializer {
33 private static final Logger log = Logger.getLogger(LoggerInitializer.class.getName());
34 public static final String LEVEL_PROPERTY = LoggerInitializer.class.getName() + ".level";
35 private static final Level DEFAULT_LEVEL = Level.INFO;
37 public LoggerInitializer() {
38 Logger logger = Logger.getLogger(Constants.JAVA_PACKAGE);
39 ConsoleHandler handler = new ConsoleHandler();
40 ColorfulConsoleFormatter formatter = new ColorfulConsoleFormatter();
42 logger.addHandler(handler);
43 handler.setFormatter(formatter);
45 setLevel(logger, handler, formatter);
49 * TODO: optional FileHandler – detailed logs in file in ~/sql-dk/log/…
53 private void setLevel(Logger logger, Handler handler, ColorfulConsoleFormatter formatter) {
54 boolean levelParseError = false;
56 String cliLevel = System.getProperty(LEVEL_PROPERTY);
57 if (cliLevel == null) {
58 level = DEFAULT_LEVEL;
61 level = Level.parse(cliLevel);
62 } catch (IllegalArgumentException e) {
63 level = DEFAULT_LEVEL;
64 levelParseError = true;
68 handler.setLevel(level);
69 logger.setLevel(level);
71 if (levelParseError) {
72 log.log(Level.WARNING, "Invalid logging level „{0}“ specified in „{1}“ → using default level „{2}“", new Object[]{cliLevel, LEVEL_PROPERTY, DEFAULT_LEVEL});
75 formatter.setPrintStacktrace(level.intValue() < Level.INFO.intValue());