Search in sources :

Example 31 with FileAppender

use of ch.qos.logback.core.FileAppender in project engineblock by engineblock.

the class ScenarioLogger method start.

public ScenarioLogger start() {
    if (!loggerDir.exists()) {
        if (!loggerDir.mkdirs()) {
            throw new RuntimeException("Unable to create logger directory:" + loggerDir.getPath());
        }
    }
    LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();
    // List<LoggerContextListener> copyOfListenerList = loggerContext.getCopyOfListenerList();
    ConsoleAppender<ILoggingEvent> ca = new ConsoleAppender<>();
    ca.setContext(loggerContext);
    PatternLayoutEncoder ple = new PatternLayoutEncoder();
    // ple.setPattern("%date %level [%thread] %logger{10} [%file:%line] %msg%n");
    ple.setPattern("%date %level [%thread] %logger{10} [%file:%line] %msg%n");
    ple.setContext(loggerContext);
    ple.start();
    String scenarioLog = loggerDir.getPath() + File.separator + scenario.getName() + ".log";
    scenarioLog = scenarioLog.replaceAll("\\s", "_");
    FileAppender<ILoggingEvent> fileAppender = new FileAppender<ILoggingEvent>();
    fileAppender.setFile(scenarioLog);
    fileAppender.setEncoder(ple);
    fileAppender.setContext(loggerContext);
    System.err.println("Logging to " + scenarioLog);
    fileAppender.start();
    Logger logger = (Logger) LoggerFactory.getLogger("ROOT");
    logger.addAppender(fileAppender);
    logger.setLevel(Level.INFO);
    logger.setAdditive(true);
    /* set to true if root should log too */
    purgeOldFiles(logger);
    return this;
}
Also used : ConsoleAppender(ch.qos.logback.core.ConsoleAppender) PatternLayoutEncoder(ch.qos.logback.classic.encoder.PatternLayoutEncoder) FileAppender(ch.qos.logback.core.FileAppender) ILoggingEvent(ch.qos.logback.classic.spi.ILoggingEvent) Logger(ch.qos.logback.classic.Logger) LoggerContext(ch.qos.logback.classic.LoggerContext)

Example 32 with FileAppender

use of ch.qos.logback.core.FileAppender in project jlineup by otto-de.

the class Util method logToFile.

static void logToFile(String workingDir) {
    LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
    PatternLayoutEncoder ple = new PatternLayoutEncoder();
    ple.setPattern("%date %level [%thread] %logger{10} [%file:%line] %msg%n");
    ple.setContext(lc);
    ple.start();
    FileAppender<ILoggingEvent> fileAppender = new FileAppender<>();
    fileAppender.setFile(workingDir + "/jlineup.log");
    fileAppender.setEncoder(ple);
    fileAppender.setContext(lc);
    fileAppender.start();
    ch.qos.logback.classic.Logger logger = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger(ch.qos.logback.classic.Logger.ROOT_LOGGER_NAME);
    logger.addAppender(fileAppender);
    logger.setLevel(Level.DEBUG);
}
Also used : PatternLayoutEncoder(ch.qos.logback.classic.encoder.PatternLayoutEncoder) FileAppender(ch.qos.logback.core.FileAppender) ILoggingEvent(ch.qos.logback.classic.spi.ILoggingEvent) Logger(org.slf4j.Logger) LoggerContext(ch.qos.logback.classic.LoggerContext)

Example 33 with FileAppender

use of ch.qos.logback.core.FileAppender in project pravega by pravega.

the class SelfTestRunner method setupLogging.

private static void setupLogging(TestConfig testConfig) {
    val logFile = new java.io.File(testConfig.getTestLogPath());
    if (logFile.delete()) {
        TestLogger.log("Main", "Deleted log file %s.", logFile.getAbsolutePath());
    }
    // Configure slf4j to not log anything (console or whatever). This interferes with the console interaction.
    LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
    context.getLoggerList().get(0).detachAndStopAllAppenders();
    val fa = new FileAppender<ILoggingEvent>();
    fa.setContext(context);
    fa.setName("selftest");
    fa.setFile(logFile.getAbsolutePath());
    val encoder = new PatternLayoutEncoder();
    encoder.setContext(context);
    encoder.setPattern("%date{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %level - %msg%n");
    encoder.start();
    fa.setEncoder(encoder);
    fa.start();
    context.getLoggerList().get(0).addAppender(fa);
    context.getLoggerList().get(0).setLevel(Level.INFO);
// context.reset();
}
Also used : lombok.val(lombok.val) FileAppender(ch.qos.logback.core.FileAppender) PatternLayoutEncoder(ch.qos.logback.classic.encoder.PatternLayoutEncoder) File(java.io.File) LoggerContext(ch.qos.logback.classic.LoggerContext)

Example 34 with FileAppender

use of ch.qos.logback.core.FileAppender in project pom-manipulation-ext by release-engineering.

the class Cli method run.

public int run(String[] args) {
    Options options = new Options();
    options.addOption("h", false, "Print this help message.");
    options.addOption(Option.builder("d").longOpt("debug").desc("Enable debug").build());
    options.addOption(Option.builder("t").longOpt("trace").desc("Enable trace").build());
    options.addOption(Option.builder("h").longOpt("help").desc("Print help").build());
    options.addOption(Option.builder("f").longOpt("file").hasArgs().numberOfArgs(1).desc("POM file").build());
    options.addOption(Option.builder().longOpt("log-context").desc("Add log-context ID").numberOfArgs(1).build());
    options.addOption(Option.builder("l").longOpt("log").desc("Log file to output logging to").numberOfArgs(1).build());
    options.addOption(Option.builder("s").longOpt("settings").hasArgs().numberOfArgs(1).desc("Optional settings.xml file").build());
    options.addOption(Option.builder("P").longOpt("activeProfiles").desc("Comma separated list of active profiles.").numberOfArgs(1).build());
    options.addOption(Option.builder("o").longOpt("outputFile").desc("outputFile to output dependencies to. Only used with '-p' (Print all project dependencies)").numberOfArgs(1).build());
    options.addOption(Option.builder("p").longOpt("printDeps").desc("Print all project dependencies").build());
    options.addOption(Option.builder().longOpt("printGAVTC").desc("Print all project dependencies in group:artifact:version:type:classifier with scope information").build());
    options.addOption(Option.builder("D").hasArgs().numberOfArgs(2).valueSeparator('=').desc("Java Properties").build());
    options.addOption(Option.builder("x").hasArgs().numberOfArgs(2).desc("XPath tester ( file : xpath )").build());
    CommandLineParser parser = new DefaultParser();
    CommandLine cmd;
    try {
        cmd = parser.parse(options, args);
    } catch (ParseException e) {
        logger.debug("Caught problem parsing ", e);
        System.err.println(e.getMessage());
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("...", options);
        return 10;
    }
    if (cmd.hasOption('h')) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("...", options);
        System.exit(0);
    }
    if (cmd.hasOption('D')) {
        userProps = cmd.getOptionProperties("D");
    }
    if (cmd.hasOption('f')) {
        target = new File(cmd.getOptionValue('f'));
    }
    if (cmd.hasOption('s')) {
        settings = new File(cmd.getOptionValue('s'));
    }
    if (cmd.hasOption("log-context")) {
        String mdc = cmd.getOptionValue("log-context");
        if (isNotEmpty(mdc)) {
            // Append a space to split up level and log-context markers.
            MDC.put("LOG-CONTEXT", mdc + ' ');
        }
    }
    createSession(target, settings);
    final ch.qos.logback.classic.Logger root = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger(org.slf4j.Logger.ROOT_LOGGER_NAME);
    if (cmd.hasOption('l')) {
        LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();
        loggerContext.reset();
        PatternLayoutEncoder ple = new PatternLayoutEncoder();
        ple.setPattern("%mdc{LOG-CONTEXT}%level %logger{36} %msg%n");
        ple.setContext(loggerContext);
        ple.start();
        FileAppender<ILoggingEvent> fileAppender = new FileAppender<>();
        fileAppender.setEncoder(ple);
        fileAppender.setContext(loggerContext);
        fileAppender.setName("fileLogging");
        fileAppender.setAppend(false);
        fileAppender.setFile(cmd.getOptionValue("l"));
        fileAppender.start();
        root.addAppender(fileAppender);
        root.setLevel(Level.INFO);
    }
    // creation stuff.
    if (cmd.hasOption('d')) {
        root.setLevel(Level.DEBUG);
    }
    if (cmd.hasOption('t')) {
        root.setLevel(Level.TRACE);
    }
    if (!session.isEnabled()) {
        logger.info("Manipulation engine disabled via command-line option");
        return 0;
    }
    if (!target.exists()) {
        logger.info("Manipulation engine disabled. Project {} cannot be found.", target);
        return 10;
    } else // Don't bother skipping if we're just trying to analyse deps.
    if (new File(target.getParentFile(), ManipulationManager.MARKER_FILE).exists() && !cmd.hasOption('p')) {
        logger.info("Skipping manipulation as previous execution found.");
        return 0;
    }
    try {
        Properties config = new ConfigIO().parse(target.getParentFile());
        String value = session.getUserProperties().getProperty("allowConfigFilePrecedence");
        if (isNotEmpty(value) && "true".equalsIgnoreCase(value)) {
            session.getUserProperties().putAll(config);
        } else {
            for (String key : config.stringPropertyNames()) {
                if (!session.getUserProperties().containsKey(key)) {
                    session.getUserProperties().setProperty(key, config.getProperty(key));
                }
            }
        }
    } catch (ManipulationException e) {
        logger.error("POM Manipulation failed: Unable to read config file ", e);
        return 10;
    }
    try {
        // Note : don't print out settings information earlier (like when we actually read it) as the logging
        // isn't setup then.
        logger.debug("Using local repository \n{} and found global settings file in {} with contents \n{} and user settings file in {} with contents \n{}", session.getLocalRepository(), DEFAULT_GLOBAL_SETTINGS_FILE, DEFAULT_GLOBAL_SETTINGS_FILE.exists() ? FileUtils.readFileToString(DEFAULT_GLOBAL_SETTINGS_FILE) : "** File does not exist **", settings, (settings != null && settings.exists()) ? FileUtils.readFileToString(settings) : "** File does not exist **");
        manipulationManager.init(session);
        Set<String> activeProfiles = null;
        if (cmd.hasOption('P')) {
            activeProfiles = new HashSet<>();
            Collections.addAll(activeProfiles, cmd.getOptionValue('P').trim().split(","));
            session.getUserProperties().setProperty(PROFILE_SCANNING, "true");
            session.getActiveProfiles().addAll(activeProfiles);
        }
        if (cmd.hasOption('x')) {
            String[] params = cmd.getOptionValues('x');
            if (params.length != 2) {
                throw new ManipulationException("Invalid number of parameters (" + params.length + "); should be <file> <xpath>");
            }
            XMLIO xmlIO = new XMLIO();
            Document doc = xmlIO.parseXML(new File(params[0]));
            XPath xPath = XPathFactory.newInstance().newXPath();
            NodeList nodeList = (NodeList) xPath.evaluate(params[1], doc, XPathConstants.NODESET);
            logger.info("Found {} node", nodeList.getLength());
            for (int i = 0; i < nodeList.getLength(); i++) {
                Node node = nodeList.item(i);
                logger.info("Found node {} and value {} ", node.getNodeName(), node.getTextContent());
            }
        } else if (cmd.hasOption('p') || cmd.hasOption("printGAVTC")) {
            Set<ArtifactRef> ts = RESTCollector.establishAllDependencies(session, pomIO.parseProject(session.getPom()), activeProfiles);
            logger.info("Found {} dependencies. {}", ts.size(), ts);
            File output = null;
            if (cmd.hasOption('o')) {
                output = new File(cmd.getOptionValue('o'));
                output.delete();
            }
            for (ArtifactRef a : ts) {
                String scope = null;
                if (a instanceof SimpleScopedArtifactRef) {
                    scope = ((SimpleScopedArtifactRef) a).getScope();
                }
                if (cmd.hasOption('o')) {
                    if (cmd.hasOption("printGAVTC")) {
                        FileUtils.writeStringToFile(output, String.format("%-80s%10s\n", a, scope), true);
                    } else {
                        FileUtils.writeStringToFile(output, a.asProjectVersionRef().toString() + '\n', true);
                    }
                } else {
                    if (cmd.hasOption("printGAVTC")) {
                        System.out.format("%-80s%10s\n", a, scope);
                    } else {
                        System.out.println(a.asProjectVersionRef());
                    }
                }
            }
        } else {
            manipulationManager.scanAndApply(session);
        }
    } catch (ManipulationException e) {
        logger.error("POM Manipulation failed; original error is {}", e.getMessage());
        logger.debug("POM Manipulation error trace is", e);
        return 10;
    } catch (RestException e) {
        logger.error("REST communication with {} failed. {}", userProps.getProperty("restURL"), e.getMessage());
        logger.trace("Exception trace is", e);
        return 100;
    } catch (Exception e) {
        logger.error("POM Manipulation failed.", e);
        return 100;
    }
    return 0;
}
Also used : Options(org.apache.commons.cli.Options) Set(java.util.Set) HashSet(java.util.HashSet) Node(org.w3c.dom.Node) Logger(org.slf4j.Logger) ILoggingEvent(ch.qos.logback.classic.spi.ILoggingEvent) Properties(java.util.Properties) Document(org.w3c.dom.Document) ConfigIO(org.commonjava.maven.ext.io.ConfigIO) SimpleScopedArtifactRef(org.commonjava.maven.ext.common.model.SimpleScopedArtifactRef) ArtifactRef(org.commonjava.maven.atlas.ident.ref.ArtifactRef) HelpFormatter(org.apache.commons.cli.HelpFormatter) CommandLineParser(org.apache.commons.cli.CommandLineParser) DefaultParser(org.apache.commons.cli.DefaultParser) PatternLayoutEncoder(ch.qos.logback.classic.encoder.PatternLayoutEncoder) FileAppender(ch.qos.logback.core.FileAppender) XPath(javax.xml.xpath.XPath) XMLIO(org.commonjava.maven.ext.io.XMLIO) NodeList(org.w3c.dom.NodeList) SimpleScopedArtifactRef(org.commonjava.maven.ext.common.model.SimpleScopedArtifactRef) RestException(org.commonjava.maven.ext.io.rest.exception.RestException) LoggerContext(ch.qos.logback.classic.LoggerContext) PlexusContainerException(org.codehaus.plexus.PlexusContainerException) RestException(org.commonjava.maven.ext.io.rest.exception.RestException) ManipulationException(org.commonjava.maven.ext.common.ManipulationException) ParseException(org.apache.commons.cli.ParseException) SettingsBuildingException(org.apache.maven.settings.building.SettingsBuildingException) ComponentLookupException(org.codehaus.plexus.component.repository.exception.ComponentLookupException) MavenExecutionRequestPopulationException(org.apache.maven.execution.MavenExecutionRequestPopulationException) CommandLine(org.apache.commons.cli.CommandLine) ManipulationException(org.commonjava.maven.ext.common.ManipulationException) ParseException(org.apache.commons.cli.ParseException) File(java.io.File)

Example 35 with FileAppender

use of ch.qos.logback.core.FileAppender in project dropwizard by dropwizard.

the class FileAppenderFactory method buildAppender.

protected FileAppender<E> buildAppender(LoggerContext context) {
    if (archive) {
        final RollingFileAppender<E> appender = new RollingFileAppender<>();
        appender.setContext(context);
        appender.setFile(currentLogFilename);
        appender.setBufferSize(new FileSize(bufferSize.toBytes()));
        if (maxFileSize != null && !requireNonNull(archivedLogFilenamePattern).contains("%d")) {
            final FixedWindowRollingPolicy rollingPolicy = new FixedWindowRollingPolicy();
            rollingPolicy.setContext(context);
            rollingPolicy.setMaxIndex(getArchivedFileCount());
            rollingPolicy.setFileNamePattern(getArchivedLogFilenamePattern());
            rollingPolicy.setParent(appender);
            rollingPolicy.start();
            appender.setRollingPolicy(rollingPolicy);
            final SizeBasedTriggeringPolicy<E> triggeringPolicy = new SizeBasedTriggeringPolicy<>();
            triggeringPolicy.setMaxFileSize(new FileSize(maxFileSize.toBytes()));
            triggeringPolicy.setContext(context);
            triggeringPolicy.start();
            appender.setTriggeringPolicy(triggeringPolicy);
            return appender;
        } else {
            final TimeBasedRollingPolicy<E> rollingPolicy;
            if (maxFileSize == null) {
                rollingPolicy = new TimeBasedRollingPolicy<>();
                final TimeBasedFileNamingAndTriggeringPolicy<E> triggeringPolicy = new DefaultTimeBasedFileNamingAndTriggeringPolicy<>();
                triggeringPolicy.setContext(context);
                triggeringPolicy.setTimeBasedRollingPolicy(rollingPolicy);
                appender.setTriggeringPolicy(triggeringPolicy);
            } else {
                // Creating a size and time policy does not need a separate triggering policy set
                // on the appender because this policy registers the trigger policy
                final SizeAndTimeBasedRollingPolicy<E> sizeAndTimeBasedRollingPolicy = new SizeAndTimeBasedRollingPolicy<>();
                sizeAndTimeBasedRollingPolicy.setMaxFileSize(new FileSize(maxFileSize.toBytes()));
                rollingPolicy = sizeAndTimeBasedRollingPolicy;
            }
            if (totalSizeCap != null) {
                rollingPolicy.setTotalSizeCap(new FileSize(totalSizeCap.toBytes()));
            }
            rollingPolicy.setContext(context);
            rollingPolicy.setFileNamePattern(archivedLogFilenamePattern);
            rollingPolicy.setMaxHistory(archivedFileCount);
            appender.setRollingPolicy(rollingPolicy);
            rollingPolicy.setParent(appender);
            rollingPolicy.start();
            return appender;
        }
    }
    final FileAppender<E> appender = new FileAppender<>();
    appender.setContext(context);
    appender.setFile(currentLogFilename);
    appender.setBufferSize(new FileSize(bufferSize.toBytes()));
    return appender;
}
Also used : FileAppender(ch.qos.logback.core.FileAppender) RollingFileAppender(ch.qos.logback.core.rolling.RollingFileAppender) FixedWindowRollingPolicy(ch.qos.logback.core.rolling.FixedWindowRollingPolicy) DefaultTimeBasedFileNamingAndTriggeringPolicy(ch.qos.logback.core.rolling.DefaultTimeBasedFileNamingAndTriggeringPolicy) RollingFileAppender(ch.qos.logback.core.rolling.RollingFileAppender) SizeAndTimeBasedRollingPolicy(ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy) SizeBasedTriggeringPolicy(ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy) FileSize(ch.qos.logback.core.util.FileSize)

Aggregations

FileAppender (ch.qos.logback.core.FileAppender)46 ILoggingEvent (ch.qos.logback.classic.spi.ILoggingEvent)33 LoggerContext (ch.qos.logback.classic.LoggerContext)27 File (java.io.File)23 PatternLayoutEncoder (ch.qos.logback.classic.encoder.PatternLayoutEncoder)18 Logger (ch.qos.logback.classic.Logger)17 Appender (ch.qos.logback.core.Appender)14 RollingFileAppender (ch.qos.logback.core.rolling.RollingFileAppender)12 Test (org.junit.Test)9 ConsoleAppender (ch.qos.logback.core.ConsoleAppender)6 Path (java.nio.file.Path)6 OutputStreamAppender (ch.qos.logback.core.OutputStreamAppender)5 FileSize (ch.qos.logback.core.util.FileSize)5 Test (org.junit.jupiter.api.Test)5 FixedWindowRollingPolicy (ch.qos.logback.core.rolling.FixedWindowRollingPolicy)4 SizeBasedTriggeringPolicy (ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy)4 IOException (java.io.IOException)4 Field (java.lang.reflect.Field)4 SyslogAppender (ch.qos.logback.classic.net.SyslogAppender)3 SizeAndTimeBasedRollingPolicy (ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy)3