Freemarker源码分析(6)log包中的类

本文详细分析了Freemarker框架中的log包,主要关注Logger抽象类和LoggerFactory接口。Logger类包含各种日志级别的抽象方法,并定义了日志库选择的常量。LoggerFactory接口则负责创建日志记录器。代码展示了如何根据系统属性或默认顺序选择日志库,如Log4J、JUL等,并在无法设置日志库时进行错误处理。
摘要由CSDN通过智能技术生成

2021SC@SDUSC

Freemarker源码分析(6)log包中的类

log包中的类大部分为弃用或者只在内部使用的类,余下的是抽象类Logger与接口LoggerFactory,两者不分开说明展示代码后共同说明
两者的结构:
抽象类Logger与接口LoggerFactory
(其中划掉的属性与方法为已弃用)
Logger代码:

public abstract class Logger {

    public static final String SYSTEM_PROPERTY_NAME_LOGGER_LIBRARY = "org.freemarker.loggerLibrary";

    public static final int LIBRARY_AUTO = -1;
    private static final int MIN_LIBRARY_ENUM = LIBRARY_AUTO;

    public static final String LIBRARY_NAME_AUTO = "auto";

    public static final int LIBRARY_NONE = 0;

    public static final String LIBRARY_NAME_NONE = "none";

    public static final int LIBRARY_JAVA = 1;

    public static final String LIBRARY_NAME_JUL = "JUL";

    @Deprecated
    public static final int LIBRARY_AVALON = 2;

    @Deprecated
    public static final String LIBRARY_NAME_AVALON = "Avalon";

    public static final int LIBRARY_LOG4J = 3;

    // This value is also used as part of the factory class name.
    public static final String LIBRARY_NAME_LOG4J = "Log4j";

    public static final int LIBRARY_COMMONS = 4;

    // This value is also used as part of the factory class name.
    public static final String LIBRARY_NAME_COMMONS_LOGGING = "CommonsLogging";

    /**
     * Constant used with {@link #selectLoggerLibrary(int)}; indicates that SLF4J should be used.
     */
    public static final int LIBRARY_SLF4J = 5;

    // This value is also used as part of the factory class name.
    public static final String LIBRARY_NAME_SLF4J = "SLF4J";
    private static final int MAX_LIBRARY_ENUM = LIBRARY_SLF4J;

    private static final String REAL_LOG4J_PRESENCE_CLASS = "org.apache.log4j.FileAppender";
    private static final String LOG4J_OVER_SLF4J_TESTER_CLASS = "freemarker.log._Log4jOverSLF4JTester";

    /**
     * Order matters! Starts with the lowest priority.
     */
    private static final String[] LIBRARIES_BY_PRIORITY = {
            null, LIBRARY_NAME_JUL,
            "org.apache.log.Logger", LIBRARY_NAME_AVALON,
            "org.apache.log4j.Logger", LIBRARY_NAME_LOG4J,
            /* In 2.3.x this two is skipped by LIBRARY_AUTO: */
            "org.apache.commons.logging.Log", LIBRARY_NAME_COMMONS_LOGGING,
            "org.slf4j.Logger", LIBRARY_NAME_SLF4J,
    };

    private static String getAvailabilityCheckClassName(int libraryEnum) {
        if (libraryEnum == LIBRARY_AUTO || libraryEnum == LIBRARY_NONE) {
            // Statically linked
            return null;
        }
        return LIBRARIES_BY_PRIORITY[(libraryEnum - 1) * 2];
    }

    static {
        if (LIBRARIES_BY_PRIORITY.length / 2 != MAX_LIBRARY_ENUM) {
            throw new AssertionError();
        }
    }

    private static String getLibraryName(int libraryEnum) {
        if (libraryEnum == LIBRARY_AUTO) {
            return LIBRARY_NAME_AUTO;
        }
        if (libraryEnum == LIBRARY_NONE) {
            return LIBRARY_NAME_NONE;
        }
        return LIBRARIES_BY_PRIORITY[(libraryEnum - 1) * 2 + 1];
    }

    private static boolean isAutoDetected(int libraryEnum) {
        // 2.4: Remove libraryEnum == LIBRARY_SLF4J || libraryEnum == LIBRARY_COMMONS
        return !(libraryEnum == LIBRARY_AUTO || libraryEnum == LIBRARY_NONE
                || libraryEnum == LIBRARY_SLF4J || libraryEnum == LIBRARY_COMMONS);
    }

    private static int libraryEnum;
    private static LoggerFactory loggerFactory;
    private static boolean initializedFromSystemProperty;

    private static String categoryPrefix = "";

    private static final Map loggersByCategory = new HashMap();

    @Deprecated
    public static void selectLoggerLibrary(int libraryEnum) throws ClassNotFoundException {
        if (libraryEnum < MIN_LIBRARY_ENUM || libraryEnum > MAX_LIBRARY_ENUM) {
            throw new IllegalArgumentException("Library enum value out of range");
        }

        synchronized (Logger.class) {
            final boolean loggerFactoryWasAlreadySet = loggerFactory != null;
            if (!loggerFactoryWasAlreadySet || libraryEnum != Logger.libraryEnum) {
                // Creates the factory only if it can be done based on system property:
                ensureLoggerFactorySet(true);

                // The system property has precedence because this method was deprecated by it:
                if (!initializedFromSystemProperty || loggerFactory == null) {
                    int replacedLibraryEnum = Logger.libraryEnum;
                    setLibrary(libraryEnum);
                    loggersByCategory.clear();
                    if (loggerFactoryWasAlreadySet) {
                        logWarnInLogger("Logger library was already set earlier to \""
                                + getLibraryName(replacedLibraryEnum) + "\"; "
                                + "change to \"" + getLibraryName(libraryEnum) + "\" won't effect loggers created "
                                + "earlier.");
                    }
                } else if (libraryEnum != Logger.libraryEnum) {
                    logWarnInLogger("Ignored " + Logger.class.getName() + ".selectLoggerLibrary(\""
                            + getLibraryName(libraryEnum)
                            + "\") call, because the \"" + SYSTEM_PROPERTY_NAME_LOGGER_LIBRARY
                            + "\" system property is set to \"" + getLibraryName(Logger.libraryEnum) + "\".");
                }
            }
        }
    }

    @Deprecated
    public static void setCategoryPrefix(String prefix) {
        synchronized (Logger.class) {
            if (prefix == null) {
                throw new IllegalArgumentException();
            }
            categoryPrefix = prefix;
        }
    }

    /**
     * Logs a debugging message.
     */
    public abstract void debug(String message);

    /**
     * Logs a debugging message with accompanying throwable.
     */
    public abstract void debug(String message, Throwable t);

    /**
     * Logs an informational message.
     */
    public abstract void info(String message);

    /**
     * Logs an informational message with accompanying throwable.
     */
    public abstract void info(String message, Throwable t);

    /**
     * Logs a warning message.
     */
    public abstract void warn(String message);

    /**
     * Logs a warning message with accompanying throwable.
     */
    public abstract void warn(String message, Throwable t);

    /**
     * Logs an error message.
     */
    public abstract void error(String message);

    /**
     * Logs an error message with accompanying throwable.
     */
    public abstract void error(String message, Throwable t);

    /**
     * Returns true if this logger will log debug messages.
     */
    public abstract boolean isDebugEnabled();

    /**
     * Returns true if this logger will log informational messages.
     */
    public abstract boolean isInfoEnabled();

    /**
     * Returns true if this logger will log warning messages.
     */
    public abstract boolean isWarnEnabled();

    /**
     * Returns true if this logger will log error messages.
     */
    public abstract boolean isErrorEnabled();

    /**
     * Returns true if this logger will log fatal error messages.
     */
    public abstract boolean isFatalEnabled();

