Search in sources :

Example 16 with JoranConfigurator

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

the class LogbackConfigurationTests method filePatternCanBeOverridden.

@Test
public void filePatternCanBeOverridden() throws JoranException {
    JoranConfigurator configurator = new JoranConfigurator();
    LoggerContext context = new LoggerContext();
    configurator.setContext(context);
    configurator.doConfigure(new File("src/test/resources/custom-file-log-pattern.xml"));
    Appender<ILoggingEvent> appender = context.getLogger("ROOT").getAppender("FILE");
    assertThat(appender).isInstanceOf(FileAppender.class);
    Encoder<?> encoder = ((FileAppender<?>) appender).getEncoder();
    assertThat(encoder).isInstanceOf(PatternLayoutEncoder.class);
    assertThat(((PatternLayoutEncoder) encoder).getPattern()).isEqualTo("bar");
}
Also used : FileAppender(ch.qos.logback.core.FileAppender) PatternLayoutEncoder(ch.qos.logback.classic.encoder.PatternLayoutEncoder) JoranConfigurator(ch.qos.logback.classic.joran.JoranConfigurator) ILoggingEvent(ch.qos.logback.classic.spi.ILoggingEvent) LoggerContext(ch.qos.logback.classic.LoggerContext) File(java.io.File) Test(org.junit.Test)

Example 17 with JoranConfigurator

use of ch.qos.logback.classic.joran.JoranConfigurator in project sakuli by ConSol.

the class LoggerInitializer method initLoggerContext.

@PostConstruct
public void initLoggerContext() {
    // properties of the LoggerContext
    List<ImmutablePair<String, String>> properties = Arrays.asList(new ImmutablePair<>(SakuliProperties.LOG_FOLDER, sakuliProperties.getLogFolder().toAbsolutePath().toString()), new ImmutablePair<>(SakuliProperties.LOG_PATTERN, sakuliProperties.getLogPattern()), new ImmutablePair<>(SakuliProperties.LOG_LEVEL_SAKULI, sakuliProperties.getLogLevelSakuli()), new ImmutablePair<>(SakuliProperties.LOG_LEVEL_SAHI, sakuliProperties.getLogLevelSahi()), new ImmutablePair<>(SakuliProperties.LOG_LEVEL_SIKULI, sakuliProperties.getLogLevelSikuli()), new ImmutablePair<>(SakuliProperties.LOG_LEVEL_SPRING, sakuliProperties.getLogLevelSpring()), new ImmutablePair<>(SakuliProperties.LOG_LEVEL_ROOT, sakuliProperties.getLogLevelRoot()));
    //log new properties before configuring
    properties.stream().filter(p -> isNotEmpty(p.getValue())).forEach(p -> logger.info("set '{}' to '{}'", p.getKey(), p.getValue()));
    //start sysout forwarding to slf4j
    SysOutOverSLF4J.sendSystemOutAndErrToSLF4J(LogLevel.INFO, LogLevel.ERROR);
    LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
    JoranConfigurator jc = new JoranConfigurator();
    jc.setContext(context);
    // overwrite default configuration
    context.reset();
    //put properties into the context
    properties.stream().filter(p -> isNotEmpty(p.getValue())).forEach(p -> context.putProperty(p.getKey(), p.getValue()));
    //determine the config file
    String configFilePath = getConfigFileFromClasspath();
    if (configFilePath == null) {
        configFilePath = getConfigFile();
    }
    if (configFilePath == null) {
        throw new LogConfigurationException("Log configuration file '" + LOG_CONFIG_FILE_NAME + "' not found! Please ensure that your config folder or your classpath contains the file.");
    }
    try {
        jc.doConfigure(configFilePath);
    } catch (JoranException e) {
        throw new LogConfigurationException("unable to run the LoggerIntializer, pleae check your config!", e);
    }
    logger.info("set logback configuration file '{}'", configFilePath);
    // Jersey uses java.util.logging - bridge to slf4
    SLF4JBridgeHandler.removeHandlersForRootLogger();
    SLF4JBridgeHandler.install();
}
Also used : NoSuchFileException(java.nio.file.NoSuchFileException) Arrays(java.util.Arrays) JoranConfigurator(ch.qos.logback.classic.joran.JoranConfigurator) Logger(org.slf4j.Logger) Files(java.nio.file.Files) LoggerFactory(org.slf4j.LoggerFactory) StringUtils.isNotEmpty(org.apache.commons.lang.StringUtils.isNotEmpty) Autowired(org.springframework.beans.factory.annotation.Autowired) SakuliProperties(org.sakuli.datamodel.properties.SakuliProperties) LoggerContext(ch.qos.logback.classic.LoggerContext) LogLevel(uk.org.lidalia.sysoutslf4j.context.LogLevel) ImmutablePair(org.apache.commons.lang3.tuple.ImmutablePair) SLF4JBridgeHandler(org.slf4j.bridge.SLF4JBridgeHandler) File(java.io.File) Component(org.springframework.stereotype.Component) List(java.util.List) Paths(java.nio.file.Paths) SysOutOverSLF4J(uk.org.lidalia.sysoutslf4j.context.SysOutOverSLF4J) JoranException(ch.qos.logback.core.joran.spi.JoranException) PostConstruct(javax.annotation.PostConstruct) LogConfigurationException(org.apache.commons.logging.LogConfigurationException) Path(java.nio.file.Path) ImmutablePair(org.apache.commons.lang3.tuple.ImmutablePair) JoranException(ch.qos.logback.core.joran.spi.JoranException) JoranConfigurator(ch.qos.logback.classic.joran.JoranConfigurator) LogConfigurationException(org.apache.commons.logging.LogConfigurationException) LoggerContext(ch.qos.logback.classic.LoggerContext) PostConstruct(javax.annotation.PostConstruct)

Example 18 with JoranConfigurator

use of ch.qos.logback.classic.joran.JoranConfigurator in project midpoint by Evolveum.

the class LoggingConfigurationManager method configure.

public static void configure(LoggingConfigurationType config, String version, OperationResult result) throws SchemaException {
    OperationResult res = result.createSubresult(LoggingConfigurationManager.class.getName() + ".configure");
    if (InternalsConfig.avoidLoggingChange) {
        LOGGER.info("IGNORING change of logging configuration (current config version: {}, new version {}) because avoidLoggingChange=true", currentlyUsedVersion, version);
        res.recordNotApplicableIfUnknown();
        return;
    }
    if (currentlyUsedVersion != null) {
        LOGGER.info("Applying logging configuration (currently applied version: {}, new version: {})", currentlyUsedVersion, version);
    } else {
        LOGGER.info("Applying logging configuration (version {})", version);
    }
    currentlyUsedVersion = version;
    // JUL Bridge initialization was here. (SLF4JBridgeHandler)
    // But it was moved to a later phase as suggested by http://jira.qos.ch/browse/LOGBACK-740
    // Initialize JUL bridge
    SLF4JBridgeHandler.removeHandlersForRootLogger();
    SLF4JBridgeHandler.install();
    //Get current log configuration
    LoggerContext lc = (LoggerContext) TraceManager.getILoggerFactory();
    //Prepare configurator in current context
    JoranConfigurator configurator = new JoranConfigurator();
    configurator.setContext(lc);
    //Generate configuration file as string
    String configXml = prepareConfiguration(config);
    if (LOGGER.isTraceEnabled()) {
        LOGGER.trace("New logging configuration:");
        LOGGER.trace(configXml);
    }
    InputStream cis = new ByteArrayInputStream(configXml.getBytes());
    LOGGER.info("Resetting current logging configuration");
    lc.getStatusManager().clear();
    //Set all loggers to error
    for (Logger l : lc.getLoggerList()) {
        LOGGER.trace("Disable logger: {}", l);
        l.setLevel(Level.ERROR);
    }
    // Reset configuration
    lc.reset();
    //Switch to new logging configuration
    lc.setName("MidPoint");
    try {
        configurator.doConfigure(cis);
        LOGGER.info("New logging configuration applied");
    } catch (JoranException e) {
        System.out.println("Error during applying logging configuration: " + e.getMessage());
        LOGGER.error("Error during applying logging configuration: " + e.getMessage(), e);
        result.createSubresult("Applying logging configuration.").recordFatalError(e.getMessage(), e);
    } catch (NumberFormatException e) {
        System.out.println("Error during applying logging configuration: " + e.getMessage());
        LOGGER.error("Error during applying logging configuration: " + e.getMessage(), e);
        result.createSubresult("Applying logging configuration.").recordFatalError(e.getMessage(), e);
    }
    //Get messages if error occurred;
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    StatusPrinter.setPrintStream(new PrintStream(baos));
    StatusPrinter.print(lc);
    String internalLog = null;
    try {
        internalLog = baos.toString("UTF8");
    } catch (UnsupportedEncodingException e) {
        // should never happen
        LOGGER.error("Woops?", e);
    }
    if (!StringUtils.isEmpty(internalLog)) {
        //Parse internal log
        res.recordSuccess();
        String[] internalLogLines = internalLog.split("\n");
        for (int i = 0; i < internalLogLines.length; i++) {
            if (internalLogLines[i].contains("|-ERROR"))
                res.recordPartialError(internalLogLines[i]);
            res.appendDetail(internalLogLines[i]);
        }
        LOGGER.trace("LogBack internal log:\n{}", internalLog);
    } else {
        res.recordSuccess();
    }
    // Initialize JUL bridge
    SLF4JBridgeHandler.removeHandlersForRootLogger();
    SLF4JBridgeHandler.install();
    return;
}
Also used : PrintStream(java.io.PrintStream) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) UnsupportedEncodingException(java.io.UnsupportedEncodingException) OperationResult(com.evolveum.midpoint.schema.result.OperationResult) ByteArrayOutputStream(java.io.ByteArrayOutputStream) Logger(ch.qos.logback.classic.Logger) LoggerContext(ch.qos.logback.classic.LoggerContext) ByteArrayInputStream(java.io.ByteArrayInputStream) JoranException(ch.qos.logback.core.joran.spi.JoranException) JoranConfigurator(ch.qos.logback.classic.joran.JoranConfigurator)

