use of ch.qos.logback.core.OutputStreamAppender in project UniversalMediaServer by UniversalMediaServer.
the class LoggingTest method testLoggingConfig.
@Test
public void testLoggingConfig() throws ConfigurationException, NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
// Set up a test (default) configuration
PMS.get();
PmsConfiguration configuration = new PmsConfiguration(false);
PMS.setConfiguration(configuration);
// Load logback configuration
LoggingConfig.loadFile();
// Silence logger
LoggingConfig.setRootLevel(Level.OFF);
// Get access to logger
LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
Logger rootLogger = context.getLogger(Logger.ROOT_LOGGER_NAME);
/* During UMS build a valid configuration should be accessible at least under "external resources"
* and thus testing for a valid configuration is considered OK to be able to do the other tests.
* "internal defaults" is returned if a valid configuration can't be found.
*/
// Test for a valid configuration
File file = new File(LoggingConfig.getConfigFilePath());
assertTrue("LoggingConfigIsFile", file.isFile());
assertFalse("LoggingConfigIsFile", file.isDirectory());
// Test getLogFilePaths() and LoggingConfigFileLoader.getLogFilePaths()
HashMap<String, String> logFilePaths = LoggingConfig.getLogFilePaths();
@SuppressWarnings("deprecation") HashMap<String, String> compLogFilePaths = LoggingConfigFileLoader.getLogFilePaths();
Iterator<Appender<ILoggingEvent>> iterator = rootLogger.iteratorForAppenders();
while (iterator.hasNext()) {
Appender<ILoggingEvent> appender = iterator.next();
if (appender instanceof FileAppender) {
FileAppender<ILoggingEvent> fa = (FileAppender<ILoggingEvent>) appender;
assertTrue("LogFilePathsContainsKey", logFilePaths.containsKey(fa.getName()));
assertEquals("LogFilePathsHasPath", logFilePaths.get(fa.getName()), fa.getFile());
if (fa.getName().equals("default.log")) {
assertTrue("CompatibleLogFilePathsContainsKey", compLogFilePaths.containsKey("debug.log"));
assertEquals("CompatibleLogFilePathsHasPath", compLogFilePaths.get("debug.log"), fa.getFile());
} else {
assertTrue("CompatibleLogFilePathsContainsKey", compLogFilePaths.containsKey(fa.getName()));
assertEquals("CompatibleLogFilePathsHasPath", compLogFilePaths.get(fa.getName()), fa.getFile());
}
}
}
// Reset LogBack configuration and create a fake one to not rely on the existing configuration file
context.reset();
TestFileAppender<ILoggingEvent> testDefaultAppender = new TestFileAppender<>();
testDefaultAppender.setName("default.log");
testDefaultAppender.setContext(context);
PatternLayoutEncoder layoutEncoder = new PatternLayoutEncoder();
layoutEncoder.setPattern("%-5level %d{HH:mm:ss.SSS} [%thread] %msg%n");
layoutEncoder.setContext(context);
testDefaultAppender.setEncoder(layoutEncoder);
rootLogger.addAppender(testDefaultAppender);
TestFileAppender<ILoggingEvent> testGenericAppender = new TestFileAppender<>();
testGenericAppender.setName("SomeOtherFileAppender");
testGenericAppender.setContext(context);
layoutEncoder = new PatternLayoutEncoder();
layoutEncoder.setPattern("%-5level %d %msg%n");
layoutEncoder.setContext(context);
testGenericAppender.setEncoder(layoutEncoder);
rootLogger.addAppender(testGenericAppender);
TestAppender<ILoggingEvent> testNonFileAppender = new TestAppender<>();
testNonFileAppender.setName("SomeNonFileAppender");
testNonFileAppender.setContext(context);
rootLogger.addAppender(testNonFileAppender);
// Test setBuffered()
LoggingConfig.setBuffered(true);
iterator = rootLogger.iteratorForAppenders();
while (iterator.hasNext()) {
Appender<ILoggingEvent> appender = iterator.next();
if (appender instanceof OutputStreamAppender && !(appender instanceof ConsoleAppender<?>)) {
// Appender has ImmediateFlush property
assertFalse("LogFileIsBuffered", ((OutputStreamAppender<ILoggingEvent>) appender).isImmediateFlush());
}
}
LoggingConfig.setBuffered(false);
iterator = rootLogger.iteratorForAppenders();
while (iterator.hasNext()) {
Appender<ILoggingEvent> appender = iterator.next();
if (appender instanceof OutputStreamAppender && !(appender instanceof ConsoleAppender<?>)) {
assertTrue("LogFileIsNotBuffered", ((OutputStreamAppender<ILoggingEvent>) appender).isImmediateFlush());
// Appender has ImmediateFlush property
}
}
// Test getRootLevel()
assertEquals("GetRootLevel", LoggingConfig.getRootLevel(), rootLogger.getLevel());
// Test setRootLevel()
LoggingConfig.setRootLevel(Level.ALL);
assertEquals("SetRootLevel", LoggingConfig.getRootLevel(), Level.ALL);
LoggingConfig.setRootLevel(Level.INFO);
assertEquals("SetRootLevel", LoggingConfig.getRootLevel(), Level.INFO);
LoggingConfig.setRootLevel(Level.OFF);
// Test setConsoleFilter()
configuration.setLoggingFilterConsole(Level.WARN);
ConsoleAppender<ILoggingEvent> consoleAppender = new ConsoleAppender<>();
consoleAppender.setContext(context);
PatternLayoutEncoder patternEncoder = new PatternLayoutEncoder();
patternEncoder.setPattern("%msg%n");
patternEncoder.setContext(context);
patternEncoder.start();
consoleAppender.setEncoder(patternEncoder);
consoleAppender.start();
rootLogger.addAppender(consoleAppender);
LoggingConfig.setConsoleFilter();
List<Filter<ILoggingEvent>> filterList = consoleAppender.getCopyOfAttachedFiltersList();
assertEquals("NumberOfConsoleFilters", filterList.size(), 1);
assertTrue("ConsoleFilterIsThresholdFilter", filterList.get(0) instanceof ThresholdFilter);
ThresholdFilter thresholdFilter = (ThresholdFilter) filterList.get(0);
Field field = thresholdFilter.getClass().getDeclaredField("level");
field.setAccessible(true);
assertEquals("ConsoleFilterLevel", field.get(thresholdFilter), Level.WARN);
configuration.setLoggingFilterConsole(Level.TRACE);
LoggingConfig.setConsoleFilter();
filterList = consoleAppender.getCopyOfAttachedFiltersList();
assertEquals("NumberOfConsoleFilters", filterList.size(), 1);
assertTrue("ConsoleFilterIsThresholdFilter", filterList.get(0) instanceof ThresholdFilter);
thresholdFilter = (ThresholdFilter) filterList.get(0);
field = thresholdFilter.getClass().getDeclaredField("level");
field.setAccessible(true);
assertEquals("ConsoleFilterLevel", field.get(thresholdFilter), Level.TRACE);
rootLogger.detachAppender(consoleAppender);
// Test setTracesFilter()
configuration.setLoggingFilterLogsTab(Level.WARN);
FrameAppender<ILoggingEvent> frameAppender = new FrameAppender<>();
frameAppender.setContext(context);
patternEncoder = new PatternLayoutEncoder();
patternEncoder.setPattern("%msg%n");
patternEncoder.setContext(context);
patternEncoder.start();
frameAppender.setEncoder(patternEncoder);
frameAppender.start();
rootLogger.addAppender(frameAppender);
LoggingConfig.setTracesFilter();
filterList = frameAppender.getCopyOfAttachedFiltersList();
assertEquals("NumberOfTracesFilters", filterList.size(), 1);
assertTrue("TracesFilterIsThresholdFilter", filterList.get(0) instanceof ThresholdFilter);
thresholdFilter = (ThresholdFilter) filterList.get(0);
field = thresholdFilter.getClass().getDeclaredField("level");
field.setAccessible(true);
assertEquals("TracesFilterLevel", field.get(thresholdFilter), Level.WARN);
configuration.setLoggingFilterLogsTab(Level.TRACE);
LoggingConfig.setTracesFilter();
filterList = frameAppender.getCopyOfAttachedFiltersList();
assertEquals("NumberOfTracesFilters", filterList.size(), 1);
assertTrue("TracesFilterIsThresholdFilter", filterList.get(0) instanceof ThresholdFilter);
thresholdFilter = (ThresholdFilter) filterList.get(0);
field = thresholdFilter.getClass().getDeclaredField("level");
field.setAccessible(true);
assertEquals("TracesFilterLevel", field.get(thresholdFilter), Level.TRACE);
rootLogger.detachAppender(frameAppender);
// Test isSyslogDisabled()
if (syslogAppenderFound(rootLogger.iteratorForAppenders())) {
assertTrue("SyslogDisabledByConfiguration", LoggingConfig.isSyslogDisabled());
} else {
assertFalse("SyslogNotDisabledByConfiguration", LoggingConfig.isSyslogDisabled());
}
// Test setSyslog() if possible
if (!syslogAppenderFound(rootLogger.iteratorForAppenders())) {
configuration.setLoggingSyslogHost("localhost");
configuration.setLoggingUseSyslog(true);
LoggingConfig.setSyslog();
assertTrue("SyslogEnabled", syslogAppenderFound(rootLogger.iteratorForAppenders()));
configuration.setLoggingUseSyslog(false);
LoggingConfig.setSyslog();
assertFalse("SyslogDisabled", syslogAppenderFound(rootLogger.iteratorForAppenders()));
}
// Test forceVerboseFileEncoder() given that LogBack configuration
// contains at least one file appender with PatternLayoutEncoder
LoggingConfig.forceVerboseFileEncoder();
iterator = rootLogger.iteratorForAppenders();
while (iterator.hasNext()) {
Appender<ILoggingEvent> appender = iterator.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
patternEncoder = (PatternLayoutEncoder) encoder;
assertTrue("AppenderPatternHasCorrectTimestamp", patternEncoder.getPattern().matches(".*%(d|date)\\{yyyy-MM-dd HH:mm:ss.SSS\\}.*"));
assertTrue("AppenderPatternHasLogger", patternEncoder.getPattern().matches(".*%logger.*"));
}
}
}
context.reset();
}
use of ch.qos.logback.core.OutputStreamAppender 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");
}
use of ch.qos.logback.core.OutputStreamAppender in project solr-document-store by DBCDK.
the class AsyncJob method initLog.
/**
* Set up logging for this class
*
* @param wesocketAppender Optional websocket appender to notify with log.
* If undesired, null can safely be passed instead
* @throws IOException in case of file errors
*/
final void initLog(AsyncJobWesocketAppender wesocketAppender) throws IOException {
UUID uuid = UUID.randomUUID();
this.id = uuid.toString();
this.file = File.createTempFile("/tmp/async-", ".log");
this.write = new FileOutputStream(file);
this.read = new RandomAccessFile(file, "r");
LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
this.log = context.getLogger(id);
log.setLevel(Level.DEBUG);
this.appender = new OutputStreamAppender();
appender.setName(id);
appender.setContext(log.getLoggerContext());
appender.setOutputStream(write);
PatternLayoutEncoder encoder = new PatternLayoutEncoder();
encoder.setContext(context);
encoder.setPattern(getLogPattern() + "%msg%n%rEx");
// Not really sure why this is nessecary appender.setEncoder should do that
encoder.init(write);
encoder.start();
appender.setEncoder(encoder);
appender.start();
log.addAppender(appender);
if (wesocketAppender != null) {
// Setup notifier using websocket to push updates to frontend
// this.wsAppender = new AsyncJobWesocketAppender(uuid,name,sessionHandler);
this.wsAppender = wesocketAppender;
wsAppender.setContext(log.getLoggerContext());
wsAppender.start();
log.addAppender(wsAppender);
}
}
use of ch.qos.logback.core.OutputStreamAppender in project zookeeper by apache.
the class LoggerTestTool method getConsoleAppender.
private OutputStreamAppender<ILoggingEvent> getConsoleAppender(ByteArrayOutputStream os) {
Logger rootLogger = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger(org.slf4j.Logger.ROOT_LOGGER_NAME);
Layout<ILoggingEvent> layout = ((LayoutWrappingEncoder<ILoggingEvent>) ((OutputStreamAppender<ILoggingEvent>) rootLogger.getAppender("CONSOLE")).getEncoder()).getLayout();
OutputStreamAppender<ILoggingEvent> appender = new OutputStreamAppender<>();
appender.setContext((LoggerContext) LoggerFactory.getILoggerFactory());
appender.setOutputStream(os);
appender.setLayout(layout);
return appender;
}
use of ch.qos.logback.core.OutputStreamAppender in project sonarqube by SonarSource.
the class WebServerProcessLoggingTest method use_json_output.
@Test
public void use_json_output() {
props.set("sonar.log.jsonOutput", "true");
LoggerContext context = underTest.configure(props);
Logger rootLogger = context.getLogger(ROOT_LOGGER_NAME);
OutputStreamAppender appender = (OutputStreamAppender) rootLogger.getAppender("file_web");
Encoder<ILoggingEvent> encoder = appender.getEncoder();
assertThat(encoder).isInstanceOf(LayoutWrappingEncoder.class);
assertThat(((LayoutWrappingEncoder) encoder).getLayout()).isInstanceOf(LogbackJsonLayout.class);
}
Aggregations