Search in sources :

Example 81 with LoggerContext

use of ch.qos.logback.classic.LoggerContext in project spring-boot by spring-projects.

the class LogbackLoggingSystem method loadConfiguration.

@Override
protected void loadConfiguration(LoggingInitializationContext initializationContext, String location, LogFile logFile) {
    super.loadConfiguration(initializationContext, location, logFile);
    LoggerContext loggerContext = getLoggerContext();
    stopAndReset(loggerContext);
    try {
        configureByResourceUrl(initializationContext, loggerContext, ResourceUtils.getURL(location));
    } catch (Exception ex) {
        throw new IllegalStateException("Could not initialize Logback logging from " + location, ex);
    }
    List<Status> statuses = loggerContext.getStatusManager().getCopyOfStatusList();
    StringBuilder errors = new StringBuilder();
    for (Status status : statuses) {
        if (status.getLevel() == Status.ERROR) {
            errors.append(errors.length() > 0 ? String.format("%n") : "");
            errors.append(status.toString());
        }
    }
    if (errors.length() > 0) {
        throw new IllegalStateException(String.format("Logback configuration error detected: %n%s", errors));
    }
}
Also used : Status(ch.qos.logback.core.status.Status) LoggerContext(ch.qos.logback.classic.LoggerContext) JoranException(ch.qos.logback.core.joran.spi.JoranException)

Example 82 with LoggerContext

use of ch.qos.logback.classic.LoggerContext in project spring-boot by spring-projects.

the class LogbackLoggingSystem method beforeInitialize.

@Override
public void beforeInitialize() {
    LoggerContext loggerContext = getLoggerContext();
    if (isAlreadyInitialized(loggerContext)) {
        return;
    }
    super.beforeInitialize();
    loggerContext.getTurboFilterList().add(FILTER);
    configureJBossLoggingToUseSlf4j();
}
Also used : LoggerContext(ch.qos.logback.classic.LoggerContext)

Example 83 with LoggerContext

use of ch.qos.logback.classic.LoggerContext in project spring-boot by spring-projects.

the class LogbackLoggingSystem method initialize.

@Override
public void initialize(LoggingInitializationContext initializationContext, String configLocation, LogFile logFile) {
    LoggerContext loggerContext = getLoggerContext();
    if (isAlreadyInitialized(loggerContext)) {
        return;
    }
    loggerContext.getTurboFilterList().remove(FILTER);
    super.initialize(initializationContext, configLocation, logFile);
    markAsInitialized(loggerContext);
    if (StringUtils.hasText(System.getProperty(CONFIGURATION_FILE_PROPERTY))) {
        getLogger(LogbackLoggingSystem.class.getName()).warn("Ignoring '" + CONFIGURATION_FILE_PROPERTY + "' system property. " + "Please use 'logging.config' instead.");
    }
}
Also used : LoggerContext(ch.qos.logback.classic.LoggerContext)

Example 84 with LoggerContext

use of ch.qos.logback.classic.LoggerContext in project spring-boot by spring-projects.

the class ConfigFileApplicationListenerTests method resetLogging.

@Before
public void resetLogging() {
    LoggerContext loggerContext = ((Logger) LoggerFactory.getLogger(getClass())).getLoggerContext();
    loggerContext.reset();
    new BasicConfigurator().configure(loggerContext);
}
Also used : BasicConfigurator(ch.qos.logback.classic.BasicConfigurator) Logger(ch.qos.logback.classic.Logger) LoggerContext(ch.qos.logback.classic.LoggerContext) Before(org.junit.Before)

Example 85 with LoggerContext

use of ch.qos.logback.classic.LoggerContext in project cdap by caskdata.

the class LocalLogAppenderResilientTest method testResilientLogging.

@Test
public void testResilientLogging() throws Exception {
    Configuration hConf = new Configuration();
    CConfiguration cConf = CConfiguration.create();
    File datasetDir = new File(tmpFolder.newFolder(), "datasetUser");
    //noinspection ResultOfMethodCallIgnored
    datasetDir.mkdirs();
    cConf.set(Constants.Dataset.Manager.OUTPUT_DIR, datasetDir.getAbsolutePath());
    cConf.set(Constants.Service.MASTER_SERVICES_BIND_ADDRESS, "localhost");
    cConf.set(Constants.Dataset.Executor.ADDRESS, "localhost");
    cConf.setInt(Constants.Dataset.Executor.PORT, Networks.getRandomPort());
    cConf.set(Constants.CFG_LOCAL_DATA_DIR, tmpFolder.newFolder().getAbsolutePath());
    Injector injector = Guice.createInjector(new ConfigModule(cConf, hConf), new IOModule(), new ZKClientModule(), new KafkaClientModule(), new DiscoveryRuntimeModule().getInMemoryModules(), new NonCustomLocationUnitTestModule().getModule(), new DataFabricModules().getInMemoryModules(), new DataSetsModules().getStandaloneModules(), new DataSetServiceModules().getInMemoryModules(), new TransactionMetricsModule(), new ExploreClientModule(), new LoggingModules().getInMemoryModules(), new NamespaceClientRuntimeModule().getInMemoryModules(), new AuthorizationTestModule(), new AuthorizationEnforcementModule().getInMemoryModules(), new AuthenticationContextModules().getMasterModule(), new AbstractModule() {

        @Override
        protected void configure() {
            bind(UGIProvider.class).to(UnsupportedUGIProvider.class);
            bind(OwnerAdmin.class).to(NoOpOwnerAdmin.class);
        }
    });
    TransactionManager txManager = injector.getInstance(TransactionManager.class);
    txManager.startAndWait();
    DatasetOpExecutorService opExecutorService = injector.getInstance(DatasetOpExecutorService.class);
    opExecutorService.startAndWait();
    // Start the logging before starting the service.
    LoggingContextAccessor.setLoggingContext(new FlowletLoggingContext("TRL_ACCT_1", "APP_1", "FLOW_1", "FLOWLET_1", "RUN", "INSTANCE"));
    String logBaseDir = "trl-log/log_files_" + new Random(System.currentTimeMillis()).nextLong();
    cConf.set(LoggingConfiguration.LOG_BASE_DIR, logBaseDir);
    cConf.setInt(LoggingConfiguration.LOG_MAX_FILE_SIZE_BYTES, 20 * 1024);
    final LogAppender appender = injector.getInstance(LocalLogAppender.class);
    new LogAppenderInitializer(appender).initialize("TestResilientLogging");
    int failureMsgCount = 3;
    final CountDownLatch failureLatch = new CountDownLatch(failureMsgCount);
    LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();
    loggerContext.getStatusManager().add(new StatusListener() {

        @Override
        public void addStatusEvent(Status status) {
            if (status.getLevel() != Status.ERROR || status.getOrigin() != appender) {
                return;
            }
            Throwable cause = status.getThrowable();
            if (cause != null) {
                Throwable rootCause = Throwables.getRootCause(cause);
                if (rootCause instanceof ServiceUnavailableException) {
                    String serviceName = ((ServiceUnavailableException) rootCause).getServiceName();
                    if (Constants.Service.DATASET_MANAGER.equals(serviceName)) {
                        failureLatch.countDown();
                    }
                }
            }
        }
    });
    Logger logger = LoggerFactory.getLogger("TestResilientLogging");
    for (int i = 0; i < failureMsgCount; ++i) {
        Exception e1 = new Exception("Test Exception1");
        Exception e2 = new Exception("Test Exception2", e1);
        logger.warn("Test log message " + i + " {} {}", "arg1", "arg2", e2);
    }
    // Wait for the three failure to append to happen
    // The wait time has to be > 3 seconds because DatasetServiceClient has 1 second timeout on discovery
    failureLatch.await(5, TimeUnit.SECONDS);
    // Start dataset service, wait for it to be discoverable
    DatasetService dsService = injector.getInstance(DatasetService.class);
    dsService.startAndWait();
    final CountDownLatch startLatch = new CountDownLatch(1);
    DiscoveryServiceClient discoveryClient = injector.getInstance(DiscoveryServiceClient.class);
    discoveryClient.discover(Constants.Service.DATASET_MANAGER).watchChanges(new ServiceDiscovered.ChangeListener() {

        @Override
        public void onChange(ServiceDiscovered serviceDiscovered) {
            if (!Iterables.isEmpty(serviceDiscovered)) {
                startLatch.countDown();
            }
        }
    }, Threads.SAME_THREAD_EXECUTOR);
    startLatch.await(5, TimeUnit.SECONDS);
    // Do some more logging after the service is started.
    for (int i = 5; i < 10; ++i) {
        Exception e1 = new Exception("Test Exception1");
        Exception e2 = new Exception("Test Exception2", e1);
        logger.warn("Test log message " + i + " {} {}", "arg1", "arg2", e2);
    }
    appender.stop();
    // Verify - we should have at least 5 events.
    LoggingContext loggingContext = new FlowletLoggingContext("TRL_ACCT_1", "APP_1", "FLOW_1", "", "RUN", "INSTANCE");
    FileLogReader logTail = injector.getInstance(FileLogReader.class);
    LoggingTester.LogCallback logCallback1 = new LoggingTester.LogCallback();
    logTail.getLogPrev(loggingContext, ReadRange.LATEST, 10, Filter.EMPTY_FILTER, logCallback1);
    List<LogEvent> allEvents = logCallback1.getEvents();
    Assert.assertTrue(allEvents.toString(), allEvents.size() >= 5);
    // Finally - stop all services
    Services.chainStop(dsService, opExecutorService, txManager);
}
Also used : NoOpOwnerAdmin(co.cask.cdap.security.impersonation.NoOpOwnerAdmin) DataSetServiceModules(co.cask.cdap.data.runtime.DataSetServiceModules) DiscoveryServiceClient(org.apache.twill.discovery.DiscoveryServiceClient) CConfiguration(co.cask.cdap.common.conf.CConfiguration) Configuration(org.apache.hadoop.conf.Configuration) LoggingConfiguration(co.cask.cdap.logging.LoggingConfiguration) LocalLogAppender(co.cask.cdap.logging.framework.local.LocalLogAppender) DatasetService(co.cask.cdap.data2.datafabric.dataset.service.DatasetService) TransactionMetricsModule(co.cask.cdap.data.runtime.TransactionMetricsModule) FileLogReader(co.cask.cdap.logging.read.FileLogReader) Random(java.util.Random) Injector(com.google.inject.Injector) KafkaClientModule(co.cask.cdap.common.guice.KafkaClientModule) FlowletLoggingContext(co.cask.cdap.logging.context.FlowletLoggingContext) DiscoveryRuntimeModule(co.cask.cdap.common.guice.DiscoveryRuntimeModule) Status(ch.qos.logback.core.status.Status) LogEvent(co.cask.cdap.logging.read.LogEvent) AuthenticationContextModules(co.cask.cdap.security.auth.context.AuthenticationContextModules) ServiceDiscovered(org.apache.twill.discovery.ServiceDiscovered) NonCustomLocationUnitTestModule(co.cask.cdap.common.guice.NonCustomLocationUnitTestModule) CConfiguration(co.cask.cdap.common.conf.CConfiguration) ExploreClientModule(co.cask.cdap.explore.guice.ExploreClientModule) TransactionManager(org.apache.tephra.TransactionManager) File(java.io.File) DataFabricModules(co.cask.cdap.data.runtime.DataFabricModules) AuthorizationEnforcementModule(co.cask.cdap.security.authorization.AuthorizationEnforcementModule) IOModule(co.cask.cdap.common.guice.IOModule) NamespaceClientRuntimeModule(co.cask.cdap.common.namespace.guice.NamespaceClientRuntimeModule) LoggingContext(co.cask.cdap.common.logging.LoggingContext) FlowletLoggingContext(co.cask.cdap.logging.context.FlowletLoggingContext) ConfigModule(co.cask.cdap.common.guice.ConfigModule) ServiceUnavailableException(co.cask.cdap.common.ServiceUnavailableException) Logger(org.slf4j.Logger) ZKClientModule(co.cask.cdap.common.guice.ZKClientModule) UnsupportedUGIProvider(co.cask.cdap.security.impersonation.UnsupportedUGIProvider) DataSetsModules(co.cask.cdap.data.runtime.DataSetsModules) CountDownLatch(java.util.concurrent.CountDownLatch) AuthorizationTestModule(co.cask.cdap.security.authorization.AuthorizationTestModule) LoggerContext(ch.qos.logback.classic.LoggerContext) ServiceUnavailableException(co.cask.cdap.common.ServiceUnavailableException) LoggingModules(co.cask.cdap.logging.guice.LoggingModules) AbstractModule(com.google.inject.AbstractModule) DatasetOpExecutorService(co.cask.cdap.data2.datafabric.dataset.service.executor.DatasetOpExecutorService) StatusListener(ch.qos.logback.core.status.StatusListener) Test(org.junit.Test)

Aggregations

LoggerContext (ch.qos.logback.classic.LoggerContext)216 Test (org.junit.Test)134 ILoggingEvent (ch.qos.logback.classic.spi.ILoggingEvent)43 Logger (ch.qos.logback.classic.Logger)41 PatternLayoutEncoder (ch.qos.logback.classic.encoder.PatternLayoutEncoder)26 FileAppender (ch.qos.logback.core.FileAppender)22 File (java.io.File)21 JoranConfigurator (ch.qos.logback.classic.joran.JoranConfigurator)19 RollingFileAppender (ch.qos.logback.core.rolling.RollingFileAppender)16 Appender (ch.qos.logback.core.Appender)14 ConsoleAppender (ch.qos.logback.core.ConsoleAppender)14 JoranException (ch.qos.logback.core.joran.spi.JoranException)14 NullLevelFilterFactory (io.dropwizard.logging.filter.NullLevelFilterFactory)13 AsyncLoggingEventAppenderFactory (io.dropwizard.logging.async.AsyncLoggingEventAppenderFactory)12 AsyncAppender (ch.qos.logback.classic.AsyncAppender)11 DropwizardLayoutFactory (io.dropwizard.logging.layout.DropwizardLayoutFactory)11 Logger (org.slf4j.Logger)10 IOException (java.io.IOException)8 TimeBasedRollingPolicy (ch.qos.logback.core.rolling.TimeBasedRollingPolicy)7 URL (java.net.URL)7