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

org.zodiac.sdk.log.factory.LogbackLoggerSpaceFactory Maven / Gradle / Ivy

The newest version!
package org.zodiac.sdk.log.factory;

import ch.qos.logback.classic.encoder.PatternLayoutEncoder;
import ch.qos.logback.classic.filter.ThresholdFilter;

import org.zodiac.sdk.log.CommonLoggingConfigurations;
import org.zodiac.sdk.log.adapter.level.AdapterLevel;
import org.zodiac.sdk.log.constants.LogConstants;
import org.zodiac.sdk.toolkit.space.SpaceId;
import org.zodiac.sdk.toolkit.util.lang.StrUtil;

import java.net.URL;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

public class LogbackLoggerSpaceFactory extends AbstractLoggerSpaceFactory {

    private SpaceId spaceId;
    private ch.qos.logback.classic.LoggerContext loggerContext;
    private Properties properties;

    /**
     * key: spanId, value: consoleAppender each logger have their own consoleAppender if had configured.
     **/
    private ConcurrentMap> consoleAppenders = new ConcurrentHashMap<>();

    public LogbackLoggerSpaceFactory(SpaceId spaceId, ch.qos.logback.classic.LoggerContext loggerContext, Properties properties, URL confFile,
        String source) {
        super(source);
        this.spaceId = spaceId;
        this.loggerContext = loggerContext;
        this.properties = properties;

        for (Map.Entry entry : properties.entrySet()) {
            loggerContext.putProperty((String)entry.getKey(), (String)entry.getValue());
        }
        try {
            new ch.qos.logback.classic.util.ContextInitializer(loggerContext).configureByResource(confFile);
        } catch (ch.qos.logback.core.joran.spi.JoranException e) {
            throw new IllegalStateException("Logback loggerSpaceFactory build error", e);
        }

        String value = properties
            .getProperty(String.format(LogConstants.PLATFORM_SINGLE_LOG_CONSOLE_SWITCH, spaceId.getSpaceName()));
        if (StrUtil.isEmpty(value)) {
            value = properties.getProperty(LogConstants.PLATFORM_ALL_LOG_CONSOLE_SWITCH);
        }
        if (Boolean.TRUE.toString().equalsIgnoreCase(value)) {
            loggerContext.addTurboFilter(new ch.qos.logback.classic.turbo.TurboFilter() {
                @Override
                public ch.qos.logback.core.spi.FilterReply decide(org.slf4j.Marker marker, ch.qos.logback.classic.Logger logger, ch.qos.logback.classic.Level level,
                    String format, Object[] params, Throwable t) {
                    ch.qos.logback.core.ConsoleAppender consoleAppender = getOrCreateConsoleAppender(logger.getName());
                    if (CommonLoggingConfigurations.shouldAttachConsoleAppender(logger.getName())
                        && !logger.isAttached(consoleAppender)) {
                        logger.addAppender(consoleAppender);
                    }
                    return ch.qos.logback.core.spi.FilterReply.NEUTRAL;
                }
            });
        }
    }

    private ch.qos.logback.core.ConsoleAppender getOrCreateConsoleAppender(String loggerName) {
        return consoleAppenders.computeIfAbsent(loggerName, k -> {
            ch.qos.logback.core.ConsoleAppender appender = new ch.qos.logback.core.ConsoleAppender<>();
            PatternLayoutEncoder encoder = new PatternLayoutEncoder();
            String logPattern = properties.getProperty(LogConstants.PLATFORM_LOG_CONSOLE_LOGBACK_PATTERN,
                LogConstants.PLATFORM_LOG_CONSOLE_LOGBACK_PATTERN_DEFAULT);
            /*Create appender filter.*/
            ch.qos.logback.classic.Level consoleLevel = getConsoleLevel(spaceId.getSpaceName());
            ThresholdFilter filter = new ThresholdFilter();
            filter.setLevel(consoleLevel.toString());

            encoder.setPattern(ch.qos.logback.core.util.OptionHelper.substVars(logPattern, loggerContext));
            encoder.setContext(loggerContext);
            encoder.start();
            appender.setEncoder(encoder);
            appender.setName(CONSOLE);
            filter.start();
            appender.addFilter(filter);
            appender.start();
            return appender;
        });
    }

    public SpaceId getSpaceId() {
        return spaceId;
    }

    public Properties getProperties() {
        return properties;
    }

    private ch.qos.logback.classic.Level getConsoleLevel(String spaceId) {
        String defaultLevel = properties.getProperty(LogConstants.PLATFORM_ALL_LOG_CONSOLE_LEVEL, "INFO");
        String level = properties
            .getProperty(String.format(LogConstants.PLATFORM_SINGLE_LOG_CONSOLE_LEVEL, spaceId), defaultLevel);
        return ch.qos.logback.classic.Level.toLevel(level, ch.qos.logback.classic.Level.INFO);
    }

    @Override
    public org.slf4j.Logger getLogger(String name) {
        return loggerContext.getLogger(name);
    }

    @Override
    public org.slf4j.Logger setLevel(String loggerName, AdapterLevel adapterLevel) {
        ch.qos.logback.classic.Logger logbackLogger = (ch.qos.logback.classic.Logger)this.getLogger(loggerName);
        ch.qos.logback.classic.Level logbackLevel = this.toLogbackLevel(adapterLevel);
        logbackLogger.setLevel(logbackLevel);
        return logbackLogger;
    }

    private ch.qos.logback.classic.Level toLogbackLevel(AdapterLevel adapterLevel) {
        if (adapterLevel == null) {
            throw new IllegalStateException("AdapterLevel is NULL when adapter to logback.");
        }
        switch (adapterLevel) {
            case TRACE:
                return ch.qos.logback.classic.Level.TRACE;
            case DEBUG:
                return ch.qos.logback.classic.Level.DEBUG;
            case INFO:
                return ch.qos.logback.classic.Level.INFO;
            case WARN:
                return ch.qos.logback.classic.Level.WARN;
            case ERROR:
                return ch.qos.logback.classic.Level.ERROR;
            default:
                throw new IllegalStateException(adapterLevel + " is unknown when adapter to logback.");
        }
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy