比如现在系统会给多个公司发送数据,现希望给每个公司的数据有单独的日志文件记录。由于公司名字是动态的没法在log4j配置文件中写死,这时就只能通过动态创建了。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
/**
 * Created by Administrator on 2017/12/10.
 */
public final class Log4jUtil {
    private final static ConcurrentHashMap<String,Logger> loggerMap = new ConcurrentHashMap<String, Logger>();
    public static Logger getLogger(String name) {
        Logger logger = loggerMap.get(name);
        if (null != logger) {
            return logger;
        }
        return createNewLogger(name);
    }
    private static Logger createNewLogger(String name) {
        Logger logger = Logger.getLogger(name);
        logger.removeAllAppenders();
        logger.setLevel(Level.DEBUG);
        logger.setAdditivity(false);
        RollingFileAppender appender = new RollingFileAppender();
        PatternLayout layout = new PatternLayout();
        String conversionPatten = "[%d] %p %t %c - %m%n";
        layout.setConversionPattern(conversionPatten);
        appender.setLayout(layout);
        String basePath = "/usr/logs/rb/";
        appender.setFile(basePath + name + ".log");
        appender.setEncoding("utf-8");
        appender.setMaxBackupIndex(10);
        appender.setMaxFileSize("50MB");
        appender.setAppend(true);
        appender.activateOptions();
        logger.addAppender(appender);
        loggerMap.put(name,logger);
        return logger;
    }
}

测试代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
/**
 * 动态生成日志文件名。
 * Created by Administrator on 2017/12/10.
 */
public class DynamicLogFileName {
    public static void main(String[] args) {
        LogTestThread ltt1 = new LogTestThread("test1");
        LogTestThread ltt2 = new LogTestThread("test2");
        ltt1.start();
        ltt2.start();
    }
}
class LogTestThread extends Thread {
    private String name;
    public LogTestThread(String name) {
        this.name = name;
    }
    public void run() {
        Logger logger = Log4jUtil.getLogger(this.name);
        for (int i=0;i<10;i++) {
            try {
                Thread.sleep((long) (Math.random()*1500L+1000L));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            logger.info(this.getName() + " msg." + i);
        }
    }
}