Search in sources :

Example 1 with SyslogAppender

use of ch.qos.logback.classic.net.SyslogAppender in project qpid-broker-j by apache.

the class BrokerSyslogLoggerImpl method createAppenderInstance.

@Override
protected Appender<ILoggingEvent> createAppenderInstance(Context context) {
    SyslogAppender syslogAppender = new SyslogAppender();
    syslogAppender.setSyslogHost(_syslogHost);
    syslogAppender.setPort(_port);
    syslogAppender.setSuffixPattern(_suffixPattern);
    syslogAppender.setStackTracePattern(_stackTracePattern);
    syslogAppender.setThrowableExcluded(_throwableExcluded);
    syslogAppender.setFacility("USER");
    return syslogAppender;
}
Also used : SyslogAppender(ch.qos.logback.classic.net.SyslogAppender)

Example 2 with SyslogAppender

use of ch.qos.logback.classic.net.SyslogAppender in project qpid-broker-j by apache.

the class VirtualHostSyslogLoggerImpl method createAppenderInstance.

@Override
protected Appender<ILoggingEvent> createAppenderInstance(Context context) {
    SyslogAppender syslogAppender = new SyslogAppender();
    syslogAppender.setSyslogHost(_syslogHost);
    syslogAppender.setPort(_port);
    syslogAppender.setSuffixPattern(_suffixPattern);
    syslogAppender.setStackTracePattern(_stackTracePattern);
    syslogAppender.setThrowableExcluded(_throwableExcluded);
    syslogAppender.setFacility("USER");
    return syslogAppender;
}
Also used : SyslogAppender(ch.qos.logback.classic.net.SyslogAppender)

Example 3 with SyslogAppender

use of ch.qos.logback.classic.net.SyslogAppender in project UniversalMediaServer by UniversalMediaServer.

the class LoggingConfig method setSyslog.

/**
 * Adds/modifies/removes a syslog appender based on PmsConfiguration and
 * disables/enables file appenders for easier access to syslog logging for
 * users without in-depth knowledge of LogBack. Stops file appenders if
 * syslog is started and vice versa.<P>
 *
 * Must be called after {@link #loadFile()} and after UMS configuration is
 * loaded.
 */
public static synchronized void setSyslog() {
    ActionType action = ActionType.NONE;
    PmsConfiguration configuration = PMS.getConfiguration();
    if (loggerContext == null) {
        LOGGER.error("Unknown loggerContext, aborting syslog configuration. Make sure that loadFile() has been called first.");
        return;
    } else if (syslogDisabled) {
        // Only create a new syslog appender if there's no syslog appender configured already
        LOGGER.warn("A syslog appender is already configured, aborting syslog configuration");
        return;
    }
    if (configuration.getLoggingUseSyslog()) {
        // Check for valid parameters
        if (configuration.getLoggingSyslogHost().isEmpty()) {
            LOGGER.error("Empty syslog hostname, syslog configuration aborted");
            return;
        }
        try {
            InetAddress.getByName(configuration.getLoggingSyslogHost());
        } catch (UnknownHostException e) {
            LOGGER.error("Unknown syslog hostname {}, syslog configuration aborted", configuration.getLoggingSyslogHost());
            return;
        }
        if (configuration.getLoggingSyslogPort() < 1 && configuration.getLoggingSyslogPort() > 65535) {
            LOGGER.error("Invalid syslog port {}, using default", configuration.getLoggingSyslogPort());
            configuration.setLoggingSyslogPortDefault();
        }
        if (!configuration.getLoggingSyslogFacility().toLowerCase().matches("auth|authpriv|daemon|cron|ftp|lpr|kern|mail|news|syslog|user|" + "uucp|local0|local1|local2|local3|local4|local5|local6|local7")) {
            LOGGER.error("Invalid syslog facility \"{}\", using default", configuration.getLoggingSyslogFacility());
            configuration.setLoggingSyslogFacilityDefault();
        }
    }
    if (configuration.getLoggingUseSyslog() && syslog == null) {
        syslog = new SyslogAppender();
        syslog.setContext(loggerContext);
        syslog.setSuffixPattern("UMS [%thread] %msg");
        syslog.setName("UMS syslog");
        syslog.setCharset(StandardCharsets.UTF_8);
        action = ActionType.START;
    } else if (!configuration.getLoggingUseSyslog() && syslog != null) {
        action = ActionType.STOP;
    }
    if (syslog != null && (action == ActionType.START || action == ActionType.NONE)) {
        syslog.setSyslogHost(configuration.getLoggingSyslogHost());
        syslog.setPort(configuration.getLoggingSyslogPort());
        syslog.setFacility(configuration.getLoggingSyslogFacility().toUpperCase());
        syslog.start();
    }
    if (action == ActionType.START || action == ActionType.STOP) {
        Iterator<Appender<ILoggingEvent>> it = CacheLogger.isActive() ? CacheLogger.iteratorForAppenders() : rootLogger.iteratorForAppenders();
        while (it.hasNext()) {
            Appender<ILoggingEvent> appender = it.next();
            if (action == ActionType.START && appender instanceof FileAppender) {
                if (CacheLogger.isActive()) {
                    CacheLogger.removeAppender(appender);
                } else {
                    rootLogger.detachAppender(appender);
                }
                syslogDetachedAppenders.add(appender);
                // If syslog is disabled later and this appender reactivated, append to the file instead of truncate
                ((FileAppender<ILoggingEvent>) appender).setAppend(true);
            } else if (action == ActionType.STOP && appender == syslog) {
                if (CacheLogger.isActive()) {
                    CacheLogger.removeAppender(syslog);
                } else {
                    rootLogger.detachAppender(syslog);
                }
                syslog.stop();
                syslog = null;
            }
        }
        if (action == ActionType.START) {
            if (CacheLogger.isActive()) {
                CacheLogger.addAppender(syslog);
            } else {
                rootLogger.addAppender(syslog);
            }
            LOGGER.info("Syslog logging started, file logging disabled");
        } else {
            it = syslogDetachedAppenders.iterator();
            while (it.hasNext()) {
                Appender<ILoggingEvent> appender = it.next();
                if (CacheLogger.isActive()) {
                    CacheLogger.addAppender(appender);
                } else {
                    rootLogger.addAppender(appender);
                }
            }
            syslogDetachedAppenders.clear();
            LOGGER.info("Syslog logging stopped, file logging enabled");
        }
    }
}
Also used : 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) UnknownHostException(java.net.UnknownHostException) PmsConfiguration(net.pms.configuration.PmsConfiguration) SyslogAppender(ch.qos.logback.classic.net.SyslogAppender) ILoggingEvent(ch.qos.logback.classic.spi.ILoggingEvent)

Example 4 with SyslogAppender

use of ch.qos.logback.classic.net.SyslogAppender 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 5 with SyslogAppender

use of ch.qos.logback.classic.net.SyslogAppender in project AJSC by att.

the class loggingConfigurationTest method getSyslogAppenderInstanceTest.

@Test
public void getSyslogAppenderInstanceTest() {
    System.out.println("Running getSyslogAppenderInstanceTest");
    LoggingConfigurationService l = new LoggingConfigurationService();
    l.init();
    Map<String, Object> map = new HashMap<String, Object>();
    map.put("appenderName", "appenderName");
    map.put("rfFileName", System.getProperty("AJSC_HOME") + File.separator + "logs" + File.separator + "rollingpolicy.log");
    // map.put("rfFiltersConf", value);
    // map.put(key, value)
    SyslogAppender sa = (SyslogAppender) l.getSyslogAppenderInstance(map);
    assertEquals("ch.qos.logback.classic.net.SyslogAppender", sa.getClass().getName());
}
Also used : HashMap(java.util.HashMap) SyslogAppender(ch.qos.logback.classic.net.SyslogAppender) Test(org.junit.Test)

Aggregations

SyslogAppender (ch.qos.logback.classic.net.SyslogAppender)8 ILoggingEvent (ch.qos.logback.classic.spi.ILoggingEvent)3 Appender (ch.qos.logback.core.Appender)3 AsyncAppender (ch.qos.logback.classic.AsyncAppender)2 Logger (ch.qos.logback.classic.Logger)2 LoggerContext (ch.qos.logback.classic.LoggerContext)2 ConsoleAppender (ch.qos.logback.core.ConsoleAppender)2 FileAppender (ch.qos.logback.core.FileAppender)2 OutputStreamAppender (ch.qos.logback.core.OutputStreamAppender)2 AsyncLoggingEventAppenderFactory (io.dropwizard.logging.async.AsyncLoggingEventAppenderFactory)2 NullLevelFilterFactory (io.dropwizard.logging.filter.NullLevelFilterFactory)2 DropwizardLayoutFactory (io.dropwizard.logging.layout.DropwizardLayoutFactory)2 UnknownHostException (java.net.UnknownHostException)2 Test (org.junit.Test)2 PatternLayoutEncoder (ch.qos.logback.classic.encoder.PatternLayoutEncoder)1 JoranConfigurator (ch.qos.logback.classic.joran.JoranConfigurator)1 JoranException (ch.qos.logback.core.joran.spi.JoranException)1 DiscoverableSubtypeResolver (io.dropwizard.jackson.DiscoverableSubtypeResolver)1 File (java.io.File)1 HashMap (java.util.HashMap)1