use of net.pms.util.Iterators in project UniversalMediaServer by UniversalMediaServer.
the class LoggingConfig method loadFile.
/**
* Loads the (optional) Logback configuration file.
*
* It loads the file defined in the <code>project.logback</code> property from the current
* directory and (re-)initializes Logback with this file. If running
* headless (<code>System.Property("console")</code> set), then the
* alternative config file defined in <code>project.logback.headless</code> is tried first.
*
* If no config file can be found in the CWD, then nothing is loaded and
* Logback will use the logback.xml file on the classpath as a default. If
* this doesn't exist then a basic console appender is used as fallback.
*
* <strong>Note:</strong> Any error messages generated while parsing the
* config file are dumped only to <code>stdout</code>.
*/
public static synchronized void loadFile() {
File file = null;
if (!setContextAndRoot()) {
return;
}
if (PMS.isHeadless()) {
file = getFile(PropertiesUtil.getProjectProperties().get("project.logback.headless").split(","));
}
if (file == null) {
file = getFile(PropertiesUtil.getProjectProperties().get("project.logback").split(","));
}
if (file == null) {
// Unpredictable: Any logback.xml found in the Classpath is loaded, if that fails defaulting to BasicConfigurator
// See http://logback.qos.ch/xref/ch/qos/logback/classic/BasicConfigurator.html
LOGGER.warn("Could not load LogBack configuration file from " + (PMS.isHeadless() ? PropertiesUtil.getProjectProperties().get("project.logback.headless") + ", " : "") + PropertiesUtil.getProjectProperties().get("project.logback"));
LOGGER.warn("Falling back to somewhat unpredictable defaults, probably only logging to console.");
return;
}
// Now get logback to actually use the config file
JoranConfigurator configurator = new JoranConfigurator();
configurator.setContext(loggerContext);
try {
// the context was probably already configured by
// default configuration rules
loggerContext.reset();
loggerContext.getStatusManager().clear();
// Do not log between loggerContext.reset() and CacheLogger.initContext()
configurator.doConfigure(file);
if (CacheLogger.isActive()) {
CacheLogger.initContext();
}
// Save the file path after loading the file
synchronized (filepathLock) {
filepath = file.getAbsolutePath();
LOGGER.debug("LogBack started with configuration file: {}", filepath);
}
} catch (JoranException je) {
try {
System.err.println("LogBack configuration failed: " + je.getLocalizedMessage());
System.err.println("Trying to create \"emergency\" configuration");
// Try to create "emergency" appenders for some logging if configuration fails
if (PMS.isHeadless()) {
ConsoleAppender<ILoggingEvent> ca = new ConsoleAppender<>();
PatternLayoutEncoder pe = new PatternLayoutEncoder();
pe.setPattern("%-5level %d{HH:mm:ss.SSS} [%thread] %logger %msg%n");
pe.setContext(loggerContext);
pe.start();
ca.setEncoder(pe);
ca.setContext(loggerContext);
ca.setName("Emergency Console");
ca.start();
loggerContext.getLogger(Logger.ROOT_LOGGER_NAME).addAppender(ca);
} else {
FrameAppender<ILoggingEvent> fa = new FrameAppender<>();
PatternLayoutEncoder pe = new PatternLayoutEncoder();
pe.setPattern("%-5level %d{HH:mm:ss.SSS} [%thread] %logger %msg%n");
pe.setContext(loggerContext);
pe.start();
fa.setEncoder(pe);
fa.setContext(loggerContext);
fa.setName("Emergency Frame");
fa.start();
loggerContext.getLogger(Logger.ROOT_LOGGER_NAME).addAppender(fa);
}
System.err.println("LogBack \"emergency\" configuration applied.");
} catch (Exception e) {
System.err.println("LogBack \"emergency\" configuration failed with: " + e);
}
if (CacheLogger.isActive()) {
CacheLogger.initContext();
}
LOGGER.error("Logback configuration failed with: {}", je.getLocalizedMessage());
StatusPrinter.printInCaseOfErrorsOrWarnings(loggerContext);
return;
}
// Build the iterator
Iterators<Appender<ILoggingEvent>> iterators = new Iterators<>();
// Add CacheLogger appenders if CacheLogger is active
if (CacheLogger.isActive()) {
iterators.addIterator(CacheLogger.iteratorForAppenders());
}
// non-root appenders there.
for (Logger logger : loggerContext.getLoggerList()) {
iterators.addIterator(logger.iteratorForAppenders());
}
// Iterate
Iterator<Appender<ILoggingEvent>> it = iterators.combinedIterator();
synchronized (logFilePathsLock) {
while (it.hasNext()) {
Appender<ILoggingEvent> appender = it.next();
if (appender instanceof FileAppender) {
FileAppender<ILoggingEvent> fa = (FileAppender<ILoggingEvent>) appender;
logFilePaths.put(fa.getName(), fa.getFile());
} else if (appender instanceof SyslogAppender) {
syslogDisabled = true;
}
}
}
// Set filters for console and traces
setConfigurableFilters(true, true);
StatusPrinter.printInCaseOfErrorsOrWarnings(loggerContext);
return;
}
use of net.pms.util.Iterators in project UniversalMediaServer by UniversalMediaServer.
the class LoggingConfig method forceVerboseFileEncoder.
public static synchronized void forceVerboseFileEncoder() {
final String timeStampFormat = "yyyy-MM-dd HH:mm:ss.SSS";
if (loggerContext == null) {
LOGGER.error("Unknown loggerContext, aborting buffered logging. Make sure that loadFile() has been called first.");
return;
}
// Build iterator
Iterators<Appender<ILoggingEvent>> iterators = new Iterators<>();
// Add CacheLogger or rootLogger appenders depending on whether CacheLogger is active.
if (CacheLogger.isActive()) {
iterators.addIterator(CacheLogger.iteratorForAppenders());
} else {
iterators.addIterator(rootLogger.iteratorForAppenders());
}
// If syslog is active there probably are detached appenders there as well
if (!syslogDetachedAppenders.isEmpty()) {
iterators.addList(syslogDetachedAppenders);
}
// Iterate
Iterator<Appender<ILoggingEvent>> it = iterators.combinedIterator();
while (it.hasNext()) {
Appender<ILoggingEvent> appender = it.next();
if (appender instanceof OutputStreamAppender && !(appender instanceof ConsoleAppender<?>)) {
// Appender has Encoder property
Encoder<ILoggingEvent> encoder = ((OutputStreamAppender<ILoggingEvent>) appender).getEncoder();
if (encoder instanceof PatternLayoutEncoder) {
// Encoder has pattern
PatternLayoutEncoder patternEncoder = (PatternLayoutEncoder) encoder;
String logPattern = patternEncoder.getPattern();
// Set timestamp format
Pattern pattern = Pattern.compile("%((date|d)(\\{([^\\}]*)\\})?)(?=\\s)");
Matcher matcher = pattern.matcher(logPattern);
if (matcher.find()) {
boolean replace = true;
if (matcher.group(4) != null && matcher.group(4).equals(timeStampFormat)) {
replace = false;
}
if (replace) {
logPattern = logPattern.replaceFirst(pattern.pattern(), "%d{" + timeStampFormat + "}");
}
} else {
if (logPattern.startsWith("%-5level")) {
logPattern = logPattern.substring(0, 8) + " %d{" + timeStampFormat + "}" + logPattern.substring(8);
} else {
logPattern = "d%{" + timeStampFormat + "} " + logPattern;
}
}
// Make sure %logger is included
pattern = Pattern.compile("((%logger|%lo|%c)(\\{\\d+\\})?)(?=\\s)");
matcher = pattern.matcher(logPattern);
if (matcher.find()) {
boolean replace = true;
if (matcher.group().equals("%logger")) {
replace = false;
}
if (replace) {
logPattern = logPattern.replaceFirst(pattern.pattern(), "%logger");
}
} else {
if (logPattern.contains("%msg")) {
logPattern = logPattern.substring(0, logPattern.indexOf("%msg")) + "%logger " + logPattern.substring(logPattern.indexOf("%msg"));
} else {
logPattern = "%logger " + logPattern;
}
}
// Activate changes
patternEncoder.setPattern(logPattern);
patternEncoder.start();
}
}
}
LOGGER.info("Verbose file logging pattern enforced");
}
Aggregations