/**
* 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, version 3 of the License.
*
* 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.Constants;
import java.util.logging.ConsoleHandler;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Configures logging subsystem.
* Usage: java -Djava.util.logging.config.class=info.globalcode.sql.dk.logging.LoggerInitializer …
*
* @author Ing. František Kučera (frantovo.cz)
*/
public class LoggerInitializer {
private static final Logger log = Logger.getLogger(LoggerInitializer.class.getName());
public static final String LEVEL_PROPERTY = LoggerInitializer.class.getName() + ".level";
private static final Level DEFAULT_LEVEL = Level.INFO;
public LoggerInitializer() {
Logger logger = Logger.getLogger(Constants.JAVA_PACKAGE);
ConsoleHandler handler = new ConsoleHandler();
ColorfulConsoleFormatter formatter = new ColorfulConsoleFormatter();
logger.addHandler(handler);
handler.setFormatter(formatter);
setLevel(logger, handler, formatter);
/**
* TODO: optional FileHandler – detailed logs in file in ~/sql-dk/log/…
*/
}
private void setLevel(Logger logger, Handler handler, ColorfulConsoleFormatter formatter) {
boolean levelParseError = false;
Level level;
String cliLevel = System.getProperty(LEVEL_PROPERTY);
if (cliLevel == null) {
level = DEFAULT_LEVEL;
} else {
try {
level = Level.parse(cliLevel);
} catch (IllegalArgumentException e) {
level = DEFAULT_LEVEL;
levelParseError = true;
}
}
handler.setLevel(level);
logger.setLevel(level);
if (levelParseError) {
log.log(Level.WARNING, "Invalid logging level „{0}“ specified in „{1}“ → using default level „{2}“", new Object[]{cliLevel, LEVEL_PROPERTY, DEFAULT_LEVEL});
}
formatter.setPrintStacktrace(level.intValue() < Level.INFO.intValue());
}
}