Search in sources :

Example 11 with ConsoleAppender

use of ch.qos.logback.core.ConsoleAppender in project UniversalMediaServer by UniversalMediaServer.

the class LoggingConfig method loadFile.

/**
 * Loads the (optional) Logback configuration file.
 *
 * It loads the file defined in the <code>project.logback</code> property from the current
 * directory and (re-)initializes Logback with this file. If running
 * headless (<code>System.Property("console")</code> set), then the
 * alternative config file defined in <code>project.logback.headless</code> is tried first.
 *
 * If no config file can be found in the CWD, then nothing is loaded and
 * Logback will use the logback.xml file on the classpath as a default. If
 * this doesn't exist then a basic console appender is used as fallback.
 *
 * <strong>Note:</strong> Any error messages generated while parsing the
 * config file are dumped only to <code>stdout</code>.
 */
public static synchronized void loadFile() {
    File file = null;
    if (!setContextAndRoot()) {
        return;
    }
    if (PMS.isHeadless()) {
        file = getFile(PropertiesUtil.getProjectProperties().get("project.logback.headless").split(","));
    }
    if (file == null) {
        file = getFile(PropertiesUtil.getProjectProperties().get("project.logback").split(","));
    }
    if (file == null) {
        // Unpredictable: Any logback.xml found in the Classpath is loaded, if that fails defaulting to BasicConfigurator
        // See http://logback.qos.ch/xref/ch/qos/logback/classic/BasicConfigurator.html
        LOGGER.warn("Could not load LogBack configuration file from " + (PMS.isHeadless() ? PropertiesUtil.getProjectProperties().get("project.logback.headless") + ", " : "") + PropertiesUtil.getProjectProperties().get("project.logback"));
        LOGGER.warn("Falling back to somewhat unpredictable defaults, probably only logging to console.");
        return;
    }
    // Now get logback to actually use the config file
    JoranConfigurator configurator = new JoranConfigurator();
    configurator.setContext(loggerContext);
    try {
        // the context was probably already configured by
        // default configuration rules
        loggerContext.reset();
        loggerContext.getStatusManager().clear();
        // Do not log between loggerContext.reset() and CacheLogger.initContext()
        configurator.doConfigure(file);
        if (CacheLogger.isActive()) {
            CacheLogger.initContext();
        }
        // Save the file path after loading the file
        synchronized (filepathLock) {
            filepath = file.getAbsolutePath();
            LOGGER.debug("LogBack started with configuration file: {}", filepath);
        }
    } catch (JoranException je) {
        try {
            System.err.println("LogBack configuration failed: " + je.getLocalizedMessage());
            System.err.println("Trying to create \"emergency\" configuration");
            // Try to create "emergency" appenders for some logging if configuration fails
            if (PMS.isHeadless()) {
                ConsoleAppender<ILoggingEvent> ca = new ConsoleAppender<>();
                PatternLayoutEncoder pe = new PatternLayoutEncoder();
                pe.setPattern("%-5level %d{HH:mm:ss.SSS} [%thread] %logger %msg%n");
                pe.setContext(loggerContext);
                pe.start();
                ca.setEncoder(pe);
                ca.setContext(loggerContext);
                ca.setName("Emergency Console");
                ca.start();
                loggerContext.getLogger(Logger.ROOT_LOGGER_NAME).addAppender(ca);
            } else {
                FrameAppender<ILoggingEvent> fa = new FrameAppender<>();
                PatternLayoutEncoder pe = new PatternLayoutEncoder();
                pe.setPattern("%-5level %d{HH:mm:ss.SSS} [%thread] %logger %msg%n");
                pe.setContext(loggerContext);
                pe.start();
                fa.setEncoder(pe);
                fa.setContext(loggerContext);
                fa.setName("Emergency Frame");
                fa.start();
                loggerContext.getLogger(Logger.ROOT_LOGGER_NAME).addAppender(fa);
            }
            System.err.println("LogBack \"emergency\" configuration applied.");
        } catch (Exception e) {
            System.err.println("LogBack \"emergency\" configuration failed with: " + e);
        }
        if (CacheLogger.isActive()) {
            CacheLogger.initContext();
        }
        LOGGER.error("Logback configuration failed with: {}", je.getLocalizedMessage());
        StatusPrinter.printInCaseOfErrorsOrWarnings(loggerContext);
        return;
    }
    // Build the iterator
    Iterators<Appender<ILoggingEvent>> iterators = new Iterators<>();
    // Add CacheLogger appenders if CacheLogger is active
    if (CacheLogger.isActive()) {
        iterators.addIterator(CacheLogger.iteratorForAppenders());
    }
    // non-root appenders there.
    for (Logger logger : loggerContext.getLoggerList()) {
        iterators.addIterator(logger.iteratorForAppenders());
    }
    // Iterate
    Iterator<Appender<ILoggingEvent>> it = iterators.combinedIterator();
    synchronized (logFilePathsLock) {
        while (it.hasNext()) {
            Appender<ILoggingEvent> appender = it.next();
            if (appender instanceof FileAppender) {
                FileAppender<ILoggingEvent> fa = (FileAppender<ILoggingEvent>) appender;
                logFilePaths.put(fa.getName(), fa.getFile());
            } else if (appender instanceof SyslogAppender) {
                syslogDisabled = true;
            }
        }
    }
    // Set filters for console and traces
    setConfigurableFilters(true, true);
    StatusPrinter.printInCaseOfErrorsOrWarnings(loggerContext);
    return;
}
Also used : ConsoleAppender(ch.qos.logback.core.ConsoleAppender) PatternLayoutEncoder(ch.qos.logback.classic.encoder.PatternLayoutEncoder) ConsoleAppender(ch.qos.logback.core.ConsoleAppender) OutputStreamAppender(ch.qos.logback.core.OutputStreamAppender) FileAppender(ch.qos.logback.core.FileAppender) SyslogAppender(ch.qos.logback.classic.net.SyslogAppender) Appender(ch.qos.logback.core.Appender) FileAppender(ch.qos.logback.core.FileAppender) Logger(ch.qos.logback.classic.Logger) ILoggingEvent(ch.qos.logback.classic.spi.ILoggingEvent) UnknownHostException(java.net.UnknownHostException) JoranException(ch.qos.logback.core.joran.spi.JoranException) Iterators(net.pms.util.Iterators) JoranException(ch.qos.logback.core.joran.spi.JoranException) JoranConfigurator(ch.qos.logback.classic.joran.JoranConfigurator) SyslogAppender(ch.qos.logback.classic.net.SyslogAppender) File(java.io.File)

Example 12 with ConsoleAppender

use of ch.qos.logback.core.ConsoleAppender in project jackrabbit-oak by apache.

the class BroadcastTest method listen.

private static void listen() throws InterruptedException {
    String config = "key 123";
    ConsoleAppender<ILoggingEvent> ca = new ConsoleAppender<ILoggingEvent>();
    LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
    ca.setContext(lc);
    PatternLayout pl = new PatternLayout();
    pl.setPattern("%msg%n");
    pl.setContext(lc);
    pl.start();
    ca.setLayout(pl);
    ca.start();
    ch.qos.logback.classic.Logger logger = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger(TCPBroadcaster.class);
    logger.addAppender(ca);
    logger.setLevel(Level.DEBUG);
    TCPBroadcaster receiver = new TCPBroadcaster(config);
    receiver.addListener(new Broadcaster.Listener() {

        @Override
        public void receive(ByteBuffer buff) {
            int end = buff.position();
            StringBuilder sb = new StringBuilder();
            while (buff.remaining() > 0) {
                char c = (char) buff.get();
                if (c >= ' ' && c < 128) {
                    sb.append(c);
                } else if (c <= 9) {
                    sb.append((char) ('0' + c));
                } else {
                    sb.append('.');
                }
            }
            String dateTime = new Timestamp(System.currentTimeMillis()).toString().substring(0, 19);
            System.out.println(dateTime + " Received " + sb);
            buff.position(end);
        }
    });
    Random r = new Random();
    int x = r.nextInt();
    System.out.println("Sending " + x);
    for (int i = 0; i < 10; i++) {
        Thread.sleep(10);
        ByteBuffer buff = ByteBuffer.allocate(1024);
        buff.putInt(0);
        buff.putInt(x);
        buff.put(new byte[100]);
        buff.flip();
        receiver.send(buff);
        if (!receiver.isRunning()) {
            System.out.println("Did not start or already stopped");
            break;
        }
    }
    Thread.sleep(Integer.MAX_VALUE);
}
Also used : ConsoleAppender(ch.qos.logback.core.ConsoleAppender) TCPBroadcaster(org.apache.jackrabbit.oak.plugins.document.persistentCache.broadcast.TCPBroadcaster) PatternLayout(ch.qos.logback.classic.PatternLayout) ILoggingEvent(ch.qos.logback.classic.spi.ILoggingEvent) LoggerContext(ch.qos.logback.classic.LoggerContext) ByteBuffer(java.nio.ByteBuffer) Timestamp(java.sql.Timestamp) Random(java.util.Random) Broadcaster(org.apache.jackrabbit.oak.plugins.document.persistentCache.broadcast.Broadcaster) TCPBroadcaster(org.apache.jackrabbit.oak.plugins.document.persistentCache.broadcast.TCPBroadcaster)

Example 13 with ConsoleAppender

use of ch.qos.logback.core.ConsoleAppender in project adeptj-runtime by AdeptJ.

the class LogbackInitializer method init.

public static void init() {
    long startTime = System.nanoTime();
    Config loggingCfg = Configs.DEFAULT.logging();
    LogbackConfig logbackConfig = getLogbackConfig(loggingCfg);
    LogbackManager logbackMgr = LogbackManager.INSTANCE;
    RollingFileAppender<ILoggingEvent> fileAppender = logbackMgr.createRollingFileAppender(logbackConfig);
    ConsoleAppender<ILoggingEvent> consoleAppender = logbackMgr.createConsoleAppender(APPENDER_CONSOLE, loggingCfg.getString(KEY_LOG_PATTERN_CONSOLE));
    List<Appender<ILoggingEvent>> appenderList = new ArrayList<>();
    appenderList.add(consoleAppender);
    appenderList.add(fileAppender);
    logbackMgr.getAppenders().addAll(appenderList);
    LoggerContext context = logbackMgr.getLoggerContext();
    initRootLogger(context, consoleAppender, loggingCfg);
    addLoggers(loggingCfg, appenderList);
    addAsyncAppender(loggingCfg, fileAppender);
    context.start();
    context.getLogger(LogbackInitializer.class).info(INIT_MSG, elapsedMillis(startTime));
}
Also used : ConsoleAppender(ch.qos.logback.core.ConsoleAppender) Appender(ch.qos.logback.core.Appender) RollingFileAppender(ch.qos.logback.core.rolling.RollingFileAppender) LogbackConfig(com.adeptj.runtime.tools.logging.LogbackConfig) LogbackManager(com.adeptj.runtime.tools.logging.LogbackManager) Config(com.typesafe.config.Config) LogbackConfig(com.adeptj.runtime.tools.logging.LogbackConfig) ArrayList(java.util.ArrayList) ILoggingEvent(ch.qos.logback.classic.spi.ILoggingEvent) LoggerContext(ch.qos.logback.classic.LoggerContext)

Example 14 with ConsoleAppender

use of ch.qos.logback.core.ConsoleAppender in project drill by apache.

the class LogFixture method setupConsole.

private void setupConsole(LogFixtureBuilder builder) {
    drillLogger = (Logger) LoggerFactory.getLogger(DRILL_PACKAGE_NAME);
    if (builder.appender == null && drillLogger.getAppender("STDOUT") != null) {
        return;
    }
    LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
    ple = new PatternLayoutEncoder();
    ple.setPattern(builder.consoleFormat);
    ple.setContext(lc);
    ple.start();
    appender = builder.appender == null ? new ConsoleAppender<>() : builder.appender;
    appender.setContext(lc);
    appender.setName("Console");
    appender.setEncoder(ple);
    appender.start();
    drillLogger.addAppender(appender);
}
Also used : PatternLayoutEncoder(ch.qos.logback.classic.encoder.PatternLayoutEncoder) ConsoleAppender(ch.qos.logback.core.ConsoleAppender) LoggerContext(ch.qos.logback.classic.LoggerContext)

Example 15 with ConsoleAppender

use of ch.qos.logback.core.ConsoleAppender in project sockjs-netty by cgbystrom.

the class TestServer method main.

public static void main(String[] args) {
    Logger rootLogger = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
    LoggerContext loggerContext = rootLogger.getLoggerContext();
    loggerContext.reset();
    PatternLayoutEncoder encoder = new PatternLayoutEncoder();
    encoder.setContext(loggerContext);
    encoder.setPattern("%-5level %-20class{0}: %message%n");
    encoder.start();
    ConsoleAppender<ILoggingEvent> appender = new ConsoleAppender<ILoggingEvent>();
    appender.setContext(loggerContext);
    appender.setEncoder(encoder);
    appender.start();
    rootLogger.addAppender(appender);
    InternalLoggerFactory.setDefaultFactory(new Slf4JLoggerFactory());
    ServerBootstrap bootstrap = new ServerBootstrap(new NioServerSocketChannelFactory(Executors.newCachedThreadPool(), Executors.newCachedThreadPool()));
    final MetricRegistry registry = new MetricRegistry();
    final JmxReporter reporter = JmxReporter.forRegistry(registry).build();
    reporter.start();
    final ServiceRouter router = new ServiceRouter();
    router.setMetricRegistry(registry);
    router.registerService(new Service("/disabled_websocket_echo", new DisabledWebSocketEchoSession()));
    router.registerService(new Service("/close", new CloseSession()));
    router.registerService(new Service("/amplify", new AmplifySession()));
    router.registerService(new Service("/broadcast", new SessionCallbackFactory() {

        @Override
        public BroadcastSession getSession(String id) throws Exception {
            return new BroadcastSession();
        }
    }));
    Service echoService = new Service("/echo", new SessionCallbackFactory() {

        @Override
        public EchoSession getSession(String id) throws Exception {
            return new EchoSession();
        }
    });
    echoService.setMaxResponseSize(4096);
    router.registerService(echoService);
    Service cookieNeededEcho = new Service("/cookie_needed_echo", new EchoSession());
    cookieNeededEcho.setMaxResponseSize(4096);
    cookieNeededEcho.setCookieNeeded(true);
    router.registerService(cookieNeededEcho);
    bootstrap.setPipelineFactory(new ChannelPipelineFactory() {

        @Override
        public ChannelPipeline getPipeline() throws Exception {
            ChannelPipeline pipeline = pipeline();
            pipeline.addLast("decoder", new HttpRequestDecoder());
            // Required for WS handshaker or else NPE.
            pipeline.addLast("chunkAggregator", new HttpChunkAggregator(130 * 1024));
            pipeline.addLast("encoder", new HttpResponseEncoder());
            pipeline.addLast("preflight", new PreflightHandler());
            pipeline.addLast("router", router);
            return pipeline;
        }
    });
    bootstrap.bind(new InetSocketAddress(8090));
    System.out.println("Server running..");
}
Also used : ConsoleAppender(ch.qos.logback.core.ConsoleAppender) InetSocketAddress(java.net.InetSocketAddress) Logger(ch.qos.logback.classic.Logger) ILoggingEvent(ch.qos.logback.classic.spi.ILoggingEvent) HttpRequestDecoder(org.jboss.netty.handler.codec.http.HttpRequestDecoder) Slf4JLoggerFactory(org.jboss.netty.logging.Slf4JLoggerFactory) PatternLayoutEncoder(ch.qos.logback.classic.encoder.PatternLayoutEncoder) NioServerSocketChannelFactory(org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory) MetricRegistry(com.codahale.metrics.MetricRegistry) HttpChunkAggregator(org.jboss.netty.handler.codec.http.HttpChunkAggregator) BroadcastSession(com.cgbystrom.sockjs.test.BroadcastSession) LoggerContext(ch.qos.logback.classic.LoggerContext) JmxReporter(com.codahale.metrics.JmxReporter) ServerBootstrap(org.jboss.netty.bootstrap.ServerBootstrap) ChannelPipeline(org.jboss.netty.channel.ChannelPipeline) HttpResponseEncoder(org.jboss.netty.handler.codec.http.HttpResponseEncoder) ChannelPipelineFactory(org.jboss.netty.channel.ChannelPipelineFactory)

Aggregations

ConsoleAppender (ch.qos.logback.core.ConsoleAppender)38 ILoggingEvent (ch.qos.logback.classic.spi.ILoggingEvent)31 PatternLayoutEncoder (ch.qos.logback.classic.encoder.PatternLayoutEncoder)21 LoggerContext (ch.qos.logback.classic.LoggerContext)19 Logger (ch.qos.logback.classic.Logger)16 Appender (ch.qos.logback.core.Appender)10 FileAppender (ch.qos.logback.core.FileAppender)9 Test (org.junit.Test)8 ThresholdFilter (ch.qos.logback.classic.filter.ThresholdFilter)5 OutputStreamAppender (ch.qos.logback.core.OutputStreamAppender)5 LayoutWrappingEncoder (ch.qos.logback.core.encoder.LayoutWrappingEncoder)5 SyslogAppender (ch.qos.logback.classic.net.SyslogAppender)4 JoranConfigurator (ch.qos.logback.classic.joran.JoranConfigurator)3 File (java.io.File)3 ArrayList (java.util.ArrayList)3 AsyncAppender (ch.qos.logback.classic.AsyncAppender)2 JoranException (ch.qos.logback.core.joran.spi.JoranException)2 RollingFileAppender (ch.qos.logback.core.rolling.RollingFileAppender)2 MetricRegistry (com.codahale.metrics.MetricRegistry)2 PmsConfiguration (net.pms.configuration.PmsConfiguration)2