Example 19 with JoranConfigurator

use of ch.qos.logback.classic.joran.JoranConfigurator in project logging-log4j2 by apache.

the class LoggerContextRule method apply.

@Override
public Statement apply(final Statement base, final Description description) {
    testClassName = description.getClassName();
    return new Statement() {

        @Override
        public void evaluate() throws Throwable {
            context = (LoggerContext) LoggerFactory.getILoggerFactory();
            final GenericConfigurator configurator = new JoranConfigurator();
            configurator.setContext(context);
            configurator.doConfigure(configLocation);
            base.evaluate();
        }
    };
}
Also used : Statement(org.junit.runners.model.Statement) JoranConfigurator(ch.qos.logback.classic.joran.JoranConfigurator) GenericConfigurator(ch.qos.logback.core.joran.GenericConfigurator)

Example 20 with JoranConfigurator

use of ch.qos.logback.classic.joran.JoranConfigurator in project GeoGig by boundlessgeo.

the class Logging method tryConfigureLogging.

static void tryConfigureLogging(Platform platform) {
    // instantiate and call ResolveGeogigDir directly to avoid calling getGeogig() and hence get
    // some logging events before having configured logging
    final Optional<URL> geogigDirUrl = new ResolveGeogigDir(platform).call();
    if (!geogigDirUrl.isPresent() || !"file".equalsIgnoreCase(geogigDirUrl.get().getProtocol())) {
        // redirect java.util.logging to SLF4J anyways
        SLF4JBridgeHandler.removeHandlersForRootLogger();
        SLF4JBridgeHandler.install();
        return;
    }
    final File geogigDir;
    try {
        geogigDir = new File(geogigDirUrl.get().toURI());
    } catch (URISyntaxException e) {
        throw Throwables.propagate(e);
    }
    if (geogigDir.equals(geogigDirLoggingConfiguration)) {
        return;
    }
    if (!geogigDir.exists() || !geogigDir.isDirectory()) {
        return;
    }
    final URL loggingFile = getOrCreateLoggingConfigFile(geogigDir);
    if (loggingFile == null) {
        return;
    }
    try {
        LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();
        loggerContext.reset();
        /*
             * Set the geogigdir variable for the config file can resolve the default location
             * ${geogigdir}/log/geogig.log
             */
        loggerContext.putProperty("geogigdir", geogigDir.getAbsolutePath());
        JoranConfigurator configurator = new JoranConfigurator();
        configurator.setContext(loggerContext);
        configurator.doConfigure(loggingFile);
        // redirect java.util.logging to SLF4J
        SLF4JBridgeHandler.removeHandlersForRootLogger();
        SLF4JBridgeHandler.install();
        geogigDirLoggingConfiguration = geogigDir;
    } catch (JoranException e) {
        LOGGER.error("Error configuring logging from file {}. '{}'", loggingFile, e.getMessage(), e);
    }
}
Also used : JoranException(ch.qos.logback.core.joran.spi.JoranException) JoranConfigurator(ch.qos.logback.classic.joran.JoranConfigurator) URISyntaxException(java.net.URISyntaxException) ResolveGeogigDir(org.locationtech.geogig.api.plumbing.ResolveGeogigDir) File(java.io.File) LoggerContext(ch.qos.logback.classic.LoggerContext) URL(java.net.URL)

Aggregations

JoranConfigurator (ch.qos.logback.classic.joran.JoranConfigurator)24 LoggerContext (ch.qos.logback.classic.LoggerContext)15 JoranException (ch.qos.logback.core.joran.spi.JoranException)12 File (java.io.File)7 Test (org.junit.Test)6 InputStream (java.io.InputStream)4 Logger (org.slf4j.Logger)4 AppenderContext (co.cask.cdap.api.logging.AppenderContext)3 NoOpMetricsCollectionService (co.cask.cdap.common.metrics.NoOpMetricsCollectionService)3 DatasetFramework (co.cask.cdap.data2.dataset2.DatasetFramework)3 LocalAppenderContext (co.cask.cdap.logging.framework.LocalAppenderContext)3 StringReader (java.io.StringReader)3 URL (java.net.URL)3 InputSource (org.xml.sax.InputSource)3 PatternLayoutEncoder (ch.qos.logback.classic.encoder.PatternLayoutEncoder)2 ILoggingEvent (ch.qos.logback.classic.spi.ILoggingEvent)2 ContextInitializer (ch.qos.logback.classic.util.ContextInitializer)2 ByteArrayInputStream (java.io.ByteArrayInputStream)2 StringWriter (java.io.StringWriter)2 Transformer (javax.xml.transform.Transformer)2