当前位置: 首页 > 工具软件 > common-tools > 使用案例 >

使用sofa-common-tools自定义日志

祖翰音
2023-12-01

项目中我们可能需要重新定义一些 log 规则,也不想沿用已有的日志配置文件。此时就需要自定义日志配置文件,并加载,sofa-common-tools 提供了这样的工具。

引入依赖:

        <dependency>
            <groupId>com.alipay.sofa.common</groupId>
            <artifactId>sofa-common-tools</artifactId>
            <version>1.0.19</version>
        </dependency>

新建如下内容:

--- com.zero
    \- log
    |     \- log4j2
    |     |       \-log-conf.xml
    |     |- log4j
    |     |       \-log-conf.xml
    |     \- logback
    |             \-log-conf.xml
    |-MyLogger.java
    |-MyLoggerFactory.java

log-conf.xml里面对应各种实现的日志配置。

MyLogger.java和MyLoggerFactory.java如下:

package com.zero.log;

import org.slf4j.Logger;
import java.io.File;

public class MyLogger {
    private static Logger monitorLog;

    private static volatile boolean inited;

    private static final String LOG_PATH = "logging.path";
    private static final String LOG_PATH_DEFAULT = System.getProperty("user.home") + File.separator
            + "logs";

    static {
        init();
        monitorLog = createLogger("monitor");
    }

    public static void init() {
        if (!inited) {
            inited = true;
            initProperties();
        }
    }

    private static void initProperties() {
        String logPath = System.getProperty(LOG_PATH, LOG_PATH_DEFAULT);
    }

    private static Logger createLogger(final String loggerName) {
        return MyLoggerFactory.getLogger(loggerName);
    }

    public static Logger getMonitorLog() {
        return monitorLog;
    }
}

package com.zero.log;

import com.alipay.sofa.common.log.LoggerSpaceManager;
import org.slf4j.Logger;

public class MyLoggerFactory {
    /** 实际生效的LogSpace */
    private static String currentSpace = null;

    static {
        currentSpace = "com.zero";
    }

    public static Logger getLogger(Class<?> clazz) {
        if (clazz == null) {
            return null;
        }
        return getLogger(clazz.getCanonicalName());
    }

    public static Logger getLogger(String name) {
        if (name == null || name.isEmpty()) {
            return null;
        }
        Logger logger = LoggerSpaceManager.getLoggerBySpace(name, currentSpace);
        return logger;
    }

    public static String getCurrentSpace() {
        return currentSpace;
    }
}

sofa里面实现原理是,根据 currentSpace 即 com.zero 和项目里面的日志框架实现,去找 com/zero/log/目录下面的日志配置文件。如果是log4j2则加载com/zero/log/log4j2/log-conf.xml这个日志配置文件。

注意项目打包时要下如下配置,否则 com/zero/log/里面的*.xml不会打入到jar包:

    <build>
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
            </resource>
            <resource>
                <directory>src/main/resources</directory>
            </resource>
        </resources>
    </build>
 类似资料: