Example usage for java.util.logging LogManager getLogger

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

Introduction

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

Prototype

public Logger getLogger(String name) 

Source Link

Document

Method to find a named logger.

Usage

From source file:alma.acs.logging.AcsLogger.java

/**
 * Non-standard factory method to be used only for special offline or testing purposes
 * where typically an AcsLogger must be provided by an alternative implementation of ContainerServices.
 * The returned AcsLogger is just like a JDK Logger obtained from {@link Logger#getLogger(String, String)}.
 * <p>//from www  .  j  av  a 2 s  .  c  om
 * Note that we do not supply a {@link LogConfig} and therefore the new AcsLogger cannot register itself 
 * for initial configuration or later configuration change notifications. <br>
 * <b>It is the client's responsibility to configure the log level and parent logger of the returned AcsLogger!</b>
 * 
 * @param name  the logger's name
 * @param resourceBundleName
 * @return <code>AcsLogger</code> that is as close to a normal JDK Logger as possible.
 * @throws IllegalArgumentException 
 *              If a Logger of the given <code>name</code> exists but is not an <code>AcsLogger</code>,
 *              or if an AcsLogger of the given <code>name</code> exists but has a different <code>resourceBundleName</code>.
 */
public static AcsLogger createUnconfiguredLogger(String name, String resourceBundleName) {

    // the following code is copied and modified from Logger.getLogger 

    LogManager manager = LogManager.getLogManager();
    Logger jdkLogger = manager.getLogger(name);
    if (jdkLogger != null && !(jdkLogger instanceof AcsLogger)) {
        throw new IllegalArgumentException(
                "Logger " + name + " already exists but is not of subtype AcsLogger.");
    }
    AcsLogger result = (AcsLogger) jdkLogger;

    if (result == null) {
        // Create a new logger.
        // Note: we may get a MissingResourceException here.
        result = new AcsLogger(name, resourceBundleName, null, true, null);
        manager.addLogger(result);
        result = (AcsLogger) manager.getLogger(name);
    }

    // unlike in the JDK logger, we can't fix the resource bundle name if the logger from cache had null and now one is given.
    // however we check that the old and new bundle are consistent.
    if (result.getResourceBundleName() != null && !result.getResourceBundleName().equals(resourceBundleName)) {
        throw new IllegalArgumentException(result.getResourceBundleName() + " != " + resourceBundleName);
    }
    return result;
}

From source file:com.l2jfree.L2Config.java

/** Flushes all pending log entries. */
// FIXME MMOLogger.flush()
public static void flush() {
    // those are redirected to loggers, so flush them first
    System.out.flush();// w  w  w  .j  a  v a2s .  co  m
    System.err.flush();

    // then flush the loggers themselves
    final LogManager logManager = LogManager.getLogManager();

    for (String loggerName : Collections.list(logManager.getLoggerNames())) {
        if (loggerName == null)
            continue;

        final Logger logger = logManager.getLogger(loggerName);

        if (logger == null)
            continue;

        for (Handler handler : logger.getHandlers())
            if (handler != null)
                handler.flush();
    }

    // and finally the real console streams
    L2Config.out.flush();
    L2Config.err.flush();
}

From source file:com.ellychou.todo.rest.service.SpringContextJerseyTest.java

/**
* Retrieves a list of root loggers./*from w  w  w  .jav a2 s.c om*/
*
* @return list of root loggers.
*/
private Set<Logger> getRootLoggers() {
    final LogManager logManager = LogManager.getLogManager();
    final Enumeration<String> loggerNames = logManager.getLoggerNames();

    final Set<Logger> rootLoggers = Sets.newHashSet();

    while (loggerNames.hasMoreElements()) {
        Logger logger = logManager.getLogger(loggerNames.nextElement());
        if (logger != null) {
            while (logger.getParent() != null) {
                logger = logger.getParent();
            }
            rootLoggers.add(logger);
        }
    }

    return rootLoggers;
}

From source file:MailHandlerDemo.java

/**
 * Used debug problems with the logging.properties. The system property
 * java.security.debug=access,stack can be used to trace access to the
 * LogManager reset.//  w ww  . j a  va2s . c  om
 *
 * @param prefix a string to prefix the output.
 * @param err any PrintStream or null for System.out.
 */
@SuppressWarnings("UseOfSystemOutOrSystemErr")
private static void checkConfig(String prefix, PrintStream err) {
    if (prefix == null || prefix.trim().length() == 0) {
        prefix = "DEBUG";
    }

    if (err == null) {
        err = System.out;
    }

    try {
        err.println(prefix + ": java.version=" + System.getProperty("java.version"));
        err.println(prefix + ": LOGGER=" + LOGGER.getLevel());
        err.println(prefix + ": JVM id " + ManagementFactory.getRuntimeMXBean().getName());
        err.println(prefix + ": java.security.debug=" + System.getProperty("java.security.debug"));
        SecurityManager sm = System.getSecurityManager();
        if (sm != null) {
            err.println(prefix + ": SecurityManager.class=" + sm.getClass().getName());
            err.println(prefix + ": SecurityManager classLoader=" + toString(sm.getClass().getClassLoader()));
            err.println(prefix + ": SecurityManager.toString=" + sm);
        } else {
            err.println(prefix + ": SecurityManager.class=null");
            err.println(prefix + ": SecurityManager.toString=null");
            err.println(prefix + ": SecurityManager classLoader=null");
        }

        String policy = System.getProperty("java.security.policy");
        if (policy != null) {
            File f = new File(policy);
            err.println(prefix + ": AbsolutePath=" + f.getAbsolutePath());
            err.println(prefix + ": CanonicalPath=" + f.getCanonicalPath());
            err.println(prefix + ": length=" + f.length());
            err.println(prefix + ": canRead=" + f.canRead());
            err.println(prefix + ": lastModified=" + new java.util.Date(f.lastModified()));
        }

        LogManager manager = LogManager.getLogManager();
        String key = "java.util.logging.config.file";
        String cfg = System.getProperty(key);
        if (cfg != null) {
            err.println(prefix + ": " + cfg);
            File f = new File(cfg);
            err.println(prefix + ": AbsolutePath=" + f.getAbsolutePath());
            err.println(prefix + ": CanonicalPath=" + f.getCanonicalPath());
            err.println(prefix + ": length=" + f.length());
            err.println(prefix + ": canRead=" + f.canRead());
            err.println(prefix + ": lastModified=" + new java.util.Date(f.lastModified()));
        } else {
            err.println(prefix + ": " + key + " is not set as a system property.");
        }
        err.println(prefix + ": LogManager.class=" + manager.getClass().getName());
        err.println(prefix + ": LogManager classLoader=" + toString(manager.getClass().getClassLoader()));
        err.println(prefix + ": LogManager.toString=" + manager);
        err.println(prefix + ": MailHandler classLoader=" + toString(MailHandler.class.getClassLoader()));
        err.println(
                prefix + ": Context ClassLoader=" + toString(Thread.currentThread().getContextClassLoader()));
        err.println(prefix + ": Session ClassLoader=" + toString(Session.class.getClassLoader()));
        err.println(prefix + ": DataHandler ClassLoader=" + toString(DataHandler.class.getClassLoader()));

        final String p = MailHandler.class.getName();
        key = p.concat(".mail.to");
        String to = manager.getProperty(key);
        err.println(prefix + ": TO=" + to);
        if (to != null) {
            err.println(prefix + ": TO=" + Arrays.toString(InternetAddress.parse(to, true)));
        }

        key = p.concat(".mail.from");
        String from = manager.getProperty(key);
        if (from == null || from.length() == 0) {
            Session session = Session.getInstance(new Properties());
            InternetAddress local = InternetAddress.getLocalAddress(session);
            err.println(prefix + ": FROM=" + local);
        } else {
            err.println(prefix + ": FROM=" + Arrays.asList(InternetAddress.parse(from, false)));
            err.println(prefix + ": FROM=" + Arrays.asList(InternetAddress.parse(from, true)));
        }

        synchronized (manager) {
            final Enumeration<String> e = manager.getLoggerNames();
            while (e.hasMoreElements()) {
                final Logger l = manager.getLogger(e.nextElement());
                if (l != null) {
                    final Handler[] handlers = l.getHandlers();
                    if (handlers.length > 0) {
                        err.println(prefix + ": " + l.getClass().getName() + ", " + l.getName());
                        for (Handler h : handlers) {
                            err.println(prefix + ":\t" + toString(prefix, err, h));
                        }
                    }
                }
            }
        }
    } catch (Throwable error) {
        err.print(prefix + ": ");
        error.printStackTrace(err);
    }
    err.flush();
}

