ch.qos.logback.core.Context Java Examples

The following examples show how to use ch.qos.logback.core.Context. 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: RollingPolicyDecoratorTest.java    From qpid-broker-j with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() throws Exception
{

    _baseFolder = TestFileUtils.createTestDirectory("rollover", true);
    _testFile = createTestFile("test.2015-06-25.0.gz");
    Context mockContext = mock(Context.class);
    _delegate = mock(RollingPolicyBase.class);
    String fileNamePattern = _baseFolder.getAbsolutePath() + "/" + "test.%d{yyyy-MM-dd}.%i.gz";
    when(_delegate.getFileNamePattern()).thenReturn(fileNamePattern);
    when(_delegate.getContext()).thenReturn(mockContext);
    _listener = mock(RollingPolicyDecorator.RolloverListener.class);

    _policy = new RollingPolicyDecorator(_delegate, _listener, createMockExecutorService());

    _rolledFileRegExp = Pattern.compile(new FileNamePattern(fileNamePattern, mockContext).toRegex());

    LOGGER.debug("Rolled file reg exp: {} ", _rolledFileRegExp);
}
 
Example #2
Source File: BrokerConsoleLoggerImpl.java    From qpid-broker-j with Apache License 2.0 6 votes vote down vote up
@Override
protected Appender<ILoggingEvent> createAppenderInstance(Context context)
{
    ConsoleAppender<ILoggingEvent> consoleAppender = new ConsoleAppender<>();

    final PatternLayoutEncoder encoder = new PatternLayoutEncoder();
    encoder.setPattern(getLayout());
    encoder.setContext(context);
    encoder.start();

    if (_consoleStreamTarget == ConsoleStreamTarget.STDERR)
    {
        consoleAppender.setTarget("System.err");
    }
    consoleAppender.setEncoder(encoder);

    return consoleAppender;
}
 
Example #3
Source File: BrokerFileLoggerImpl.java    From qpid-broker-j with Apache License 2.0 6 votes vote down vote up
@Override
protected Appender<ILoggingEvent> createAppenderInstance(Context loggerContext)
{
    SystemConfig<?> systemConfig = getAncestor(SystemConfig.class);
    _logbackStatusListener = new BrokerLoggerStatusListener(this,
                                                            systemConfig,
                                                            BROKER_FAIL_ON_LOGGER_IO_ERROR,
                                                            IOException.class,
                                                            IOError.class);
    _statusManager = loggerContext.getStatusManager();
    _statusManager.add(_logbackStatusListener);

    final RollingFileAppender<ILoggingEvent> appender = new RollingFileAppender<>();
    AppenderUtils.configureRollingFileAppender(this, loggerContext, appender);
    return appender;
}
 
Example #4
Source File: StartupAppender.java    From qpid-broker-j with Apache License 2.0 6 votes vote down vote up
public void logToConsole()
{
    Context context = getContext();
    ConsoleAppender<ILoggingEvent> consoleAppender = new ConsoleAppender<>();
    consoleAppender.setContext(context);
    PatternLayoutEncoder patternLayoutEncoder = new PatternLayoutEncoder();
    patternLayoutEncoder.setContext(context);

    // added MDC variable 'qpid.log.prefix' for test purposes
    patternLayoutEncoder.setPattern("%X{qpid.log.prefix}%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n");
    patternLayoutEncoder.start();

    consoleAppender.addFilter(new Filter<ILoggingEvent>()
    {
        @Override
        public FilterReply decide(final ILoggingEvent event)
        {
            return event.getLevel().isGreaterOrEqual(_consoleAppenderAcceptLogLevel) ? FilterReply.ACCEPT : FilterReply.DENY;
        }
    });

    consoleAppender.setEncoder(patternLayoutEncoder);
    consoleAppender.start();
    replayAccumulatedEvents(consoleAppender);
    consoleAppender.stop();
}
 
Example #5
Source File: ApplicationInfoEnricher.java    From justtestlah with Apache License 2.0 6 votes vote down vote up
@Override
public void start() {
  if (started) {
    return;
  }
  props.getProperties();
  Context context = getContext();
  String platform = props.getProperty("platform");

  StringBuilder strBuilder = new StringBuilder(platform.toUpperCase());
  if (platform.equalsIgnoreCase("android") || platform.equalsIgnoreCase("ios")) {
    String appPath = props.getProperty(platform + ".appPath");
    ApplicationInfo appInfo = applicationInfoService.getAppInfo(appPath);
    if (appInfo != null && !appInfo.toString().isEmpty()) {
      strBuilder.append(" ");
      strBuilder.append(appInfo);
    }
  }
  context.putProperty("appInfo", strBuilder.toString());
  started = true;
}
 
