All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.ovea.tadjin.util.logging.JdkOverLog4j Maven / Gradle / Ivy

The newest version!
/**
 * Copyright (C) 2011 Ovea 
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.ovea.tadjin.util.logging;

import org.apache.log4j.Level;
import org.apache.log4j.Logger;

import java.lang.reflect.Field;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Handler;
import java.util.logging.LogManager;
import java.util.logging.LogRecord;

/**
 * @author Mathieu Carbou
 */
public final class JdkOverLog4j extends Handler {

    private static final JdkOverLog4j JDK_OVER_LOG4J = new JdkOverLog4j();

    private static final Map LEVELS_JDK_TO_LOG4J = new HashMap() {
        {
            put(java.util.logging.Level.OFF, Level.OFF);
            put(java.util.logging.Level.SEVERE, Level.ERROR);
            put(java.util.logging.Level.WARNING, Level.WARN);
            put(java.util.logging.Level.INFO, Level.INFO);
            put(java.util.logging.Level.CONFIG, Level.INFO);
            put(java.util.logging.Level.FINE, Level.DEBUG);
            put(java.util.logging.Level.FINER, Level.DEBUG);
            put(java.util.logging.Level.FINEST, Level.TRACE);
            put(java.util.logging.Level.ALL, Level.ALL);
        }
    };

    private static final Map LEVELS_LOG4J_TO_JDK = new HashMap() {
        {
            put(Level.OFF, java.util.logging.Level.OFF);
            put(Level.FATAL, java.util.logging.Level.SEVERE);
            put(Level.ERROR, java.util.logging.Level.SEVERE);
            put(Level.WARN, java.util.logging.Level.WARNING);
            put(Level.INFO, java.util.logging.Level.INFO);
            put(Level.DEBUG, java.util.logging.Level.FINE);
            put(Level.TRACE, java.util.logging.Level.FINEST);
            put(Level.ALL, java.util.logging.Level.ALL);
        }
    };

    @Override
    public void publish(LogRecord record) {
        // normalize levels
        Logger log4jLogger = Logger.getLogger(record.getLoggerName());
        Level log4jLevel = log4jLogger.getEffectiveLevel();
        java.util.logging.Logger jdkLogger = java.util.logging.Logger.getLogger(record.getLoggerName());
        java.util.logging.Level expectedJdkLevel = LEVELS_LOG4J_TO_JDK.get(log4jLevel);
        if (expectedJdkLevel == null)
            throw new AssertionError("Level not supported yet - have a bug !" + log4jLevel);
        if (!expectedJdkLevel.equals(jdkLogger.getLevel())) {
            jdkLogger.setLevel(expectedJdkLevel);
        }
        log4jLogger.log(record.getLoggerName(), LEVELS_JDK_TO_LOG4J.get(record.getLevel()), record.getMessage(), record.getThrown());
    }

    @Override
    public void flush() {
    }

    @Override
    public void close() throws SecurityException {
    }