From source file:org.ebayopensource.turmeric.eclipse.core.logging.SOALogger.java

/**
 * If the tracing is enabled, then the logging level will be setup accordingly.
 *
 * @param clazz the clazz/*from   w  ww.  jav  a  2 s  . co m*/
 * @return An instance of <code>LogManager</code>
 */
public static synchronized SOALogger getLogger(String clazz) {
    java.util.logging.LogManager manager = java.util.logging.LogManager.getLogManager();
    Logger result = manager.getLogger(clazz);
    if (result instanceof SOALogger) {
        return (SOALogger) result;
    } else if (result != null) {//there is an existing logger instance
        if (loggers.keySet().contains(clazz)) {
            return loggers.get(clazz);
        }
        SOALogger logger = new SOALogger(clazz);
        logger.setLevel(result.getLevel());
        logger.setFilter(result.getFilter());
        logger.setParent(result.getParent());
        logger.setUseParentHandlers(logger.getUseParentHandlers());
        loggers.put(clazz, logger);
        return logger;
    } else {//can not find a logger, so let's create one.
        result = new SOALogger(clazz);
    }

    manager.addLogger(result);
    SOALogger logger = (SOALogger) manager.getLogger(clazz);
    try {
        ISOALoggingSystemProvider logSystemProvider = SOALoggingSystemExtensionRegistry.getInstance()
                .getLoggingSystemIDProvider(PluginLogDelegateHandler.getBuildSystemName());
        if (logSystemProvider != null) {
            logSystemProvider.newLoggerCreated(logger);
        }
    } catch (Exception e) {
        //ignore the issue
        e.printStackTrace();
    }
    return logger;
}

From source file:org.echocat.jomon.runtime.logging.Slf4jUtils.java

@Nonnull
public static Installation tryInstallJulToSlf4jBridge(@Nullable ILoggerFactory loggerFactory,
        @Nullable LogManager logManager) {
    final Jul2Slf4jHandler newHandler = new Jul2Slf4jHandler(loggerFactory);
    final LogManager manager = logManager != null ? logManager : getLogManager();
    manager.reset();/*from  ww w  .jav  a 2  s .  co  m*/
    final java.util.logging.Logger logger = manager.getLogger("");
    final List<Handler> originalHandlers = new ArrayList<>();
    for (final Handler oldHandlers : logger.getHandlers()) {
        logger.removeHandler(oldHandlers);
        originalHandlers.add(newHandler);
    }
    logger.addHandler(newHandler);
    return new Jul2Slf4jInstallation(originalHandlers, newHandler, manager);
}

From source file:org.hippoecm.repository.LoggingServlet.java

/**
 * Get a sorted map with sets "logger name" => <code>LoggerLevelInfo</code>
 * @return SortedMap<String, LoggerLevelInfo>
 *//*from   ww  w .  j av a  2 s  .  co m*/
