Search in sources :

Example 6 with JoranException

use of ch.qos.logback.core.joran.spi.JoranException in project cdap by caskdata.

the class LogPipelineLoader method load.

/**
   * Creates the {@link LogPipelineSpecification} representing the given log pipeline configuration URL.
   */
private <T extends LoggerContext> LogPipelineSpecification<T> load(Provider<T> contextProvider, URL configURL) throws JoranException {
    // Create one AppenderContext per config file
    T context = contextProvider.get();
    CConfiguration pipelineCConf = CConfiguration.copy(cConf);
    LogPipelineConfigurator configurator = new LogPipelineConfigurator(pipelineCConf);
    configurator.setContext(context);
    configurator.doConfigure(configURL);
    // Check if the configuration has any error in it.
    if (!new StatusChecker(context).isErrorFree(Status.ERROR)) {
        List<Status> errors = new ArrayList<>();
        for (Status status : context.getStatusManager().getCopyOfStatusList()) {
            if (status.getEffectiveLevel() == Status.ERROR) {
                errors.add(status);
            }
        }
        throw new JoranException("Configuration failed " + errors);
    }
    // Default the pipeline name to the config file name (without extension) if it is not set
    if (context.getName() == null) {
        String path = configURL.getPath();
        int idx = path.lastIndexOf("/");
        int dotIdx = path.lastIndexOf('.');
        int startIdx = idx < 0 ? 0 : idx + 1;
        int endIdx = dotIdx > idx ? dotIdx : path.length();
        context.setName(path.substring(startIdx, endIdx));
    }
    byte[] checkpointPrefix = Bytes.toBytes(context.getName());
    String prefixNum = configurator.getExecutionContext().getProperty(Constants.Logging.PIPELINE_CHECKPOINT_PREFIX_NUM);
    if (prefixNum != null) {
        try {
            checkpointPrefix = Bytes.toBytes(Integer.parseInt(prefixNum));
        } catch (NumberFormatException e) {
            LOG.warn("Ignoring invalid {} setting for pipeline in {}", Constants.Logging.PIPELINE_CHECKPOINT_PREFIX_NUM, configURL);
        }
    }
    return new LogPipelineSpecification<>(configURL, context, setupPipelineCConf(configurator, pipelineCConf), checkpointPrefix);
}
Also used : Status(ch.qos.logback.core.status.Status) ArrayList(java.util.ArrayList) CConfiguration(co.cask.cdap.common.conf.CConfiguration) StatusChecker(ch.qos.logback.core.status.StatusChecker) JoranException(ch.qos.logback.core.joran.spi.JoranException) LogPipelineConfigurator(co.cask.cdap.logging.pipeline.LogPipelineConfigurator)

Example 7 with JoranException

use of ch.qos.logback.core.joran.spi.JoranException in project waltz by khartec.

the class LoggingUtilities method configureLogging.

public static void configureLogging() {
    LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
    try {
        JoranConfigurator configurator = new JoranConfigurator();
        context.reset();
        configurator.setContext(context);
        System.out.println("Attempting to load logback configuration file: " + LOG_CONFIG_FILE_NAME + " from classpath or " + System.getProperty("user.home") + "/.waltz/");
        Resource logbackConfigFile = IOUtilities.getFileResource(LOG_CONFIG_FILE_NAME);
        if (logbackConfigFile.exists()) {
            System.out.println("Found logback configuration file at: " + logbackConfigFile.getFile().getAbsolutePath());
            configurator.doConfigure(logbackConfigFile.getFile());
        } else {
            System.out.println("Logback configuration file not found..");
        }
    } catch (IOException | JoranException e) {
    // StatusPrinter will handle this
    }
    StatusPrinter.printInCaseOfErrorsOrWarnings(context);
}
Also used : JoranException(ch.qos.logback.core.joran.spi.JoranException) JoranConfigurator(ch.qos.logback.classic.joran.JoranConfigurator) Resource(org.springframework.core.io.Resource) IOException(java.io.IOException) LoggerContext(ch.qos.logback.classic.LoggerContext)

Example 8 with JoranException

use of ch.qos.logback.core.joran.spi.JoranException in project sulky by huxi.

the class LoggingTestBase method configureLoggingFromString.

@SuppressWarnings({ "PMD.AvoidPrintStackTrace" })
private static void configureLoggingFromString(String loggingConfig, boolean verbose) {
    ILoggerFactory loggerFactory = LoggerFactory.getILoggerFactory();
    if (loggerFactory instanceof LoggerContext) {
        LoggerContext loggerContext = (LoggerContext) loggerFactory;
        // reset previous configuration initially loaded from logback.xml
        if (verbose) {
            System.out.println("\nAbout to reset logging system.");
        }
        loggerContext.reset();
        byte[] stringBytes = loggingConfig.getBytes(StandardCharsets.UTF_8);
        InputStream is = new ByteArrayInputStream(stringBytes);
        JoranConfigurator configurator = new JoranConfigurator();
        configurator.setContext(loggerContext);
        try {
            configurator.doConfigure(is);
            if (verbose) {
                System.out.println("\nPrinting status of logging system:");
                StatusPrinter.print(loggerContext);
            }
        } catch (JoranException ex) {
            System.err.println("!!! Error configuring logging framework with '" + loggingConfig + "'!");
            // this is not a bug! - Avoid Print Stack Trace : Avoid printStackTrace(); use a logger call instead.
            ex.printStackTrace();
            StatusPrinter.print(loggerContext);
        }
    }
}
Also used : ILoggerFactory(org.slf4j.ILoggerFactory) ByteArrayInputStream(java.io.ByteArrayInputStream) JoranException(ch.qos.logback.core.joran.spi.JoranException) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) JoranConfigurator(ch.qos.logback.classic.joran.JoranConfigurator) LoggerContext(ch.qos.logback.classic.LoggerContext)

Example 9 with JoranException

use of ch.qos.logback.core.joran.spi.JoranException in project cdap by caskdata.

the class LogPipelineLoader method doLoad.

/**
   * Loads the log pipeline configurations
   *
   * @param contextProvider a guice {@link Provider} for creating new instance of {@link LoggerContext}.
   * @param ignoreOnError {@code true} to ignore pipeline configuration that has error.
   * @param <T> Type of the {@link LoggerContext}
   * @return a map from pipeline name to the {@link LogPipelineSpecification}
   * @throws InvalidPipelineException if any of the pipeline configuration is invalid.
   */
private <T extends LoggerContext> Map<String, LogPipelineSpecification<T>> doLoad(Provider<T> contextProvider, boolean ignoreOnError) throws InvalidPipelineException {
    Map<String, LogPipelineSpecification<T>> result = new HashMap<>();
    Set<byte[]> checkpointPrefixes = new TreeSet<>(Bytes.BYTES_COMPARATOR);
    checkpointPrefixes.addAll(RESERVED_CHECKPOINT_PREFIX);
    for (URL configURL : getPipelineConfigURLs()) {
        try {
            LogPipelineSpecification<T> spec = load(contextProvider, configURL);
            LogPipelineSpecification<T> existingSpec = result.get(spec.getName());
            if (existingSpec != null) {
                if (!ignoreOnError) {
                    throw new InvalidPipelineException("Duplicate pipeline with name " + spec.getName() + " at " + configURL + ". It was already defined at " + existingSpec.getSource());
                }
                LOG.warn("Pipeline {} already defined in {}. Ignoring the duplicated one from {}.", spec.getName(), existingSpec.getSource(), configURL);
                continue;
            }
            if (!checkpointPrefixes.add(spec.getCheckpointPrefix())) {
                if (!ignoreOnError) {
                    // Checkpoint prefix can't be the same, otherwise pipeline checkpoints will be overwriting each other.
                    throw new InvalidPipelineException("Checkpoint prefix " + Bytes.toStringBinary(spec.getCheckpointPrefix()) + " already exists. " + "Please either remove the property " + Constants.Logging.PIPELINE_CHECKPOINT_PREFIX_NUM + " or use a different value.");
                }
                LOG.warn("Pipeline {} has checkpoint prefix {} already defined by other pipeline. Ignoring one from {}.", spec.getName(), Bytes.toStringBinary(spec.getCheckpointPrefix()), spec.getSource());
                continue;
            }
            if (SYSTEM_LOG_PIPELINE_NAME.equals(spec.getName())) {
                // Make sure the byte prefix is correct
                if (!Arrays.equals(spec.getCheckpointPrefix(), Constants.Logging.SYSTEM_PIPELINE_CHECKPOINT_PREFIX)) {
                    // This error cannot be ignored
                    throw new InvalidPipelineException("System pipeline '" + SYSTEM_LOG_PIPELINE_NAME + "' should have checkpoint prefix set to " + Bytes.toStringBinary(Constants.Logging.SYSTEM_PIPELINE_CHECKPOINT_PREFIX));
                }
            }
            result.put(spec.getName(), spec);
        } catch (JoranException e) {
            if (!ignoreOnError) {
                throw new InvalidPipelineException("Failed to process log processing pipeline config at " + configURL, e);
            }
            LOG.warn("Ignoring invalid log processing pipeline configuration in {} due to\n  {}", configURL, e.getMessage());
        }
    }
    Preconditions.checkState(result.containsKey(SYSTEM_LOG_PIPELINE_NAME), "The CDAP system log processing pipeline is missing. " + "Please check and fix any configuration error shown earlier in the log.");
    return result;
}
Also used : HashMap(java.util.HashMap) JoranException(ch.qos.logback.core.joran.spi.JoranException) TreeSet(java.util.TreeSet) URL(java.net.URL)

Example 10 with JoranException

use of ch.qos.logback.core.joran.spi.JoranException in project camel by apache.

the class ITestApplication method overrideLoggingConfig.

private static void overrideLoggingConfig() {
    URL logbackFile = ITestApplication.class.getResource("/spring-logback.xml");
    if (logbackFile != null) {
        LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
        try {
            JoranConfigurator configurator = new JoranConfigurator();
            configurator.setContext(context);
            // Call context.reset() to clear any previous configuration, e.g. default
            // configuration. For multi-step configuration, omit calling context.reset().
            context.reset();
            configurator.doConfigure(logbackFile);
        } catch (JoranException je) {
        // StatusPrinter will handle this
        }
        StatusPrinter.printInCaseOfErrorsOrWarnings(context);
    }
}
Also used : JoranException(ch.qos.logback.core.joran.spi.JoranException) JoranConfigurator(ch.qos.logback.classic.joran.JoranConfigurator) LoggerContext(ch.qos.logback.classic.LoggerContext) URL(java.net.URL)

Aggregations

JoranException (ch.qos.logback.core.joran.spi.JoranException)18 JoranConfigurator (ch.qos.logback.classic.joran.JoranConfigurator)15 LoggerContext (ch.qos.logback.classic.LoggerContext)12 InputStream (java.io.InputStream)5 URL (java.net.URL)5 File (java.io.File)4 ByteArrayInputStream (java.io.ByteArrayInputStream)3 ILoggerFactory (org.slf4j.ILoggerFactory)3 IOException (java.io.IOException)2 ArrayList (java.util.ArrayList)2 BasicConfigurator (ch.qos.logback.classic.BasicConfigurator)1 Logger (ch.qos.logback.classic.Logger)1 ContextInitializer (ch.qos.logback.classic.util.ContextInitializer)1 SaxEvent (ch.qos.logback.core.joran.event.SaxEvent)1 SaxEventRecorder (ch.qos.logback.core.joran.event.SaxEventRecorder)1 Status (ch.qos.logback.core.status.Status)1 StatusChecker (ch.qos.logback.core.status.StatusChecker)1 CConfiguration (co.cask.cdap.common.conf.CConfiguration)1 LogPipelineConfigurator (co.cask.cdap.logging.pipeline.LogPipelineConfigurator)1 OperationResult (com.evolveum.midpoint.schema.result.OperationResult)1