Example #6
Source File: JDBCLoggerHelper.java    From qpid-broker-j with Apache License 2.0 6 votes vote down vote up
Appender<ILoggingEvent> createAppenderInstance(final Context context,
                                               final ConfiguredObject<?> logger,
                                               final JDBCSettings settings)
{
    try
    {
        final JDBCSettingsDBNameResolver dbNameResolver = new JDBCSettingsDBNameResolver(settings);
        final ConnectionSource connectionSource = createConnectionSource(context, logger, settings);
        final DBAppender appender = new DBAppender();
        appender.setDbNameResolver(dbNameResolver);
        appender.setConnectionSource(connectionSource);
        appender.setContext(context);
        appender.start();
        return appender;
    }
    catch (Exception e)
    {
        LOGGER.error("Failed to create appender", e);
        throw new IllegalConfigurationException("Cannot create appender");
    }
}
 
Example #7
Source File: AppenderUtils.java    From singer with Apache License 2.0 5 votes vote down vote up
/**
 * Create the basic thrift appender which logs to a file
 * and rolls the file when it exceeds a certain size.
 *
 * @param basePath base directory the files are under.
 * @param topic the topic name for the current appender.
 * @param rotateThresholdKBytes threshold in kilobytes to rotate after.
 * @param context the logback context.
 */
public static Appender<LogMessage> createFileRollingThriftAppender(
    File basePath,
    String topic,
    long rotateThresholdKBytes,
    Context context,
    int maxRetentionHours) {
  RollingFileAppender<LogMessage> appender = new RollingFileAppender<LogMessage>();
  appender.setContext(context);
  appender.setAppend(true);
  appender.setPrudent(false);

  LogMessageEncoder encoder = new LogMessageEncoder();
  appender.setEncoder(encoder);
  appender.setFile(basePath + PATH_SEP + topic);

  TimeBasedRollingPolicy policy = new TimeBasedRollingPolicy();
  policy.setMaxHistory(maxRetentionHours);
  policy.setFileNamePattern(basePath + PATH_SEP + topic + ".%d{yyyy-MM-dd-HH}.%i");
  policy.setCleanHistoryOnStart(false);
  policy.setContext(context);
  policy.setParent(appender);

  // Also impose a max size per file policy.
  SizeAndTimeBasedFNATP fnatp = new SizeAndTimeBasedFNATP();
  fnatp.setContext(context);
  fnatp.setTimeBasedRollingPolicy(policy);
  fnatp.setMaxFileSize(FileSize.valueOf(String.format("%sKB", rotateThresholdKBytes)));

  policy.setTimeBasedFileNamingAndTriggeringPolicy(fnatp);
  appender.setRollingPolicy(policy);
  appender.setTriggeringPolicy(policy);

  policy.start();
  appender.start();

  return appender;
}
 
Example #8
Source File: DelegatingAppender.java    From spring-boot-data-geode with Apache License 2.0 5 votes vote down vote up
public DelegatingAppender() {

		Optional.ofNullable(LoggerFactory.getILoggerFactory())
			.filter(it -> Objects.isNull(DEFAULT_APPENDER.getContext()))
			.filter(Context.class::isInstance)
			.map(Context.class::cast)
			.ifPresent(DEFAULT_APPENDER::setContext);

		this.name = DEFAULT_NAME;
	}
 
Example #9
Source File: CustomFieldsAdapter.java    From cf-java-logging-support with Apache License 2.0 5 votes vote down vote up
private List<String> getListItemsAsStrings(Context context, String key) {
	Object object = context.getObject(key);
	if (object instanceof Collection) {
		Collection<?> list = (Collection<?>) object;
		ArrayList<String> listItems = new ArrayList<>(list.size());
		for (Object current : list) {
			listItems.add(current.toString());
		}
		return listItems;
	}
	return emptyList();
}
 
Example #10
Source File: StringAppenderUnitTests.java    From spring-boot-data-geode with Apache License 2.0 5 votes vote down vote up
@Test
public void buildAndStartStringAppender() {

	Context mockContext = mock(Context.class);

	DelegatingAppender delegate = spy(new DelegatingAppender());

	Logger rootLogger = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);

	StringAppender stringAppender = new StringAppender.Builder()
		.applyTo(delegate)
		.applyTo(rootLogger)
		.setContext(mockContext)
		.setName("TestStringAppender")
		.useSynchronization()
		.buildAndStart();

	assertThat(stringAppender).isNotNull();
	assertThat(stringAppender.isStarted()).isTrue();
	assertThat(stringAppender.getContext()).isEqualTo(mockContext);
	assertThat(stringAppender.getName()).isEqualTo("TestStringAppender");
	assertThat(stringAppender.getStringAppenderWrapper())
		.isInstanceOf(StringAppender.StringBufferAppenderWrapper.class);
	assertThat(rootLogger.getAppender("TestStringAppender")).isEqualTo(stringAppender);

	verify(delegate, times(1)).setAppender(isA(CompositeAppender.class));

	Appender compositeAppender = delegate.getAppender();

	assertThat(compositeAppender).isInstanceOf(CompositeAppender.class);
	assertThat(((CompositeAppender) compositeAppender).getAppenderOne()).isEqualTo(DelegatingAppender.DEFAULT_APPENDER);
	assertThat(((CompositeAppender) compositeAppender).getAppenderTwo()).isEqualTo(stringAppender);
}
 
Example #11
Source File: KafkaAppender.java    From SkyEye with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void setContext(Context context) {
    super.setContext(context);

    this.host = SysUtil.host;
    this.app = context.getName();
}
 
Example #12
Source File: AppHostKeyBuilder.java    From SkyEye with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void setContext(Context context) {
    super.setContext(context);
    String host = context.getProperty(CoreConstants.HOSTNAME_KEY);
    String app = context.getName();
    appHost = ByteBuffer.allocate(4).putInt(new StringBuilder(app).append(host).toString().hashCode()).array();
}
 
Example #13
Source File: BaseLogbackAppenderTest.java    From logzio-logback-appender with Apache License 2.0 5 votes vote down vote up
protected Logger createLogger(LogzioLogbackAppender logzioLogbackAppender, String token, String type, String loggerName, Integer drainTimeout,
                            boolean addHostname, boolean line, String additionalFields,
                            boolean compressRequests) {
    logger.info("Creating logger {}. token={}, type={}, drainTimeout={}, addHostname={}, line={}, additionalFields={} ",
            loggerName, token, type, drainTimeout, addHostname, line, additionalFields);

    ch.qos.logback.classic.Logger logbackLogger =  (ch.qos.logback.classic.Logger) LoggerFactory.getLogger(loggerName);
    Context logbackContext = logbackLogger.getLoggerContext();
    logzioLogbackAppender.setContext(logbackContext);
    logzioLogbackAppender.setToken(token);
    logzioLogbackAppender.setLogzioType(type);
    logzioLogbackAppender.setDebug(true);
    logzioLogbackAppender.setLine(line);
    logzioLogbackAppender.setLogzioUrl("http://" + mockListener.getHost() + ":" + mockListener.getPort());
    logzioLogbackAppender.setAddHostname(addHostname);
    logzioLogbackAppender.setCompressRequests(compressRequests);
    logzioLogbackAppender.setName("LogzioLogbackAppender");
    if (drainTimeout != null) {
        logzioLogbackAppender.setDrainTimeoutSec(drainTimeout);
    }
    if (additionalFields != null) {
        logzioLogbackAppender.setAdditionalFields(additionalFields);
    }
    if (logzioLogbackAppender.getEncoder() != null) {
        logzioLogbackAppender.getEncoder().setContext(logbackContext);
        logzioLogbackAppender.getEncoder().start();
    }
    logzioLogbackAppender.start();
    assertThat(logzioLogbackAppender.isStarted()).isTrue();
    logbackLogger.addAppender(logzioLogbackAppender);
    logbackLogger.setAdditive(false);
    return logbackLogger;
}
 
Example #14
Source File: CompositeAppender.java    From spring-boot-data-geode with Apache License 2.0 5 votes vote down vote up
@Override
public void setContext(Context context) {

	super.setContext(context);

	getAppenderOne().setContext(context);
	getAppenderTwo().setContext(context);
}
 