    public static Logger getLogger(String category) {
        if (categoryPrefix.length() != 0) {
            category = categoryPrefix + category;
        }
        synchronized (loggersByCategory) {
            Logger logger = (Logger) loggersByCategory.get(category);
            if (logger == null) {
                ensureLoggerFactorySet(false);
                logger = loggerFactory.getLogger(category);
                loggersByCategory.put(category, logger);
            }
            return logger;
        }
    }

    private static void ensureLoggerFactorySet(boolean onlyIfCanBeSetFromSysProp) {
        if (loggerFactory != null) return;
        synchronized (Logger.class) {
            if (loggerFactory != null) return;

            String sysPropVal = getSystemProperty(SYSTEM_PROPERTY_NAME_LOGGER_LIBRARY);

            final int libraryEnum;
            if (sysPropVal != null) {
                sysPropVal = sysPropVal.trim();

                boolean foundMatch = false;
                int matchedEnum = MIN_LIBRARY_ENUM;
                do {
                    if (sysPropVal.equalsIgnoreCase(getLibraryName(matchedEnum))) {
                        foundMatch = true;
                    } else {
                        matchedEnum++;
                    }
                } while (matchedEnum <= MAX_LIBRARY_ENUM && !foundMatch);

                if (!foundMatch) {
                    logWarnInLogger("Ignored invalid \"" + SYSTEM_PROPERTY_NAME_LOGGER_LIBRARY
                            + "\" system property value: \"" + sysPropVal + "\"");
                    if (onlyIfCanBeSetFromSysProp) return;
                }

                libraryEnum = foundMatch ? matchedEnum : LIBRARY_AUTO;
            } else {
                if (onlyIfCanBeSetFromSysProp) return;
                libraryEnum = LIBRARY_AUTO;
            }

            try {
                setLibrary(libraryEnum);
                if (sysPropVal != null) {
                    initializedFromSystemProperty = true;
                }
            } catch (Throwable e) {
                final boolean disableLogging = !(onlyIfCanBeSetFromSysProp && sysPropVal != null);
                logErrorInLogger(
                        "Couldn't set up logger for \"" + getLibraryName(libraryEnum) + "\""
                                + (disableLogging ? "; logging disabled" : "."), e);
                if (disableLogging) {
                    try {
                        setLibrary(LIBRARY_NONE);
                    } catch (ClassNotFoundException e2) {
                        throw new RuntimeException("Bug", e2);
                    }
                }
            }
        }
    }

    private static LoggerFactory createLoggerFactory(int libraryEnum) throws ClassNotFoundException {
        if (libraryEnum == LIBRARY_AUTO) {
            for (int libraryEnumToTry = MAX_LIBRARY_ENUM; libraryEnumToTry >= MIN_LIBRARY_ENUM; libraryEnumToTry--) {
                if (!isAutoDetected(libraryEnumToTry)) continue;
                if (libraryEnumToTry == LIBRARY_LOG4J && hasLog4LibraryThatDelegatesToWorkingSLF4J()) {
                    libraryEnumToTry = LIBRARY_SLF4J;
                }

                try {
                    return createLoggerFactoryForNonAuto(libraryEnumToTry);
                } catch (ClassNotFoundException e) {
                    // Expected, intentionally suppressed.
                } catch (Throwable e) {
                    logErrorInLogger(
                            "Unexpected error when initializing logging for \""
                                    + getLibraryName(libraryEnumToTry) + "\".",
                            e);
                }
            }
            logWarnInLogger("Auto detecton couldn't set up any logger libraries; FreeMarker logging suppressed.");
            return new _NullLoggerFactory();
        } else {
            return createLoggerFactoryForNonAuto(libraryEnum);
        }
    }

