Java Code Examples for ch.qos.logback.core.Context

The following examples show how to use ch.qos.logback.core.Context. These examples are extracted from open source projects. 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 Project: justtestlah   Source File: ApplicationInfoEnricher.java    License: 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 2
Source Project: qpid-broker-j   Source File: BrokerFileLoggerImpl.java    License: 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 3
Source Project: qpid-broker-j   Source File: BrokerConsoleLoggerImpl.java    License: 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 4
Source Project: qpid-broker-j   Source File: StartupAppender.java    License: 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 Project: qpid-broker-j   Source File: RollingPolicyDecoratorTest.java    License: 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 6
Source Project: qpid-broker-j   Source File: JDBCLoggerHelper.java    License: 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 Project: singer   Source File: AppenderUtils.java    License: 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 Project: frpMgr   Source File: LoggerStartupListener.java    License: MIT License 5 votes vote down vote up
@Override
public void start() {
	if (started)
		return;
	String userHome = System.getProperty("user.home");
	Context context = getContext();
	context.putProperty("USER_HOME", userHome);
	started = true;
}
 
Example 9
Source Project: rocketmq-4.3.0   Source File: Slf4jLoggerFactoryTest.java    License: 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 10
Source Project: rocketmq-read   Source File: Slf4jLoggerFactoryTest.java    License: 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 11
@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 12
@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 13
Source Project: styx   Source File: LoggingTestSupport.java    License: Apache License 2.0 5 votes vote down vote up
private ListAppender<ILoggingEvent> addListAppender() {
    ListAppender<ILoggingEvent> appender = new ListAppender<>();
    appender.setContext((Context) LoggerFactory.getILoggerFactory());
    appender.start();

    logger.addAppender(appender);

    return appender;
}
 
Example 14
Source Project: styx   Source File: ExceptionConverter.java    License: 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 15
Source Project: qpid-broker-j   Source File: VirtualHostSyslogLoggerImpl.java    License: 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 Project: qpid-broker-j   Source File: BrokerSyslogLoggerImpl.java    License: 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 17
Source Project: qpid-broker-j   Source File: BrokerMemoryLoggerImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected Appender<ILoggingEvent> createAppenderInstance(Context context)
{
    if (_logRecorder != null)
    {
        throw new IllegalStateException("RecordEventAppender is already created");
    }
    RecordEventAppender appender =  new RecordEventAppender(getMaxRecords());
    _logRecorder = new LogRecorder(appender);
    return appender;
}
 
Example 18
Source Project: qpid-broker-j   Source File: VirtualHostFileLoggerImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected Appender<ILoggingEvent> createAppenderInstance(Context loggerContext)
{
    final RollingFileAppender<ILoggingEvent> appender = new RollingFileAppender<>();
    AppenderUtils.configureRollingFileAppender(this, loggerContext, appender);
    return appender;
}
 
Example 19
Source Project: qpid-broker-j   Source File: BrokerLoggerTest.java    License: Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws Exception
{

    _taskExecutor = new TaskExecutorImpl();
    _taskExecutor.start();

    _loggerAppender = new ListAppender<>();
    _loggerAppender.setName(APPENDER_NAME);


    Model model = BrokerModel.getInstance();

    _broker = mock(Broker.class);
    when(_broker.getCategoryClass()).thenReturn(Broker.class);
    when(_broker.getTypeClass()).thenReturn(Broker.class);
    when(_broker.getModel()).thenReturn(model);
    when(_broker.getChildExecutor()).thenReturn(_taskExecutor);
    doReturn(Broker.class).when(_broker).getCategoryClass();

    Map<String, Object> attributes = new HashMap<>();
    attributes.put("name", APPENDER_NAME);
    _brokerLogger = new AbstractBrokerLogger(attributes, _broker)
    {
        @Override
        public Appender<ILoggingEvent> createAppenderInstance(Context context)
        {
            return _loggerAppender;
        }
    };
    _brokerLogger.open();
}
 
Example 20
Source Project: qpid-broker-j   Source File: JDBCBrokerLoggerImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected Appender<ILoggingEvent> createAppenderInstance(final Context context)
{
    final SystemConfig<?> systemConfig = getAncestor(SystemConfig.class);
    _logbackStatusListener = new BrokerLoggerStatusListener(this,
                                                            systemConfig,
                                                            BROKER_FAIL_ON_JDBC_LOGGER_ERROR,
                                                            SQLException.class);
    _statusManager = context.getStatusManager();
    _statusManager.add(_logbackStatusListener);

    return _jdbcLoggerHelper.createAppenderInstance(context, this, this);
}
 
Example 21
Source Project: qpid-broker-j   Source File: JDBCLoggerHelper.java    License: Apache License 2.0 5 votes vote down vote up
private ConnectionSource createConnectionSource(final Context context,
                                                final ConfiguredObject<?> logger,
                                                final JDBCSettings settings)
{
    final JDBCSettingsDrivenConnectionSource connectionSource =
            new JDBCSettingsDrivenConnectionSource(logger, settings);
    connectionSource.setContext(context);
    connectionSource.start();
    return connectionSource;
}
 
Example 22
Source Project: spring-boot-data-geode   Source File: CompositeAppender.java    License: 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 23
Source Project: spring-boot-data-geode   Source File: StringAppender.java    License: 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 24
Source Project: spring-boot-data-geode   Source File: DelegatingAppender.java    License: 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 25
@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 26
Source Project: SkyEye   Source File: KafkaAppender.java    License: 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 27
Source Project: SkyEye   Source File: AppHostKeyBuilder.java    License: 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 28
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 29
public void initialize(Context context) {
	if (context == null) {
		return;
	}
	customFieldExclusions = calculateExclusions(context);
	customFieldMdcKeyNames = getListItemsAsStrings(context, OPTION_MDC_CUSTOM_FIELDS);
}
 
Example 30
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();
}