Example #15
Source File: BrokerSyslogLoggerImpl.java    From qpid-broker-j with Apache License 2.0 5 votes vote down vote up
@Override
protected Appender<ILoggingEvent> createAppenderInstance(Context context)
{
    SyslogAppender syslogAppender = new SyslogAppender();
    syslogAppender.setSyslogHost(_syslogHost);
    syslogAppender.setPort(_port);
    syslogAppender.setSuffixPattern(_suffixPattern);
    syslogAppender.setStackTracePattern(_stackTracePattern);
    syslogAppender.setThrowableExcluded(_throwableExcluded);
    syslogAppender.setFacility("USER");
    return syslogAppender;
}
 
Example #16
Source File: CustomFieldsAdapter.java    From cf-java-logging-support with Apache License 2.0 5 votes vote down vote up
public void initialize(Context context) {
	if (context == null) {
		return;
	}
	customFieldExclusions = calculateExclusions(context);
	customFieldMdcKeyNames = getListItemsAsStrings(context, OPTION_MDC_CUSTOM_FIELDS);
}
 
Example #17
Source File: ExceptionConverter.java    From styx with Apache License 2.0 5 votes vote down vote up
private String[] readStyxClassesFromProperty() {
    String[] targetClasses = TARGET_CLASSES_DEFAULT;
    Context ctx = getContext();
    String property = ctx.getProperty(TARGET_CLASSES_PROPERTY_NAME);
    if (isNotEmpty(property)) {
        targetClasses = stream(property.split(","))
                .map(String::trim)
                .toArray(String[]::new);
    } else {
        addError(MessageFormat.format("The '{0}' property should be present on logback configuration. Using default classname prefixes.",
                TARGET_CLASSES_PROPERTY_NAME));
    }
    return targetClasses;
}
 
Example #18
Source File: StringAppender.java    From spring-boot-data-geode with Apache License 2.0 5 votes vote down vote up
private Context resolveContext() {

			return this.context != null
				? this.context
				: Optional.ofNullable(LoggerFactory.getILoggerFactory())
					.filter(Context.class::isInstance)
					.map(Context.class::cast)
					.orElse(null);
		}
 
Example #19
Source File: ChildConverterContextInjector.java    From cf-java-logging-support with Apache License 2.0 5 votes vote down vote up
private void inject(Context context, Converter<ILoggingEvent> head, boolean injectAll) {
	for (Converter<ILoggingEvent> c = head; c != null; c = c.getNext()) {
		if (c instanceof CompositeConverter<?>) {
			Converter<ILoggingEvent> childConverter = ((CompositeConverter<ILoggingEvent>) c).getChildConverter();
			inject(context, childConverter, true);
		}
		if (injectAll && c instanceof ContextAware) {
			((ContextAware) c).setContext(context);
		}
	}
}
 
Example #20
Source File: ChildConverterContextInjectorTest.java    From cf-java-logging-support with Apache License 2.0 5 votes vote down vote up
@Test
public void doesNotInjectContextInSingleConverter() throws Exception {
	DynamicConverter<ILoggingEvent> converter = new ContextAwareTestConverter();

	processor.process(Mockito.mock(Context.class), converter);

	assertNull("No context should be set.", converter.getContext());
}
 
Example #21
Source File: ChildConverterContextInjectorTest.java    From cf-java-logging-support with Apache License 2.0 5 votes vote down vote up
@Test
public void injectsContextInSingleChild() throws Exception {
	CompositeTestConverter parent = new CompositeTestConverter();
	ContextAwareTestConverter child = new ContextAwareTestConverter();
	parent.setChildConverter(child);
	Context context = Mockito.mock(Context.class);

	processor.process(context, parent);

	assertThat(child.getContext(), is(sameInstance(context)));
}
 
Example #22
Source File: ChildConverterContextInjectorTest.java    From cf-java-logging-support with Apache License 2.0 5 votes vote down vote up
@Test
public void followsChainToConverterWithChild() throws Exception {
	SimpleTestConverter start = new SimpleTestConverter();
	CompositeTestConverter parent = new CompositeTestConverter();
	ContextAwareTestConverter child = new ContextAwareTestConverter();
	start.setNext(parent);
	parent.setChildConverter(child);
	Context context = Mockito.mock(Context.class);

	processor.process(context, parent);

	assertThat(child.getContext(), is(sameInstance(context)));
}
 
Example #23
Source File: ChildConverterContextInjectorTest.java    From cf-java-logging-support with Apache License 2.0 5 votes vote down vote up
@Test
public void injectsIntoChildrenOfChildren() throws Exception {
	CompositeTestConverter grandParent = new CompositeTestConverter();
	CompositeTestConverter parent = new CompositeTestConverter();
	ContextAwareTestConverter child = new ContextAwareTestConverter();
	grandParent.setChildConverter(parent);
	parent.setChildConverter(child);
	Context context = Mockito.mock(Context.class);

	processor.process(context, grandParent);

	assertThat(parent.getContext(), is(sameInstance(context)));
	assertThat(child.getContext(), is(sameInstance(context)));
}
 