private SortedMap<String, LoggerLevelInfo> getLoggerLevelInfosMap() {
    SortedMap<String, LoggerLevelInfo> loggerLevelInfosMap = new TreeMap<String, LoggerLevelInfo>();

    if (isJDK14Log) {
        java.util.logging.LogManager manager = java.util.logging.LogManager.getLogManager();

        for (Enumeration<String> namesIter = manager.getLoggerNames(); namesIter.hasMoreElements();) {
            String loggerName = namesIter.nextElement();
            java.util.logging.Logger logger = manager.getLogger(loggerName);
            java.util.logging.Level level = logger.getLevel();
            java.util.logging.Level effectiveLevel = level;

            // try to find effective level
            if (level == null) {
                for (java.util.logging.Logger l = logger; l != null; l = l.getParent()) {
                    if (l.getLevel() != null) {
                        effectiveLevel = l.getLevel();
                        break;
                    }
                }
            }

            if (level != null) {
                loggerLevelInfosMap.put(loggerName, new LoggerLevelInfo(loggerName, level.toString()));
            } else {
                loggerLevelInfosMap.put(loggerName,
                        new LoggerLevelInfo(loggerName, null, effectiveLevel.toString()));
            }
        }
    } else if (isLog4jLog) {
        try {
            // Log4j Classes
            Class<?> loggerClass = Class.forName("org.apache.log4j.Logger");
            Class<?> managerClass = Class.forName("org.apache.log4j.LogManager");

            // Log4j Methods
            Method getName = loggerClass.getMethod("getName", null);
            Method getLevel = loggerClass.getMethod("getLevel", null);
            Method getEffectiveLevel = loggerClass.getMethod("getEffectiveLevel", null);
            Method getLoggers = managerClass.getMethod("getCurrentLoggers", null);

            // get and sort loggers and log levels
            Enumeration loggers = (Enumeration) getLoggers.invoke(null, null);

            while (loggers.hasMoreElements()) {
                try {
                    Object logger = loggers.nextElement();
                    String loggerName = (String) getName.invoke(logger, null);
                    Object level = getLevel.invoke(logger, null);
                    Object effectiveLevel = getEffectiveLevel.invoke(logger, null);

                    if (level != null) {
                        loggerLevelInfosMap.put(loggerName, new LoggerLevelInfo(loggerName, level.toString()));
                    } else {
                        loggerLevelInfosMap.put(loggerName,
                                new LoggerLevelInfo(loggerName, null, effectiveLevel.toString()));
                    }
                } catch (Exception e) {
                    log.error("Error getting logger name and level : " + e.getMessage());
                }
            }
        } catch (Exception e) {
            log.error("Error getting log4j through reflection: " + e.getMessage(), e);
        }
    }

    return loggerLevelInfosMap;
}

From source file:org.hippoecm.repository.LoggingServlet.java

/**
 * Set the logger's log level through reflection
 * @param name String the name of the logger to change
 * @param level String the new log level
 *//*  www.  ja v  a 2s .co  m*/
private void setLoggerLevel(String name, String level) {
    if (name == null || name.length() == 0) {
        log.warn("Invalid empty name. Not settting log level");
        return;
    }

    if (isJDK14Log) {
        java.util.logging.LogManager logManager = java.util.logging.LogManager.getLogManager();
        java.util.logging.Logger logger = logManager.getLogger(name);

        if (logger != null) {
            logger.setLevel(Level.parse(level));
        } else {
            log.warn("Logger not found : " + name);
        }
    } else if (isLog4jLog) {
        try {
            log.warn("Setting logger " + name + " to level " + level);

            // basic log4j reflection
            Class<?> loggerClass = Class.forName("org.apache.log4j.Logger");
            Class<?> levelClass = Class.forName("org.apache.log4j.Level");
            Class<?> logManagerClass = Class.forName("org.apache.log4j.LogManager");
            Method setLevel = loggerClass.getMethod("setLevel", levelClass);

            // get the logger
            Object logger = logManagerClass.getMethod("getLogger", String.class).invoke(null, name);

            // get the static level object field, e.g. Level.INFO
            Field levelField;
            levelField = levelClass.getField(level);
            Object levelObj = levelField.get(null);

            // set the level
            setLevel.invoke(logger, levelObj);
        } catch (NoSuchFieldException e) {
            log.warn("Unable to find Level." + level + " , not adjusting logger " + name);
        } catch (Exception e) {
            log.error("Unable to set logger " + name + " + to level " + level, e);
        }
    } else {
        log.warn("Unable to determine logger");
    }
}