    private static LoggerFactory createLoggerFactoryForNonAuto(int libraryEnum) throws ClassNotFoundException {
        final String availabilityCheckClassName = getAvailabilityCheckClassName(libraryEnum);
        if (availabilityCheckClassName != null) { // Dynamically created factory
            Class.forName(availabilityCheckClassName);
            String libraryName = getLibraryName(libraryEnum);
            try {
                return (LoggerFactory) Class.forName(
                        "freemarker.log._" + libraryName + "LoggerFactory").newInstance();
            } catch (Exception e) {
                throw new RuntimeException(
                        "Unexpected error when creating logger factory for \"" + libraryName + "\".", e);
            }
        } else { // Non-dynamically created factory
            if (libraryEnum == LIBRARY_JAVA) {
                return new _JULLoggerFactory();
            } else if (libraryEnum == LIBRARY_NONE) {
                return new _NullLoggerFactory();
            } else {
                throw new RuntimeException("Bug");
            }
        }
    }

    private static boolean hasLog4LibraryThatDelegatesToWorkingSLF4J() {
        try {
            Class.forName(getAvailabilityCheckClassName(LIBRARY_LOG4J));
            Class.forName(getAvailabilityCheckClassName(LIBRARY_SLF4J));
        } catch (Throwable e) {
            return false;
        }
        try {
            Class.forName(REAL_LOG4J_PRESENCE_CLASS);
            return false;
        } catch (ClassNotFoundException e) {
            try {
                Object r = Class.forName(LOG4J_OVER_SLF4J_TESTER_CLASS)
                        .getMethod("test", new Class[] {}).invoke(null);
                return ((Boolean) r).booleanValue();
            } catch (Throwable e2) {
                return false;
            }
        }
    }

    private synchronized static void setLibrary(int libraryEnum) throws ClassNotFoundException {
        loggerFactory = createLoggerFactory(libraryEnum);
        Logger.libraryEnum = libraryEnum;
    }

    private static void logWarnInLogger(String message) {
        logInLogger(false, message, null);
    }

    private static void logErrorInLogger(String message, Throwable exception) {
        logInLogger(true, message, exception);
    }

    private static void logInLogger(boolean error, String message, Throwable exception) {
        boolean canUseRealLogger;
        synchronized (Logger.class) {
            canUseRealLogger = loggerFactory != null && !(loggerFactory instanceof _NullLoggerFactory);
        }

        if (canUseRealLogger) {
            try {
                final Logger logger = Logger.getLogger("freemarker.logger");
                if (error) {
                    logger.error(message);
                } else {
                    logger.warn(message);
                }
            } catch (Throwable e) {
                canUseRealLogger = false;
            }
        }

        if (!canUseRealLogger) {
            System.err.println((error ? "ERROR" : "WARN") + " "
                    + LoggerFactory.class.getName() + ": " + message);
            if (exception != null) {
                System.err.println("\tException: " + tryToString(exception));
                while (exception.getCause() != null) {
                    exception = exception.getCause();
                    System.err.println("\tCaused by: " + tryToString(exception));
                }
            }
        }
    }

    private static String getSystemProperty(final String key) {
        try {
            return (String) AccessController.doPrivileged(
                    new PrivilegedAction() {
                        @Override
                        public Object run() {
                            return System.getProperty(key, null);
                        }
                    });
        } catch (AccessControlException e) {
            logWarnInLogger("Insufficient permissions to read system property \"" + key + "\".");
            return null;
        } catch (Throwable e) {
            logErrorInLogger("Failed to read system property \"" + key + "\".", e);
            return null;
        }
    }

    private static String tryToString(Object object) {
        if (object == null) return null;
        try {
            return object.toString();
        } catch (Throwable e) {
            return object.getClass().getName();
        }
    }

}

LoggerFactory代码:

interface LoggerFactory {
    public Logger getLogger(String category);
}

这是freemarker本身自带的日志库,用于生成日志库。将日志记录器的创建委托给实际的日志记录库。默认情况下,它按照如下顺序查找日志程序库(在FreeMarker 3.x中):Log4J、Avalon LogKit、JUL(即java.util.logging)。

注:Freemarker代码来自FreeMarker 中文官方参考手册

新手写的代码分析,文章若有错误还请指出

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值