ch.qos.logback.core.encoder.Encoder Java Examples

The following examples show how to use ch.qos.logback.core.encoder.Encoder. 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: BaleenLoggerBuilderTest.java    From baleen with Apache License 2.0 6 votes vote down vote up
@Test
public void testFileWithoutDailyRolling() {
  BaleenFileLoggerBuilder builder =
      new BaleenFileLoggerBuilder(
          NAME,
          BaleenLogging.DEFAULT_PATTERN,
          LOG_FILENAME,
          new MinMaxFilter(Level.INFO, Level.WARN),
          false,
          Optional.of(5),
          Optional.of(10));

  LoggerContext context = new LoggerContext();
  Encoder<ILoggingEvent> encoder = new PatternLayoutEncoder();

  Appender<ILoggingEvent> appender = builder.build(context, encoder);

  assertTrue(appender instanceof FileAppender);
  assertEquals(encoder, ((FileAppender<ILoggingEvent>) appender).getEncoder());

  // TODO: Add tests on the (current private) methods
}
 
Example #2
Source File: BaleenLoggerBuilderTest.java    From baleen with Apache License 2.0 6 votes vote down vote up
@Test
public void testFileWithDailyRollingWithoutSize() {
  BaleenFileLoggerBuilder builder =
      new BaleenFileLoggerBuilder(
          NAME,
          BaleenLogging.DEFAULT_PATTERN,
          LOG_FILENAME,
          new MinMaxFilter(Level.INFO, Level.WARN),
          true,
          Optional.empty(),
          Optional.of(10));

  LoggerContext context = new LoggerContext();
  Encoder<ILoggingEvent> encoder = new PatternLayoutEncoder();

  Appender<ILoggingEvent> appender = builder.build(context, encoder);

  assertTrue(appender instanceof FileAppender);
  assertEquals(encoder, ((FileAppender<ILoggingEvent>) appender).getEncoder());

  // TODO: Add tests on the (current private) methods
}
 
Example #3
Source File: BaleenLoggerBuilderTest.java    From baleen with Apache License 2.0 6 votes vote down vote up
@Test
public void testFileWithDailyRolling() {
  BaleenFileLoggerBuilder builder =
      new BaleenFileLoggerBuilder(
          NAME,
          BaleenLogging.DEFAULT_PATTERN,
          LOG_FILENAME,
          new MinMaxFilter(Level.INFO, Level.WARN),
          true,
          Optional.of(5),
          Optional.of(10));

  LoggerContext context = new LoggerContext();
  Encoder<ILoggingEvent> encoder = new PatternLayoutEncoder();

  Appender<ILoggingEvent> appender = builder.build(context, encoder);

  assertTrue(appender instanceof FileAppender);
  assertEquals(encoder, ((FileAppender<ILoggingEvent>) appender).getEncoder());

  // TODO: Add tests on the (current private) methods
}
 
Example #4
Source File: BaleenLoggerBuilderTest.java    From baleen with Apache License 2.0 6 votes vote down vote up
/** Test abstract functions (using console implementation) and the functions of console */
@Test
public void testAbstractAndConsole() {
  BaleenConsoleLoggerBuilder builder =
      new BaleenConsoleLoggerBuilder(
          NAME, BaleenLogging.DEFAULT_PATTERN, new MinMaxFilter(Level.INFO, Level.WARN));

  LoggerContext context = new LoggerContext();
  Encoder<ILoggingEvent> encoder = new PatternLayoutEncoder();

  Appender<ILoggingEvent> appender = builder.build(context, encoder);

  assertEquals(NAME, builder.getName());

  assertTrue(appender instanceof ConsoleAppender);
  assertEquals(encoder, ((ConsoleAppender<ILoggingEvent>) appender).getEncoder());

  assertNotNull(appender);
  assertEquals(NAME, appender.getName());
  Filter<ILoggingEvent> filter = appender.getCopyOfAttachedFiltersList().get(0);
  assertTrue(filter instanceof MinMaxFilter);
  assertEquals(Level.INFO, ((MinMaxFilter) filter).getMin());
  assertEquals(Level.WARN, ((MinMaxFilter) filter).getMax());
}
 
Example #5
Source File: AbstractBaleenLoggerBuilder.java    From baleen with Apache License 2.0 5 votes vote down vote up
/**
 * Build a new appender for the specified context and encoder (where required).
 *
 * @param context The logger context
 * @param encoder The encoder to use (if that is possible for the specific appender)
 * @return The new appender
 */
@Override
public final Appender<ILoggingEvent> build(
    LoggerContext context, Encoder<ILoggingEvent> encoder) {
  Appender<ILoggingEvent> appender = createAppender(context, encoder);
  appender.setName(name);
  appender.setContext(context);

  if (filters != null) {
    filters.forEach(appender::addFilter);
  }

  return appender;
}
 
Example #6
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 #7
Source File: BaleenLoggerBuilderTest.java    From baleen with Apache License 2.0 5 votes vote down vote up
@Test
public void testAbstractAndConsoleMultipleFilters() {
  BaleenConsoleLoggerBuilder builder =
      new BaleenConsoleLoggerBuilder(
          NAME,
          BaleenLogging.DEFAULT_PATTERN,
          Arrays.asList(
              new MinMaxFilter(Level.INFO, Level.ERROR),
              new MinMaxFilter(Level.INFO, Level.WARN)));

  LoggerContext context = new LoggerContext();
  Encoder<ILoggingEvent> encoder = new PatternLayoutEncoder();

  Appender<ILoggingEvent> appender = builder.build(context, encoder);

  assertEquals(NAME, builder.getName());

  assertTrue(appender instanceof ConsoleAppender);
  assertEquals(encoder, ((ConsoleAppender<ILoggingEvent>) appender).getEncoder());

  assertNotNull(appender);
  assertEquals(NAME, appender.getName());
  assertEquals(2, appender.getCopyOfAttachedFiltersList().size());
  Filter<ILoggingEvent> filter = appender.getCopyOfAttachedFiltersList().get(0);
  assertTrue(filter instanceof MinMaxFilter);
  assertEquals(Level.INFO, ((MinMaxFilter) filter).getMin());
  assertEquals(Level.ERROR, ((MinMaxFilter) filter).getMax());

  filter = appender.getCopyOfAttachedFiltersList().get(1);
  assertTrue(filter instanceof MinMaxFilter);
  assertEquals(Level.INFO, ((MinMaxFilter) filter).getMin());
  assertEquals(Level.WARN, ((MinMaxFilter) filter).getMax());

  // TODO: Test that both filters are being applied
}
 
Example #8
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 #9
Source File: InMemoryLoggingBuilder.java    From baleen with Apache License 2.0 5 votes vote down vote up
@Override
protected Appender<ILoggingEvent> createAppender(
    LoggerContext context, Encoder<ILoggingEvent> encoder) {
  appender = new InMemoryAppender<ILoggingEvent>();

  return appender;
}
 
Example #10
Source File: BaleenConsoleLoggerBuilder.java    From baleen with Apache License 2.0 5 votes vote down vote up
/**
 * Build a new appender that will log to the console
 *
 * @param context The logger context (not used by this logger)
 * @param encoder The encoder to use (if that is possible for the specific appender)
 * @return The new console-based log appender
 */
@Override
protected Appender<ILoggingEvent> createAppender(
    LoggerContext context, Encoder<ILoggingEvent> encoder) {
  ConsoleAppender<ILoggingEvent> appender = new ConsoleAppender<>();
  appender.setEncoder(encoder);
  return appender;
}
 
Example #11
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 #12
Source File: BaleenFileLoggerBuilder.java    From baleen with Apache License 2.0 5 votes vote down vote up
/**
 * Create an appender that will roll over based on size
 *
 * @param context
 * @param encoder
 * @return An appender that matches the set up of the logger builder
 */
private RollingFileAppender<ILoggingEvent> createLogAppender(
    LoggerContext context, Encoder<ILoggingEvent> encoder) {
  RollingFileAppender<ILoggingEvent> appender = new RollingFileAppender<>();
  appender.setEncoder(encoder);
  appender.setFile(file);

  FixedWindowRollingPolicy rolling = new FixedWindowRollingPolicy();
  rolling.setParent(appender);
  rolling.setContext(context);

  // Set the maximum number of logs, either to the user specified setting or default to 1
  rolling.setMinIndex(1);
  if (maxNumberLogs.isPresent() && maxNumberLogs.get() >= 0) {
    rolling.setMaxIndex(maxNumberLogs.get());
  } else {
    rolling.setMaxIndex(1);
  }
  rolling.setFileNamePattern(getFileWithPattern("%i"));

  // Configure size based rolling
  SizeBasedTriggeringPolicy<ILoggingEvent> trigger = new SizeBasedTriggeringPolicy<>();
  trigger.setMaxFileSize(getMaxFileSize());
  trigger.setContext(context);

  rolling.start();
  trigger.start();
  appender.setRollingPolicy(rolling);
  appender.setTriggeringPolicy(trigger);

  return appender;
}
 
Example #13
Source File: BaleenFileLoggerBuilder.java    From baleen with Apache License 2.0 5 votes vote down vote up
/**
 * Create an appender that will create a new log each day
 *
 * @param context
 * @param encoder
 * @return An appender that matches the set up of the logger builder
 */
private RollingFileAppender<ILoggingEvent> createDailyLogAppender(
    LoggerContext context, Encoder<ILoggingEvent> encoder) {
  RollingFileAppender<ILoggingEvent> appender = new RollingFileAppender<>();
  appender.setEncoder(encoder);
  appender.setFile(file);

  TimeBasedRollingPolicy<ILoggingEvent> rolling = new TimeBasedRollingPolicy<>();
  rolling.setContext(context);
  rolling.setParent(appender);

  rolling.setFileNamePattern(getFileWithPattern("%d"));

  // Set the maximum number of logs, either to the user specified setting or default to 1
  if (maxNumberLogs.isPresent() && maxNumberLogs.get() >= 0) {
    rolling.setMaxHistory(maxNumberLogs.get());
  } else {
    rolling.setMaxHistory(1);
  }

  // Do we need to also split files by size?
  if (divideBasedOnSize()) {
    SizeAndTimeBasedFNATP<ILoggingEvent> sizeBased = new SizeAndTimeBasedFNATP<>();
    sizeBased.setContext(context);
    sizeBased.setMaxFileSize(getMaxFileSize());
    sizeBased.setTimeBasedRollingPolicy(rolling);

    rolling.setTimeBasedFileNamingAndTriggeringPolicy(sizeBased);
  }

  rolling.start();
  if (rolling.getTimeBasedFileNamingAndTriggeringPolicy() != null) {
    rolling.getTimeBasedFileNamingAndTriggeringPolicy().start();
  }
  appender.setRollingPolicy(rolling);

  return appender;
}
 
Example #14
Source File: BufferedJedisWriterFactory.java    From logback-redis with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("squid:S2095") // rule=resource should be closed: JedisClient is closed when writer is shut down
public AbstractBufferedJedisWriter createJedisWriter(JedisWriterConfiguration writerConfiguration) {
    final RedisConnectionConfig connectionConfig = writerConfiguration.getConnectionConfig();
    final Method method = connectionConfig.getMethod();
    if (method == null) {
        throw getUnsupportedWriterTypeException(null);
    }
    final Encoder<DeferredProcessingAware> encoder = writerConfiguration.getEncoder();
    final Function<DeferredProcessingAware, String> messageCreator = event -> new String(encoder.encode(event), StandardCharsets.UTF_8);

    final JedisClientProvider clientProvider = new JedisClientProvider(jedisPoolFactory, writerConfiguration.getConnectionConfig());
    final JedisClient client = new JedisClient(clientProvider,
            writerConfiguration.getMaxInitializeTries(),
            writerConfiguration.getRetryInitializeIntervalMillis());

    switch (method) {
        case RPUSH:
            return new BufferedJedisRPusher(client,
                    messageCreator,
                    connectionConfig.getKey(),
                    writerConfiguration.getMaxBufferedMessages(),
                    writerConfiguration.getFlushBufferIntervalMillis());
        case PUBLISH:
            return new BufferedJedisPublisher(client,
                    messageCreator,
                    connectionConfig.getKey(),
                    writerConfiguration.getMaxBufferedMessages(),
                    writerConfiguration.getFlushBufferIntervalMillis());
        default:
            throw getUnsupportedWriterTypeException(method.name());
    }
}
 
Example #15
Source File: LogbackCapture.java    From emissary with Apache License 2.0 5 votes vote down vote up
private static Encoder<ILoggingEvent> buildEncoder(String layoutPattern) {
    if (layoutPattern == null)
        layoutPattern = "[%p] %m%n";
    PatternLayoutEncoder encoder = new PatternLayoutEncoder();
    encoder.setPattern(layoutPattern);
    encoder.setCharset(Charset.forName("UTF-16"));
    encoder.setContext(ContextSelectorStaticBinder.getSingleton().getContextSelector().getDefaultLoggerContext());
    encoder.start();
    return encoder;
}
 
Example #16
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 #17
Source File: AppenderUtilsTest.java    From qpid-broker-j with Apache License 2.0 5 votes vote down vote up
@Test
public void testCreateRollingFileAppenderNonDailyRolling()
{
    when(_settings.isRollDaily()).thenReturn(Boolean.FALSE);
    when(_settings.isCompressOldFiles()).thenReturn(Boolean.FALSE);

    RollingFileAppender<ILoggingEvent> appender = new RollingFileAppender<>();
    AppenderUtils.configureRollingFileAppender(_settings, new LoggerContext(), appender);

    assertEquals("Unexpected appender file name", _testLogFileName, appender.getFile());

    RollingPolicy rollingPolicy = appender.getRollingPolicy();
    final boolean condition2 = rollingPolicy instanceof RollingPolicyDecorator;
    assertTrue("Unexpected rolling policy", condition2);
    rollingPolicy = ((RollingPolicyDecorator)rollingPolicy).getDecorated();
    final boolean condition1 = rollingPolicy instanceof AppenderUtils.SimpleRollingPolicy;
    assertTrue("Unexpected decorated rolling policy", condition1);
    assertEquals("Unexpected max history",
                        (long) MAX_HISTORY,
                        (long) ((AppenderUtils.SimpleRollingPolicy) rollingPolicy).getMaxIndex());
    assertEquals("Unexpected file name pattern",
                        _testLogFileName + ".%i",
                        ((AppenderUtils.SimpleRollingPolicy) rollingPolicy).getFileNamePattern());
    assertEquals("Unexpected compression mode", CompressionMode.NONE, rollingPolicy.getCompressionMode());

    TriggeringPolicy triggeringPolicy = appender.getTriggeringPolicy();
    assertEquals("Unexpected triggering policy",
                        String.valueOf(MAX_FILE_SIZE) + " MB",
                        ((AppenderUtils.SizeTriggeringPolicy) triggeringPolicy).getMaxFileSize().toString());

    Encoder encoder = appender.getEncoder();
    final boolean condition = encoder instanceof PatternLayoutEncoder;
    assertTrue("Unexpected encoder", condition);
    assertEquals("Unexpected layout pattern", LAYOUT, ((PatternLayoutEncoder)encoder).getPattern());
}
 
Example #18
Source File: TarsLoggerServerAppenderConfig.java    From TarsJava with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
public void setEncoder(Encoder<E> encoder) {
    this.encoder = encoder;
}
 
Example #19
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 #20
Source File: SystemdJournalAppender.java    From logback-journal with Apache License 2.0 4 votes vote down vote up
public void setEncoder(Encoder<ILoggingEvent> encoder) {
	this.encoder = encoder;
}
 
Example #21
Source File: SystemdJournalAppender.java    From logback-journal with Apache License 2.0 4 votes vote down vote up
public Encoder<ILoggingEvent> getEncoder() {
	return encoder;
}
 
Example #22
Source File: KafkaAppenderConfig.java    From logback-kafka-appender with Apache License 2.0 4 votes vote down vote up
public void setEncoder(Encoder<E> encoder) {
    this.encoder = encoder;
}
 
Example #23
Source File: LoghubAppender.java    From aliyun-log-logback-appender with Apache License 2.0 4 votes vote down vote up
public Encoder<E> getEncoder() {
    return encoder;
}
 
Example #24
Source File: LoghubAppender.java    From aliyun-log-logback-appender with Apache License 2.0 4 votes vote down vote up
public void setEncoder(Encoder<E> encoder) {
    this.encoder = encoder;
}
 
Example #25
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 #26
Source File: LogzioLogbackAppender.java    From logzio-logback-appender with Apache License 2.0 4 votes vote down vote up
public void setEncoder(Encoder<ILoggingEvent> encoder) {
    this.encoder = encoder;
}
 
Example #27
Source File: LogzioLogbackAppender.java    From logzio-logback-appender with Apache License 2.0 4 votes vote down vote up
public Encoder<ILoggingEvent> getEncoder() {
    return encoder;
}
 
Example #28
Source File: RedisBatchAppender.java    From logback-redis with Apache License 2.0 4 votes vote down vote up
public void setEncoder(Encoder<DeferredProcessingAware> encoder) {
    this.encoder = encoder;
}
 
Example #29
Source File: EvictingQueueBuilder.java    From baleen with Apache License 2.0 4 votes vote down vote up
@Override
protected Appender<ILoggingEvent> createAppender(
    LoggerContext context, Encoder<ILoggingEvent> encoder) {
  return appender;
}
 
Example #30
Source File: BaleenLoggerBuilder.java    From baleen with Apache License 2.0 2 votes vote down vote up
/**
 * Creates a new configured appender.
 *
 * @param context The logger context
 * @param encoder The encoder to use (if this appender has an option)
 * @return The configured appender (ideally in an unstarted state)
 */
Appender<ILoggingEvent> build(LoggerContext context, Encoder<ILoggingEvent> encoder);