ch.qos.logback.core.OutputStreamAppender Java Examples

The following examples show how to use ch.qos.logback.core.OutputStreamAppender. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: CommandLineClient.java    From termsuite-core with Apache License 2.0 6 votes vote down vote up
private void applyLogConfig() {
	boolean loggingActivated = isSet(TermSuiteCliOption.LOG_INFO) 
			|| isSet(TermSuiteCliOption.LOG_DEBUG) 
			|| isSet(TermSuiteCliOption.LOG_TO_FILE);
	
	if(loggingActivated) {
		OutputStreamAppender<ILoggingEvent> appender = 
				isSet(TermSuiteCliOption.LOG_TO_FILE) ?
						LogbackUtils.createFileAppender(asPath(TermSuiteCliOption.LOG_TO_FILE)) :
							LogbackUtils.createConsoleAppender();
		LogbackUtils.activateLogging(appender);
		
		Level level = Level.WARN;
		if(isSet(TermSuiteCliOption.LOG_INFO))
			level = Level.INFO;
		else if(isSet(TermSuiteCliOption.LOG_DEBUG))
			level = Level.DEBUG;
		else if(isSet(TermSuiteCliOption.LOG_TO_FILE))
			level = Level.INFO;
		LogbackUtils.setGlobalLogLevel(level);
	}
}
 
Example #2
Source File: LogbackLogConfigurator.java    From butterfly with MIT License 6 votes vote down vote up
@Override
    public void setVerboseMode(boolean verboseMode) {
        this.verboseMode = verboseMode;

        if (verboseMode) {
            PatternLayoutEncoder patternLayoutEncoder = new PatternLayoutEncoder();
            patternLayoutEncoder.setPattern("[%d{HH:mm:ss.SSS}] [%highlight(%level)] %msg%n");
            patternLayoutEncoder.setContext(loggerContext);
            patternLayoutEncoder.start();

            Appender<ILoggingEvent> consoleAppender = new ConsoleAppender();
            ((OutputStreamAppender) consoleAppender).setEncoder(patternLayoutEncoder);
            consoleAppender.setContext(loggerContext);
            consoleAppender.start();

            loggerContext.getLogger("com.paypal.butterfly.cli").detachAppender("CONSOLE");
            loggerContext.getLogger("ROOT").addAppender(consoleAppender);
//        } else {
            // TODO
        }
    }
 
Example #3
Source File: LogbackUtils.java    From termsuite-core with Apache License 2.0 5 votes vote down vote up
static void activateLogging(OutputStreamAppender<ILoggingEvent> appender) {
	PatternLayoutEncoder ple = new PatternLayoutEncoder();
	ple.setPattern("%date %level [%thread] %logger{10} [%file:%line] %msg%n");
	ple.setContext(getContext());
	ple.start();
	appender.setContext(getContext());
	appender.setEncoder(ple);
	appender.start();
	
	// add appender to any Logger (here is root)
	ch.qos.logback.classic.Logger rootLogger = getRootLogger();
	rootLogger.addAppender(appender);
}
 
Example #4
Source File: LogbackConfiguration.java    From portmapper with GNU General Public License v3.0 5 votes vote down vote up
private OutputStreamAppender<ILoggingEvent> createAppender(final OutputStream logMessageOutputStream,
        final Encoder<ILoggingEvent> encoder) {
    final OutputStreamAppender<ILoggingEvent> appender = new OutputStreamAppender<ILoggingEvent>();
    appender.setContext(loggerContext);
    appender.setEncoder(encoder);
    appender.setOutputStream(logMessageOutputStream);
    appender.setName(OUTPUT_STREAM_APPENDER_NAME);
    appender.start();
    return appender;
}
 
Example #5
Source File: LogbackUtils.java    From termsuite-core with Apache License 2.0 5 votes vote down vote up
public static OutputStreamAppender<ILoggingEvent> createFileAppender(Path path) {
	FileAppender<ILoggingEvent> fa = new FileAppender<ILoggingEvent>();
	fa.setFile(path.toString());
	fa.setAppend(true);
	fa.setName("FileLogger");
	return fa;
}
 
Example #6
Source File: LogstashTests.java    From godaddy-logger with MIT License 5 votes vote down vote up
private Map<String, Object> getJson() throws IOException {
    OutputStreamAppender<ILoggingEvent> appender = (OutputStreamAppender<ILoggingEvent>) testLogger.getAppender("loggingEventCompositeJsonEncoderAppender");
    LoggingEventCompositeJsonEncoder encoder = (LoggingEventCompositeJsonEncoder) appender.getEncoder();

    String encodedValue = new String(encoder.encode(listAppender.list.get(0)), "UTF-8");

    return jsonFactory.createParser(encodedValue).readValueAs(new TypeReference<Map<String, Object>>() {});
}
 
Example #7
Source File: BaleenLoggingTest.java    From baleen with Apache License 2.0 5 votes vote down vote up
@Test
public void test() {
  BaleenLogging logging = new BaleenLogging();
  InMemoryLoggingBuilder builder = new InMemoryLoggingBuilder();
  logging.configure(
      Arrays.asList(
          builder,
          new BaleenConsoleLoggerBuilder(PATTERN, new MinMaxFilter(Level.INFO, Level.ERROR))));

  LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
  Logger rootLogger = context.getLogger(ch.qos.logback.classic.Logger.ROOT_LOGGER_NAME);

  int count = 0;

  Iterator<Appender<ILoggingEvent>> it = rootLogger.iteratorForAppenders();
  while (it.hasNext()) {
    Appender<ILoggingEvent> appender = it.next();

    if (appender instanceof OutputStreamAppender) {
      Encoder<ILoggingEvent> e = ((OutputStreamAppender<ILoggingEvent>) appender).getEncoder();
      assertTrue(e instanceof PatternLayoutEncoder);

      assertEquals(PATTERN, ((PatternLayoutEncoder) e).getPattern());
    }

    count++;
  }

  // 3 = 2 + instrumented appender
  assertEquals(3, count);
}
 
Example #8
Source File: LogbackCapture.java    From emissary with Apache License 2.0 5 votes vote down vote up
private static OutputStreamAppender<ILoggingEvent> buildAppender(final Encoder<ILoggingEvent> encoder, final OutputStream outputStream) {
    OutputStreamAppender<ILoggingEvent> appender = new OutputStreamAppender<ILoggingEvent>();
    appender.setName("logcapture");
    appender.setContext(ContextSelectorStaticBinder.getSingleton().getContextSelector().getDefaultLoggerContext());
    appender.setEncoder(encoder);
    appender.setOutputStream(outputStream);
    appender.start();
    return appender;
}
 
Example #9
Source File: LogBackConfiguration.java    From summerframework with Apache License 2.0 5 votes vote down vote up
private void setLayout(LoggerContext loggerContext,OutputStreamAppender outputStreamAppender){
    Encoder<?> encoder = outputStreamAppender.getEncoder();
    if (encoder instanceof LayoutWrappingEncoder) {
        TraceIdPatternLogbackLayout traceIdLayOut = new TraceIdPatternLogbackLayout();
        traceIdLayOut.setContext(loggerContext);
        traceIdLayOut.setPattern(getLogBackPattern());
        traceIdLayOut.start();
        Field field = ReflectionUtils.findField(encoder.getClass(), "layout");
        field.setAccessible(true);
        ReflectionUtils.setField(field, encoder, traceIdLayOut);
    }
}
 
Example #10
Source File: LogBackConfiguration.java    From summerframework with Apache License 2.0 5 votes vote down vote up
private void setLayout(LoggerContext loggerContext,Iterator<Appender<?>> iterator){
    while (iterator.hasNext()) {
        Appender appender = iterator.next();
        if (appender instanceof OutputStreamAppender) {
            setLayout(loggerContext,(OutputStreamAppender<?>)appender);
        }else if(appender instanceof AsyncAppenderBase){
            AsyncAppenderBase asyncAppenderBase= (AsyncAppenderBase) appender;
            setLayout(loggerContext,asyncAppenderBase.iteratorForAppenders());
        }
    }
}
 
Example #11
Source File: BaleenLoggingTest.java    From baleen with Apache License 2.0 4 votes vote down vote up
@Test
public void config() throws Exception {
  YamlConfiguration configuration =
      new YamlConfiguration(BaleenLoggingTest.class, "dummyConfig.yaml");

  BaleenLogging logging = new BaleenLogging();
  logging.configure(configuration);

  LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
  Logger rootLogger = context.getLogger(ch.qos.logback.classic.Logger.ROOT_LOGGER_NAME);

  int count = 0;

  Iterator<Appender<ILoggingEvent>> it = rootLogger.iteratorForAppenders();
  while (it.hasNext()) {
    Appender<ILoggingEvent> appender = it.next();

    switch (count) {
      case 0:
        assertTrue(appender instanceof ConsoleAppender);
        break;
      case 1:
        assertTrue(appender instanceof RollingFileAppender);
        break;
      case 2:
        assertTrue(appender instanceof FileAppender);
        assertFalse(appender instanceof RollingFileAppender);
        break;
      case 3:
        if (appender instanceof OutputStreamAppender) {
          Encoder<ILoggingEvent> e =
              ((OutputStreamAppender<ILoggingEvent>) appender).getEncoder();
          assertTrue(e instanceof PatternLayoutEncoder);
          assertEquals(PATTERN, ((PatternLayoutEncoder) e).getPattern());
        }
        break;
      case 4:
        if (appender instanceof EvictingQueueAppender) {
          assertEquals(
              EvictingQueueAppender.DEFAULT_MAX_SIZE,
              ((EvictingQueueAppender<ILoggingEvent>) appender).getMaxSize());
        } else {
          fail("Unknown additional appender");
        }
        break;
      case 5:
        // Allow additional appenders for checking, otherwise throw an error
        if (!(appender instanceof InstrumentedAppender)) {
          fail("Unknown additional appender");
        }
        break;
      default:
        fail("Too many appenders" + appender.getName());
    }
    count++;
  }

  assertEquals(6, count);

  // TODO: test the instance parameters match the configuration
}
 
Example #12
Source File: OfframpConsole.java    From data-highway with Apache License 2.0 4 votes vote down vote up
/**
 * Helper function to configure where message and CLI output is directed as well as configure logging
 * This should be called first to ensure correct output of message and cli logging into the desired stream.
 */
private void configureOutput() {
  try {
    if (flipOutput) {
      PrintStream tmp = msgout;
      msgout = cliout;
      cliout = tmp;
    }

    // change output format from json to yaml
    if (format == Format.YAML) {
      mapper = new YAMLMapper();
    }

    // retrieve the ch.qos.logback.classic.LoggerContext
    LoggerContext logCtx = (LoggerContext) org.slf4j.LoggerFactory.getILoggerFactory();

    PatternLayoutEncoder logEncoder = new PatternLayoutEncoder();
    logEncoder.setContext(logCtx);
    logEncoder.setPattern("%d{HH:mm:ss.SSS} - %-5level %logger{35} - %msg%n");
    logEncoder.start();

    OutputStreamAppender logConsoleAppender = new OutputStreamAppender();
    logConsoleAppender.setContext(logCtx);
    logConsoleAppender.setOutputStream(cliout);
    logConsoleAppender.setName("console");
    logConsoleAppender.setEncoder(logEncoder);
    logConsoleAppender.start();

    Logger rootLogger = logCtx.getLogger("root");
    rootLogger.detachAndStopAllAppenders();
    rootLogger.setLevel(Level.WARN);
    rootLogger.addAppender(logConsoleAppender);

    Logger roadLogger = logCtx.getLogger("com.hotels.road");
    roadLogger.setLevel(Level.WARN);

    Logger clientLogger = logCtx.getLogger("com.hotels.road.offramp.client");
    clientLogger.setLevel(debug ? Level.DEBUG : Level.INFO);

    Logger cliLogger = logCtx.getLogger("com.hotels.road.tool.cli");
    cliLogger.setLevel(debug ? Level.DEBUG : Level.INFO);
  } catch (Exception e) {
    System.err.println("Error configuring the message and cli output:");
    e.printStackTrace();
    System.exit(Error.OUTPUT_CONFIGURATION.code);
  }
}
 
Example #13
Source File: LogbackUtils.java    From termsuite-core with Apache License 2.0 4 votes vote down vote up
public static OutputStreamAppender<ILoggingEvent> createConsoleAppender() {
	ConsoleAppender<ILoggingEvent> fa = new ConsoleAppender<ILoggingEvent>();
	fa.setName("ConsoleLogger");
	return fa;
}
 
Example #14
Source File: AgentOutputAppender.java    From gocd with Apache License 2.0 4 votes vote down vote up
private void write(String message, Exception throwable) {
    for (OutputStreamAppender<ILoggingEvent> appender : appenders) {
        Logger logger = (Logger) LoggerFactory.getLogger(AgentOutputAppender.class);
        appender.doAppend(new LoggingEvent("", logger, Level.ERROR, message, throwable, null));
    }
}
 
Example #15
Source File: AgentOutputAppender.java    From gocd with Apache License 2.0 4 votes vote down vote up
void close() {
    appenders.forEach(OutputStreamAppender::stop);
}
 
Example #16
Source File: LogbackConfiguration.java    From portmapper with GNU General Public License v3.0 4 votes vote down vote up
public void registerOutputStream(final OutputStream logMessageOutputStream) {
    final Encoder<ILoggingEvent> encoder = createPatternLayoutEncoder(PATTERN_LAYOUT);
    final OutputStreamAppender<ILoggingEvent> appender = createAppender(logMessageOutputStream, encoder);
    configureLogger(appender);
}
 
Example #17
Source File: LogbackConfiguration.java    From portmapper with GNU General Public License v3.0 4 votes vote down vote up
@SuppressWarnings("java:S4792") // Logger configuration is ok
private void configureLogger(final OutputStreamAppender<ILoggingEvent> appender) {
    final Logger logbackLogger = getLogger();
    logbackLogger.addAppender(appender);
    logbackLogger.setAdditive(false);
}