Search in sources :

Example 1 with AppenderContext

use of io.cdap.cdap.api.logging.AppenderContext in project cdap by caskdata.

the class RollingLocationLogAppender method start.

@Override
public void start() {
    // These should all passed. The settings are from the custom-log-pipeline.xml and
    // the context must be AppenderContext
    Preconditions.checkState(basePath != null, "Property basePath must be base directory.");
    Preconditions.checkState(filePath != null, "Property filePath must be filePath along with filename.");
    Preconditions.checkState(triggeringPolicy != null, "Property triggeringPolicy must be specified.");
    Preconditions.checkState(rollingPolicy != null, "Property rollingPolicy must be specified");
    Preconditions.checkState(encoder != null, "Property encoder must be specified.");
    Preconditions.checkState(dirPermissions != null, "Property dirPermissions cannot be null");
    Preconditions.checkState(filePermissions != null, "Property filePermissions cannot be null");
    if (context instanceof AppenderContext) {
        AppenderContext context = (AppenderContext) this.context;
        locationManager = new LocationManager(context.getLocationFactory(), basePath, dirPermissions, filePermissions, fileMaxInactiveTimeMs);
        filePath = filePath.replace("instanceId", Integer.toString(context.getInstanceId()));
    } else if (!Boolean.TRUE.equals(context.getObject(Constants.Logging.PIPELINE_VALIDATION))) {
        throw new IllegalStateException("Expected logger context instance of " + AppenderContext.class.getName() + " but got " + context.getClass().getName());
    }
    started = true;
}
Also used : AppenderContext(io.cdap.cdap.api.logging.AppenderContext)

Example 2 with AppenderContext

use of io.cdap.cdap.api.logging.AppenderContext in project cdap by caskdata.

the class FixedWindowRollingPolicy method start.

@Override
public void start() {
    if (fileNamePatternStr != null) {
        if (context instanceof AppenderContext) {
            AppenderContext context = (AppenderContext) this.context;
            fileNamePatternStr = fileNamePatternStr.replace("instanceId", Integer.toString(context.getInstanceId()));
        } else if (!Boolean.TRUE.equals(context.getObject(Constants.Logging.PIPELINE_VALIDATION))) {
            throw new IllegalStateException("Expected logger context instance of " + AppenderContext.class.getName() + " but got " + context.getClass().getName());
        }
        fileNamePattern = new FileNamePattern(fileNamePatternStr, this.context);
    } else {
        LOG.error(FNP_NOT_SET);
        throw new IllegalStateException(FNP_NOT_SET + CoreConstants.SEE_FNP_NOT_SET);
    }
    if (maxIndex < minIndex) {
        LOG.warn("MaxIndex {} cannot be smaller than MinIndex {}.", maxIndex, minIndex);
        maxIndex = minIndex;
    }
    if ((maxIndex - minIndex) > MAX_WINDOW_SIZE) {
        LOG.warn("Large window sizes are not allowed.");
        maxIndex = minIndex + MAX_WINDOW_SIZE;
        LOG.warn("MaxIndex reduced to " + maxIndex);
    }
    IntegerTokenConverter itc = fileNamePattern.getIntegerTokenConverter();
    if (itc == null) {
        throw new IllegalStateException("FileNamePattern [" + fileNamePattern.getPattern() + "] does not contain a valid IntegerToken");
    }
    processedIndex = maxIndex;
    super.start();
}
Also used : FileNamePattern(ch.qos.logback.core.rolling.helper.FileNamePattern) IntegerTokenConverter(ch.qos.logback.core.rolling.helper.IntegerTokenConverter) AppenderContext(io.cdap.cdap.api.logging.AppenderContext)

Example 3 with AppenderContext

use of io.cdap.cdap.api.logging.AppenderContext in project cdap by caskdata.

the class CDAPLogAppenderTest method testCDAPLogAppender.

