Example usage for java.util.logging LogManager getLogManager

List of usage examples for java.util.logging LogManager getLogManager

Introduction

In this page you can find the example usage for java.util.logging LogManager getLogManager.

Prototype

public static LogManager getLogManager() 

Source Link

Document

Returns the global LogManager object.

Usage

From source file:pub.vrtech.common.logs.jdk.JdkLoggerAdapter.java

public JdkLoggerAdapter() {
    try {/* w  ww .java 2  s  .c o m*/
        InputStream in = Thread.currentThread().getContextClassLoader()
                .getResourceAsStream("logging.properties");
        if (in != null) {
            LogManager.getLogManager().readConfiguration(in);
        } else {
            System.err.println("No such logging.properties in classpath for jdk logging config!");
        }
    } catch (Throwable t) {
        System.err.println("Failed to load logging.properties in classpath for jdk logging config, cause: "
                + t.getMessage());
    }
    try {
        Handler[] handlers = java.util.logging.Logger.getLogger(GLOBAL_LOGGER_NAME).getHandlers();
        for (Handler handler : handlers) {
            if (handler instanceof FileHandler) {
                FileHandler fileHandler = (FileHandler) handler;
                Field field = fileHandler.getClass().getField("files");
                File[] files = (File[]) field.get(fileHandler);
                if (files != null && files.length > 0) {
                    file = files[0];
                }
            }
        }
    } catch (Throwable t) {
    }
}

From source file:org.ballerinalang.composer.server.launcher.log.LogManagerUtils.java

/**
 * Updating the default log manager.//from  w  ww.  j a  v  a 2  s . co m
 * @throws IOException When log config file cannot be found.
 */
public void updateLogManager() throws IOException {
    // Modifying log manager property reading.
    LogManager logManager = LogManager.getLogManager();
    InputStream properties = this.readConfiguration();
    logManager.readConfiguration(properties);
}

From source file:com.googlecode.arit.jul.HandlerResourceScanner.java

public HandlerResourceScanner() {
    LogManager logManager = LogManager.getLogManager();
    Class<? extends LogManager> clazz = logManager.getClass();
    try {//from w w  w. j a v  a  2  s.com
        // We only enable the plugin if the getLoggerNames method has not been overridden.
        // An overridden getLoggerNames method is an indication that the log manager maintains
        // multiple logger name spaces and that we need a specialized plugin. This is the
        // case for Tomcat's ClassLoaderLogManager. Note that WebSphere's WsLogManager
        // overrides getLogger, but not getLoggerNames.
        if (clazz.getMethod("getLoggerNames").getDeclaringClass().equals(LogManager.class)) {
            this.logManager = logManager;
        } else {
            this.logManager = null;
        }
    } catch (NoSuchMethodException ex) {
        throw new NoSuchMethodError(ex.getMessage());
    }
}

From source file:org.eclipse.gyrex.boot.internal.logback.LogbackConfigurator.java

public static void configureDefaultContext() throws Exception {
    // reset JUL (this should disable the default JUL console output)
    LogManager.getLogManager().reset();

    // install SLF4J Bridge
    if (!SLF4JBridgeHandler.isInstalled()) {
        SLF4JBridgeHandler.install();// w  w  w  .j a  va2s.c  o m
    }

    // don't perform any further configuration if a config file is specified
    if (StringUtils.isNotBlank(System.getProperty("logback.configurationFile")))
        return;

    // reset LoggerContext
    final LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
    lc.reset();

    // turn of packaging data calculation in production (http://jira.qos.ch/browse/LOGBACK-730)
    lc.setPackagingDataEnabled(Platform.inDevelopmentMode());

    // install SLF4J Bridge
    if (!SLF4JBridgeHandler.isInstalled()) {
        SLF4JBridgeHandler.install();
    }

    // configure status manager
    if (lc.getStatusManager() == null) {
        lc.setStatusManager(new BasicStatusManager());
    }
    final StatusManager sm = lc.getStatusManager();

    // always good to have a console status listener
    if (Platform.inDebugMode() || Platform.inDevelopmentMode()) {
        final OnConsoleStatusListener onConsoleStatusListener = new OnConsoleStatusListener();
        onConsoleStatusListener.setContext(lc);
        sm.add(onConsoleStatusListener);
        onConsoleStatusListener.start();
    }

    // signal Gyrex configuration
    sm.add(new InfoStatus("Setting up Gyrex log configuration.", lc));

    // ensure log directory exists
    final IPath instanceLogfileDirectory = getLogfileDir();
    if (null != instanceLogfileDirectory) {
        instanceLogfileDirectory.toFile().mkdirs();
    }

    // prefer configuration file from workspace
    final File configurationFile = getLogConfigurationFile();
    if ((null != configurationFile) && configurationFile.isFile() && configurationFile.canRead()) {

        sm.add(new InfoStatus(
                String.format("Loading configuration from '%s'.", configurationFile.getAbsolutePath()), lc));

        // create our customized configurator
        final JoranConfigurator configurator = new JoranConfigurator() {
            @Override
            protected void addImplicitRules(final Interpreter interpreter) {
                super.addImplicitRules(interpreter);
                // set some properties for log file substitution
                if (null != instanceLogfileDirectory) {
                    interpreter.getInterpretationContext().addSubstitutionProperty("gyrex.instance.area.logs",
                            instanceLogfileDirectory.addTrailingSeparator().toOSString());
                }
            }
        };
        configurator.setContext(lc);

        // configuration
        configurator.doConfigure(configurationFile);

        // print logback's internal status
        StatusPrinter.printIfErrorsOccured(lc);

        // done'
        return;
    }

    // get root logger
    final Logger rootLogger = lc.getLogger(org.slf4j.Logger.ROOT_LOGGER_NAME);

    // propagate level changes to java.util.logging
    final LevelChangePropagator levelChangePropagator = new LevelChangePropagator();
    levelChangePropagator.setResetJUL(true);
    levelChangePropagator.setContext(lc);
    lc.addListener(levelChangePropagator);
    levelChangePropagator.start();

    // add console logger
    rootLogger.addAppender(createConsoleAppender(lc));

    // add error logger
    if (null != instanceLogfileDirectory) {
        rootLogger.addAppender(createErrorLogAppender(lc, instanceLogfileDirectory));
    }

    // set log level
    if (Platform.inDebugMode() || Platform.inDevelopmentMode()) {
        rootLogger.setLevel(Level.DEBUG);
    } else {
        rootLogger.setLevel(Level.INFO);
    }

    // some of our components are very communicative
    // we apply some "smart" defaults for those known 3rdParty libs
    lc.getLogger("org.apache.commons").setLevel(Level.WARN);
    lc.getLogger("httpclient.wire").setLevel(Level.WARN);
    lc.getLogger("org.apache.http").setLevel(Level.WARN);
    lc.getLogger("org.apache.zookeeper").setLevel(Level.WARN);
    lc.getLogger("org.apache.solr").setLevel(Level.WARN);
    lc.getLogger("org.apache.sshd").setLevel(Level.WARN);
    lc.getLogger("org.apache.mina").setLevel(Level.WARN);
    lc.getLogger("org.mortbay.log").setLevel(Level.WARN);
    lc.getLogger("org.eclipse.jetty").setLevel(Level.INFO);
    lc.getLogger("org.quartz").setLevel(Level.INFO);
    lc.getLogger("sun").setLevel(Level.INFO);

    // apply overrides
    if (!LOGBACK_DEBUG_OPTIONS_BRIDGE.overriddenLogLevels.isEmpty()) {
        for (final Entry<String, String[]> e : LOGBACK_DEBUG_OPTIONS_BRIDGE.overriddenLogLevels.entrySet()) {
            lc.getLogger(e.getKey()).setLevel(Level.toLevel(e.getValue()[0], null));
        }
    }

    // print logback's internal status
    StatusPrinter.printIfErrorsOccured(lc);
}

From source file:com.izforge.izpack.util.LogUtils.java

public static void loadConfiguration(final Properties configuration) throws IOException {
    if (OVERRIDE) {
        LogManager manager = LogManager.getLogManager();

        // Merge global logging properties
        InputStream baseResourceStream = null;
        try {/*from   ww  w.j  a v  a 2s.com*/
            baseResourceStream = LogUtils.class.getResourceAsStream(LOGGING_BASE_CONFIGURATION);
            final Properties baseProps = new Properties();
            baseProps.load(baseResourceStream);
            mergeLoggingConfiguration(configuration, baseProps);
        } finally {
            IOUtils.closeQuietly(baseResourceStream);
        }

        boolean mkdirs = false;
        String pattern = null;
        if (configuration.getProperty("handlers") != null
                && configuration.getProperty("handlers").contains(FILEHANDLER_CLASSNAME)
                && manager.getProperty("handlers").contains(FILEHANDLER_CLASSNAME)) {
            // IzPack maintains just one log file, don't override the existing handler type of it.
            // Special use case: Command line argument -logfile "wins" over the <log-file> tag.
            // Assumption at the moment for optimization: Just FileHandler is used for configurations from install.xml.
            return;
        }
        for (String key : configuration.stringPropertyNames()) {
            if (key.equals(FILEHANDLER_CLASSNAME + ".pattern")) {
                // Workaround for not normalized file paths, for example ${INSTALL_PATH}/../install_log/name.log
                // to get them working before creating ${INSTALL_PATH} in the
                // com.izforge.izpack.installer.unpacker.UnpackerBase.preUnpack phase
                // otherwise the FileHandler will fail when opening files already in constructor and not recover from that.
                pattern = FilenameUtils.normalize(configuration.getProperty(key));
                configuration.setProperty(key, pattern);
            } else if (key.equals(FILEHANDLER_CLASSNAME + ".mkdirs")) {
                // This key goes beyond the capabilities of java.util.logging.FileHandler
                mkdirs = Boolean.parseBoolean(configuration.getProperty(key));
                configuration.remove(key);
            }
        }
        if (mkdirs && pattern != null) {
            FileUtils.forceMkdirParent(new File(pattern));
        }

        // Merge user settings compiled in
        final Properties userProps = new Properties();
        InputStream userPropsStream = LogUtils.class
                .getResourceAsStream(ResourceManager.getInstallLoggingConfigurationResourceName());
        try {
            if (userPropsStream != null) {
                userProps.load(userPropsStream);
                for (String userPropName : userProps.stringPropertyNames()) {
                    if (userPropName.endsWith(".level") && !userPropName.startsWith(FILEHANDLER_CLASSNAME)) {
                        String level = userProps.getProperty(userPropName);
                        if (level != null) {
                            configuration.setProperty(userPropName, level);
                        }
                    }
                }
            }
        } finally {
            IOUtils.closeQuietly(userPropsStream);
        }

        InputStream defaultResourceStream = null;
        try {
            defaultResourceStream = LogUtils.class.getResourceAsStream(LOGGING_CONFIGURATION);
            final Properties defaultProps = new Properties();
            defaultProps.load(defaultResourceStream);
            mergeLoggingConfiguration(configuration, defaultProps);
        } finally {
            IOUtils.closeQuietly(defaultResourceStream);
        }

        if (Debug.isDEBUG()) {
            configuration.setProperty(FILEHANDLER_CLASSNAME + ".level", Level.FINE.toString());
            configuration.setProperty(ConsoleHandler.class.getName() + ".level", Level.FINE.toString());
        }

        // Set general log level which acts as filter in front of all handlers
        String fileLevelName = configuration.getProperty(FILEHANDLER_CLASSNAME + ".level",
                Level.ALL.toString());
        Level fileLevel = Level.ALL;
        if (fileLevelName != null) {
            fileLevel = Level.parse(fileLevelName);
        }

        String consoleLevelName = configuration.getProperty(CONSOLEHANDLER_CLASSNAME + ".level",
                Level.INFO.toString());
        Level consoleLevel = Level.INFO;
        if (consoleLevelName != null) {
            consoleLevel = Level.parse(consoleLevelName);
        }

        configuration.setProperty(".level",
                (fileLevel.intValue() < consoleLevel.intValue()) ? fileLevelName : consoleLevelName);

        final PipedOutputStream out = new PipedOutputStream();
        final PipedInputStream in = new PipedInputStream(out);
        try {
            new Thread(new Runnable() {
                public void run() {
                    try {
                        configuration.store(out, null);
                    } catch (IOException e) {
                        e.printStackTrace();
                    } finally {
                        IOUtils.closeQuietly(out);
                    }
                }
            }).start();

            manager.readConfiguration(in);
        } finally {
            IOUtils.closeQuietly(in);
        }
    }
}