    public static void install() {
        // force init
        LogManager.getLogManager().getLogger("");
        Logger.getRootLogger();
        // replace JDK log manager
        try {
            Field manager = LogManager.class.getDeclaredField("manager");
            manager.setAccessible(true);
            manager.set(null, new Log4JLogManager());
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage(), e);
        }
        // reset jdk log manager
        LogManager.getLogManager().getLogger("").addHandler(JDK_OVER_LOG4J);
        Enumeration names = LogManager.getLogManager().getLoggerNames();
        while (names.hasMoreElements()) {
            java.util.logging.Logger logger = LogManager.getLogManager().getLogger(names.nextElement());
            for (Handler handler : logger.getHandlers()) {
                logger.removeHandler(handler);
            }
            logger.setLevel(LEVELS_LOG4J_TO_JDK.get(Logger.getLogger(logger.getName()).getEffectiveLevel()));
            logger.addHandler(JDK_OVER_LOG4J);
        }
    }

    private static final class Log4JLogManager extends LogManager {
        @Override
        public synchronized java.util.logging.Logger getLogger(String name) {

            final Logger log4jLogger = Logger.getLogger(name);
            final int off = java.util.logging.Level.OFF.intValue();

            java.util.logging.Logger logger = new java.util.logging.Logger(name, null) {
                @Override
                public boolean isLoggable(java.util.logging.Level level) {
                    int jdkLevel = getLevel().intValue();
                    return !(level.intValue() < jdkLevel || jdkLevel == off);
                }

                @Override
                public void setLevel(java.util.logging.Level newLevel) throws SecurityException {
                    log4jLogger.setLevel(LEVELS_JDK_TO_LOG4J.get(newLevel));
                    super.setLevel(newLevel);
                }

                @Override
                public java.util.logging.Level getLevel() {
                    java.util.logging.Level current = LEVELS_LOG4J_TO_JDK.get(log4jLogger.getEffectiveLevel());
                    if (current != super.getLevel()) {
                        super.setLevel(current);
                    }
                    return current;
                }

                @Override
                public void addHandler(Handler handler) throws SecurityException {
                    Handler[] hs = getHandlers();
                    if (hs.length != 1 || hs[0] != JDK_OVER_LOG4J) {
                        for (Handler h : hs) {
                            super.removeHandler(h);
                        }
                        super.addHandler(JDK_OVER_LOG4J);
                    }
                }

                @Override
                public void log(java.util.logging.Level level, String msg) {
                    if (isLoggable(level))
                        super.log(level, msg);
                }

                @Override
                public void log(java.util.logging.Level level, String msg, Object param1) {
                    if (isLoggable(level))
                        super.log(level, msg, param1);
                }

                @Override
                public void log(java.util.logging.Level level, String msg, Object[] params) {
                    if (isLoggable(level))
                        super.log(level, msg, params);
                }

                @Override
                public void log(java.util.logging.Level level, String msg, Throwable thrown) {
                    if (isLoggable(level))
                        super.log(level, msg, thrown);
                }

                @Override
                public void log(LogRecord record) {
                    if (isLoggable(record.getLevel()))
                        super.log(record);
                }

                @Override
                public void logp(java.util.logging.Level level, String sourceClass, String sourceMethod, String msg) {
                    if (isLoggable(level))
                        super.logp(level, sourceClass, sourceMethod, msg);
                }

                @Override
                public void logp(java.util.logging.Level level, String sourceClass, String sourceMethod, String msg, Object param1) {
                    if (isLoggable(level))
                        super.logp(level, sourceClass, sourceMethod, msg, param1);
                }

                @Override
                public void logp(java.util.logging.Level level, String sourceClass, String sourceMethod, String msg, Object[] params) {
                    if (isLoggable(level))
                        super.logp(level, sourceClass, sourceMethod, msg, params);
                }

                @Override
                public void logp(java.util.logging.Level level, String sourceClass, String sourceMethod, String msg, Throwable thrown) {
                    if (isLoggable(level))
                        super.logp(level, sourceClass, sourceMethod, msg, thrown);
                }

                @Override
                public void logrb(java.util.logging.Level level, String sourceClass, String sourceMethod, String bundleName, String msg) {
                    if (isLoggable(level))
                        super.logrb(level, sourceClass, sourceMethod, bundleName, msg);
                }

                @Override
                public void logrb(java.util.logging.Level level, String sourceClass, String sourceMethod, String bundleName, String msg, Object param1) {
                    if (isLoggable(level))
                        super.logrb(level, sourceClass, sourceMethod, bundleName, msg, param1);
                }

                @Override
                public void logrb(java.util.logging.Level level, String sourceClass, String sourceMethod, String bundleName, String msg, Object[] params) {
                    if (isLoggable(level))
                        super.logrb(level, sourceClass, sourceMethod, bundleName, msg, params);
                }

                @Override
                public void logrb(java.util.logging.Level level, String sourceClass, String sourceMethod, String bundleName, String msg, Throwable thrown) {
                    if (isLoggable(level))
                        super.logrb(level, sourceClass, sourceMethod, bundleName, msg, thrown);
                }
            };
            logger.addHandler(JDK_OVER_LOG4J);
            logger.setLevel(LEVELS_LOG4J_TO_JDK.get(log4jLogger.getEffectiveLevel()));
            return logger;
        }
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy