package envoy.util; import java.io.File; import java.io.IOException; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.logging.*; import envoy.data.Config; /** * Configures the {@link java.util.logging} API to output the log into the * console and a log file. *
* Project: envoy-client
* File: EnvoyLogger.java
* Created: 14.12.2019
*
* @author Leon Hofmeister
* @author Kai S. K. Engelbart
* @since Envoy Common v0.1-beta
*/
public final class EnvoyLog {
private static FileHandler fileHandler;
private static StreamHandler consoleHandler;
private static boolean initialized;
private EnvoyLog() {}
/**
* Initializes logging.
*
* @param config the config providing the console and log file barriers
* @since Envoy Common v0.1-beta
*/
public static void initialize(Config config) {
if (initialized) throw new IllegalStateException("EnvoyLog is already initialized");
// Remove default console handler
LogManager.getLogManager().reset();
// Configure log file
final File logFile = new File(config.getHomeDirectory(),
"log/" + DateTimeFormatter.ofPattern("yyyy-MM-dd--hh-mm").format(LocalDateTime.now()) + ".log");
logFile.getParentFile().mkdirs();
// Configure formatting
// Sample log entry: [2020-06-13 16:50:26] [INFORMATION]
// [envoy.client.ui.Startup] Closing connection...
System.setProperty("java.util.logging.SimpleFormatter.format", "[%1$tF %1$tT] [%4$-7s] [%3$s] %5$s %6$s%n");
final SimpleFormatter formatter = new SimpleFormatter();
try {
fileHandler = new FileHandler(logFile.getAbsolutePath());
fileHandler.setLevel(config.getFileLevelBarrier());
fileHandler.setFormatter(formatter);
} catch (SecurityException | IOException e) {
e.printStackTrace();
}
consoleHandler = new StreamHandler(System.out, formatter) {
@Override
public synchronized void publish(LogRecord record) {
super.publish(record);
flush();
}
};
consoleHandler.setLevel(config.getConsoleLevelBarrier());
consoleHandler.setFormatter(formatter);
initialized = true;
EnvoyLog.attach("envoy");
}
/**
* Configures all loggers that are contained within the hierarchy of a specific
* path to use the console and file handlers.
*
* @param path the path to the loggers to configure
* @since Envoy Common v0.1-beta
*/
private static void attach(String path) {
if (!initialized) throw new IllegalStateException("EnvoyLog is not initialized");
// Get root logger
final Logger logger = Logger.getLogger(path);
// Add handlers
if (fileHandler != null) logger.addHandler(fileHandler);
logger.addHandler(consoleHandler);
// Delegate logger level filtering to the handlers
logger.setLevel(Level.ALL);
}
/**
* Creates a logger for a specified class, which output will be displayed inside
* the console and written to the log file.
*
* @param logClass the class in which the logger is used
* @return the created logger
* @since Envoy Common v0.1-beta
*/
public static Logger getLogger(Class> logClass) { return Logger.getLogger(logClass.getCanonicalName()); }
}