@Test
public void testCDAPLogAppender() {
    int syncInterval = 1024 * 1024;
    CDAPLogAppender cdapLogAppender = new CDAPLogAppender();
    cdapLogAppender.setSyncIntervalBytes(syncInterval);
    cdapLogAppender.setMaxFileLifetimeMs(TimeUnit.DAYS.toMillis(1));
    cdapLogAppender.setMaxFileSizeInBytes(104857600);
    cdapLogAppender.setDirPermissions("700");
    cdapLogAppender.setFilePermissions("600");
    cdapLogAppender.setFileRetentionDurationDays(1);
    cdapLogAppender.setLogCleanupIntervalMins(10);
    cdapLogAppender.setFileCleanupBatchSize(100);
    AppenderContext context = new LocalAppenderContext(injector.getInstance(TransactionRunner.class), injector.getInstance(LocationFactory.class), new NoOpMetricsCollectionService());
    context.start();
    cdapLogAppender.setContext(context);
    cdapLogAppender.start();
    FileMetaDataReader fileMetaDataReader = injector.getInstance(FileMetaDataReader.class);
    LoggingEvent event = new LoggingEvent("io.cdap.Test", (ch.qos.logback.classic.Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME), Level.ERROR, "test message", null, null);
    Map<String, String> properties = new HashMap<>();
    properties.put(NamespaceLoggingContext.TAG_NAMESPACE_ID, "default");
    properties.put(ApplicationLoggingContext.TAG_APPLICATION_ID, "testApp");
    properties.put(UserServiceLoggingContext.TAG_USER_SERVICE_ID, "testService");
    event.setMDCPropertyMap(properties);
    cdapLogAppender.doAppend(event);
    cdapLogAppender.stop();
    context.stop();
    try {
        List<LogLocation> files = fileMetaDataReader.listFiles(cdapLogAppender.getLoggingPath(properties), 0, Long.MAX_VALUE);
        Assert.assertEquals(1, files.size());
        LogLocation logLocation = files.get(0);
        Assert.assertEquals(LogLocation.VERSION_1, logLocation.getFrameworkVersion());
        Assert.assertTrue(logLocation.getLocation().exists());
        CloseableIterator<LogEvent> logEventCloseableIterator = logLocation.readLog(Filter.EMPTY_FILTER, 0, Long.MAX_VALUE, Integer.MAX_VALUE);
        int logCount = 0;
        while (logEventCloseableIterator.hasNext()) {
            logCount++;
            LogEvent logEvent = logEventCloseableIterator.next();
            Assert.assertEquals(event.getMessage(), logEvent.getLoggingEvent().getMessage());
        }
        logEventCloseableIterator.close();
        Assert.assertEquals(1, logCount);
        // checking permission
        String expectedPermissions = "rw-------";
        for (LogLocation file : files) {
            Location location = file.getLocation();
            Assert.assertEquals(expectedPermissions, location.getPermissions());
        }
    } catch (Exception e) {
        Assert.fail();
    }
}
Also used : HashMap(java.util.HashMap) LogEvent(io.cdap.cdap.logging.read.LogEvent) NoOpMetricsCollectionService(io.cdap.cdap.common.metrics.NoOpMetricsCollectionService) IOException(java.io.IOException) LocationFactory(org.apache.twill.filesystem.LocationFactory) LoggingEvent(ch.qos.logback.classic.spi.LoggingEvent) LocalAppenderContext(io.cdap.cdap.logging.framework.LocalAppenderContext) TransactionRunner(io.cdap.cdap.spi.data.transaction.TransactionRunner) LogLocation(io.cdap.cdap.logging.write.LogLocation) AppenderContext(io.cdap.cdap.api.logging.AppenderContext) LocalAppenderContext(io.cdap.cdap.logging.framework.LocalAppenderContext) FileMetaDataReader(io.cdap.cdap.logging.meta.FileMetaDataReader) Location(org.apache.twill.filesystem.Location) LogLocation(io.cdap.cdap.logging.write.LogLocation) Test(org.junit.Test)

Example 4 with AppenderContext

use of io.cdap.cdap.api.logging.AppenderContext in project cdap by caskdata.

the class RollingLocationLogAppenderTest method testRollOver.

@Test
public void testRollOver() throws Exception {
    // assume SLF4J is bound to logback in the current environment
    AppenderContext appenderContext = new LocalAppenderContext(injector.getInstance(TransactionRunner.class), injector.getInstance(LocationFactory.class), new NoOpMetricsCollectionService());
    JoranConfigurator configurator = new JoranConfigurator();
    configurator.setContext(appenderContext);
    // Call context.reset() to clear any previous configuration, e.g. default
    // configuration. For multi-step configuration, omit calling context.reset().
    appenderContext.reset();
    configurator.doConfigure(getClass().getResourceAsStream("/rolling-appender-logback-test.xml"));
    StatusPrinter.printInCaseOfErrorsOrWarnings(appenderContext);
    RollingLocationLogAppender rollingAppender = (RollingLocationLogAppender) appenderContext.getLogger(RollingLocationLogAppenderTest.class).getAppender("rollingAppender");
    addTagsToMdc("testNs", "testApp");
    Logger logger = appenderContext.getLogger(RollingLocationLogAppenderTest.class);
    ingestLogs(logger, 20000);
    Map<LocationIdentifier, LocationOutputStream> activeFiles = rollingAppender.getLocationManager().getActiveLocations();
    Assert.assertEquals(1, activeFiles.size());
    LocationOutputStream locationOutputStream = activeFiles.get(new LocationIdentifier("testNs", "testApp"));
    Location parentDir = Locations.getParent(locationOutputStream.getLocation());
    Assert.assertEquals(10, parentDir.list().size());
    // different program should go to different directory
    addTagsToMdc("testNs", "testApp1");
    ingestLogs(logger, 20000);
    activeFiles = rollingAppender.getLocationManager().getActiveLocations();
    Assert.assertEquals(2, activeFiles.size());
    locationOutputStream = activeFiles.get(new LocationIdentifier("testNs", "testApp1"));
    parentDir = Locations.getParent(locationOutputStream.getLocation());
    Assert.assertEquals(10, parentDir.list().size());
    // different program should go to different directory because namespace is different
    addTagsToMdc("testNs1", "testApp1");
    ingestLogs(logger, 20000);
    activeFiles = rollingAppender.getLocationManager().getActiveLocations();
    Assert.assertEquals(3, activeFiles.size());
    locationOutputStream = activeFiles.get(new LocationIdentifier("testNs1", "testApp1"));
    parentDir = Locations.getParent(locationOutputStream.getLocation());
    Assert.assertEquals(10, parentDir.list().size());
}
Also used : LocalAppenderContext(io.cdap.cdap.logging.framework.LocalAppenderContext) TransactionRunner(io.cdap.cdap.spi.data.transaction.TransactionRunner) JoranConfigurator(ch.qos.logback.classic.joran.JoranConfigurator) AppenderContext(io.cdap.cdap.api.logging.AppenderContext) LocalAppenderContext(io.cdap.cdap.logging.framework.LocalAppenderContext) NoOpMetricsCollectionService(io.cdap.cdap.common.metrics.NoOpMetricsCollectionService) Logger(org.slf4j.Logger) LocationFactory(org.apache.twill.filesystem.LocationFactory) Location(org.apache.twill.filesystem.Location) Test(org.junit.Test)

Example 5 with AppenderContext

use of io.cdap.cdap.api.logging.AppenderContext in project cdap by caskdata.

the class RollingLocationLogAppenderTest method testFileClose.

@Test
public void testFileClose() throws Exception {
    // assume SLF4J is bound to logback in the current environment
    AppenderContext appenderContext = new LocalAppenderContext(injector.getInstance(TransactionRunner.class), injector.getInstance(LocationFactory.class), new NoOpMetricsCollectionService());
    JoranConfigurator configurator = new JoranConfigurator();
    configurator.setContext(appenderContext);
    // Call context.reset() to clear any previous configuration, e.g. default
    // configuration. For multi-step configuration, omit calling context.reset().
    appenderContext.reset();
    configurator.doConfigure(getClass().getResourceAsStream("/rolling-appender-logback-test.xml"));
    StatusPrinter.printInCaseOfErrorsOrWarnings(appenderContext);
    RollingLocationLogAppender rollingAppender = (RollingLocationLogAppender) appenderContext.getLogger(RollingLocationLogAppenderTest.class).getAppender("rollingAppender");
    addTagsToMdc("testNs", "testApp");
    Logger logger = appenderContext.getLogger(RollingLocationLogAppenderTest.class);
    ingestLogs(logger, 20);
    // wait for 500 ms so that file is eligible for closing
    Thread.sleep(500);
    // flush to make sure file is closed
    rollingAppender.flush();
    Assert.assertEquals(0, rollingAppender.getLocationManager().getActiveLocations().size());
}
Also used : LocalAppenderContext(io.cdap.cdap.logging.framework.LocalAppenderContext) TransactionRunner(io.cdap.cdap.spi.data.transaction.TransactionRunner) JoranConfigurator(ch.qos.logback.classic.joran.JoranConfigurator) AppenderContext(io.cdap.cdap.api.logging.AppenderContext) LocalAppenderContext(io.cdap.cdap.logging.framework.LocalAppenderContext) NoOpMetricsCollectionService(io.cdap.cdap.common.metrics.NoOpMetricsCollectionService) Logger(org.slf4j.Logger) LocationFactory(org.apache.twill.filesystem.LocationFactory) Test(org.junit.Test)

Aggregations

AppenderContext (io.cdap.cdap.api.logging.AppenderContext)12 LocalAppenderContext (io.cdap.cdap.logging.framework.LocalAppenderContext)7 NoOpMetricsCollectionService (io.cdap.cdap.common.metrics.NoOpMetricsCollectionService)6 TransactionRunner (io.cdap.cdap.spi.data.transaction.TransactionRunner)6 LocationFactory (org.apache.twill.filesystem.LocationFactory)6 Test (org.junit.Test)6 JoranConfigurator (ch.qos.logback.classic.joran.JoranConfigurator)3 LoggingEvent (ch.qos.logback.classic.spi.LoggingEvent)3 LogPipelineLoader (io.cdap.cdap.logging.framework.LogPipelineLoader)3 LogPipelineSpecification (io.cdap.cdap.logging.framework.LogPipelineSpecification)3 FileMetaDataReader (io.cdap.cdap.logging.meta.FileMetaDataReader)3 LogProcessorPipelineContext (io.cdap.cdap.logging.pipeline.LogProcessorPipelineContext)3 LogLocation (io.cdap.cdap.logging.write.LogLocation)3 IOException (java.io.IOException)3 ArrayList (java.util.ArrayList)3 HashMap (java.util.HashMap)3 Location (org.apache.twill.filesystem.Location)3 Logger (org.slf4j.Logger)3 CConfiguration (io.cdap.cdap.common.conf.CConfiguration)2 RetryOnStartFailureService (io.cdap.cdap.common.service.RetryOnStartFailureService)2