Example #24
Source File: ChildConverterContextInjectorTest.java    From cf-java-logging-support with Apache License 2.0 5 votes vote down vote up
@Test
public void injectsIntoFullChildChain() throws Exception {
	CompositeTestConverter parent = new CompositeTestConverter();
	SimpleTestConverter child1 = new SimpleTestConverter();
	ContextAwareTestConverter child2 = new ContextAwareTestConverter();
	parent.setChildConverter(child1);
	child1.setNext(child2);
	Context context = Mockito.mock(Context.class);

	processor.process(context, parent);

	assertThat(child2.getContext(), is(sameInstance(context)));

}
 
Example #25
Source File: Slf4jLoggerFactoryTest.java    From rocketmq with Apache License 2.0 5 votes vote down vote up
@Before
public void initLogback() throws JoranException {
    InternalLoggerFactory.setCurrentLoggerType(InternalLoggerFactory.LOGGER_SLF4J);
    System.setProperty("loggingDir", loggingDir);
    ILoggerFactory iLoggerFactory = LoggerFactory.getILoggerFactory();
    JoranConfigurator joranConfigurator = new JoranConfigurator();
    joranConfigurator.setContext((Context) iLoggerFactory);
    URL logbackConfigFile = Slf4jLoggerFactoryTest.class.getClassLoader().getResource("logback_test.xml");
    if (logbackConfigFile == null) {
        throw new RuntimeException("can't find logback_test.xml");
    } else {
        joranConfigurator.doConfigure(logbackConfigFile);
    }
}
 
Example #26
Source File: LoggerStartupListener.java    From archivo with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void start() {
    if (started) {
        return;
    }

    Path dataDir = OSHelper.getDataDirectory();

    Context context = getContext();
    context.putProperty("DATA_DIR", dataDir.toString());

    started = true;
}
 
Example #27
Source File: HostNameKeyingStrategy.java    From logback-kafka-appender with Apache License 2.0 5 votes vote down vote up
@Override
public void setContext(Context context) {
    super.setContext(context);
    final String hostname = context.getProperty(CoreConstants.HOSTNAME_KEY);
    if (hostname == null) {
        if (!errorWasShown) {
        addError("Hostname could not be found in context. HostNamePartitioningStrategy will not work.");
            errorWasShown = true;
        }
    } else {
        hostnameHash = ByteBuffer.allocate(4).putInt(hostname.hashCode()).array();
    }
}
 
Example #28
Source File: ContextNameKeyingStrategy.java    From logback-kafka-appender with Apache License 2.0 5 votes vote down vote up
@Override
public void setContext(Context context) {
    super.setContext(context);
    final String hostname = context.getProperty(CoreConstants.CONTEXT_NAME_KEY);
    if (hostname == null) {
        addError("Hostname could not be found in context. HostNamePartitioningStrategy will not work.");
    } else {
        contextNameHash = ByteBuffer.allocate(4).putInt(hostname.hashCode()).array();
    }
}
 
Example #29
Source File: LogConfigurator.java    From gocd with Apache License 2.0 5 votes vote down vote up
private void allowCleanShutdown() {
    DelayingShutdownHook hook = new DelayingShutdownHook();
    Context context = (Context) this.loggerFactory;
    hook.setContext(context);
    Thread hookThread = new Thread(hook, "Logback shutdown hook [" + context.getName() + "]");
    Runtime.getRuntime().addShutdownHook(hookThread);
}
 
Example #30
Source File: LogConfigurator.java    From gocd with Apache License 2.0 5 votes vote down vote up
protected void configureWith(URL resource) {
    JoranConfigurator configurator = new JoranConfigurator();
    configurator.setContext((LoggerContext) loggerFactory);
    ((LoggerContext) loggerFactory).reset();

    // the statusManager keeps a copy of all logback status messages even after reset, so we clear that
    ((LoggerContext) loggerFactory).getStatusManager().clear();
    try {
        configurator.doConfigure(resource);
    } catch (JoranException ignore) {
    }
    StatusPrinter.printInCaseOfErrorsOrWarnings((Context) loggerFactory);
}