From source file:org.uiautomation.ios.server.IOSDriver.java

public IOSDriver(int port) {
    try {//w  w w  .j a v a 2  s. c  o m
        LogManager.getLogManager()
                .readConfiguration(IOSDriver.class.getResourceAsStream("/ios-logging.properties"));
    } catch (Exception e) {
        System.err.println("Cannot configure logger.");
    }
    this.hostInfo = new HostInfo(port);
}

From source file:org.nuxeo.common.logging.JavaUtilLoggingHelper.java

/**
 * Resets {@code java.util.logging} redirections.
 */// ww  w  . j ava  2 s . co m
public static synchronized void reset() {
    if (activeHandler == null) {
        return;
    }
    try {
        Logger rootLogger = LogManager.getLogManager().getLogger("");
        rootLogger.removeHandler(activeHandler);
    } catch (SecurityException e) {
        log.error("Handler removal failed", e);
    }
    activeHandler = null;
}

From source file:cz.hobrasoft.pdfmu.Main.java

private static void disableLoggers() {
    // http://stackoverflow.com/a/3363747
    LogManager.getLogManager().reset(); // Remove the handlers
}

From source file:org.dstadler.commons.logging.jdk.PatternFormatter.java

public PatternFormatter() {
    LogManager manager = LogManager.getLogManager();
    String cName = getClass().getName();

    timeFormat = manager.getProperty(cName + ".timeFormat");

    if (timeFormat == null) {
        timeFormat = "dd-MMM-yyy; HH:mm:ss";
    }/*  w  w w.j  av  a2  s . c om*/
    setTimeFormat(timeFormat);

    logPattern = manager.getProperty(cName + ".logPattern");
    if (logPattern == null) {
        logPattern = "[{0} - {1}] {2}: {3} \n";
    }
    setLogPattern(logPattern);

    exceptionPattern = manager.getProperty(cName + ".exceptionPattern");
    if (exceptionPattern == null) {
        exceptionPattern = "[{0} - {1}] {2} {3} \nException in {4}: {6} \n{7} ";
    }
    setExceptionPattern(exceptionPattern);

    logMessageFormat = new MessageFormat(logPattern, Locale.ROOT);
    exceptionMessageFormat = new MessageFormat(exceptionPattern, Locale.ROOT);

    dateFormat = FastDateFormat.getInstance(timeFormat);
}

From source file:org.codesecure.dependencycheck.App.java

private static void prepareLogger() {
    //while java doc for JUL says to use preferences api - it throws an exception...
    //Preferences.systemRoot().put("java.util.logging.config.file", "log.properties");
    //System.getProperties().put("java.util.logging.config.file", "configuration/log.properties");
    File dir = new File("logs");

    if (!dir.exists()) {
        dir.mkdir();// w  ww .j a v a 2s  . c o m
    }
    try {
        InputStream in = App.class.getClassLoader().getResourceAsStream(LOG_PROPERTIES_FILE);
        LogManager.getLogManager().reset();
        LogManager.getLogManager().readConfiguration(in);
    } catch (IOException ex) {
        System.err.println(ex.toString());
        Logger.getLogger(App.class.getName()).log(Level.SEVERE, null, ex);
    } catch (SecurityException ex) {
        Logger.getLogger(App.class.getName()).log(Level.SEVERE, null, ex);
    }
}