问题描述
比如我有两个用户A和B,我需要记录这两个用户的操作信息:add和del。我希望把A的日志存放到logs/A/**目录下,比如logs/A/add/add.loglogs/A/add/del.log我希望把B的日志存放到logs/B/**目录下,比如logs/B/add/add.loglogs/B/add/del.log当程序在记录日志时,知道用户是谁。如何在记录日志时,让程序根据用户来选择日志存放目录?log4j支持这样的功能吗,能否给出简明的log4j配置。在此谢谢各位~
解决方案
可以的:package com.ljn.others;import java.io.IOException;import java.util.HashMap;import java.util.Map;import org.apache.commons.lang.StringUtils;import org.apache.log4j.Level;import org.apache.log4j.Logger;import org.apache.log4j.PatternLayout;import org.apache.log4j.RollingFileAppender;import org.apache.log4j.varia.LevelRangeFilter;/** * @author lijinnan * @date:2014-5-7 */public class LoggerFactory { private static final String SEPARATOR = "/"; private static final Map<String, Logger> logMap = new HashMap<String, Logger>(); public static Logger getLogger(String baseDir, String userName, String fileName) { if (StringUtils.isEmpty(baseDir) || StringUtils.isEmpty(userName) || StringUtils.isEmpty(fileName)) { throw new IllegalArgumentException("cannot be empty"); } String key = findKey(userName, fileName); Logger logger = logMap.get(key); if (logger == null) try { String logFilePath = baseDir + SEPARATOR + key; logger = Logger.getLogger(key); PatternLayout playout = new PatternLayout(); playout.setConversionPattern("%d{[yyyy-MM-dd HH:mm:ss.SSS]}:[%p] %m%n"); RollingFileAppender fAppender = new RollingFileAppender(playout, logFilePath); fAppender.setMaxFileSize("500MB"); fAppender.setMaxBackupIndex(3); fAppender.setAppend(true); fAppender.setThreshold(Level.INFO); fAppender.setLayout(playout); LevelRangeFilter filterInfo = new LevelRangeFilter(); filterInfo.setLevelMin(Level.INFO); filterInfo.setLevelMax(Level.ERROR); fAppender.addFilter(filterInfo); logger.addAppender(fAppender); logMap.put(key, logger); } catch (IOException e) { logger.error(Thread.currentThread().getName(), e); } return logger; } private static String findKey(String userName, String fileName) { return userName + SEPARATOR + fileName; }}package com.ljn.others;import java.util.Random;import org.apache.log4j.Logger;/** * @author lijinnan */public class UserService { private static final String BASE_DIR = "d:/odd/log"; public static void main(String[] args) { while(true) { add(); del(); System.out.println("ok"); } } public static void add() { String user = getCurrentUser(); Logger logger = LoggerFactory.getLogger(BASE_DIR, user, "add.log"); logger.info(user + " add"); } public static void del() { String user = getCurrentUser(); Logger logger = LoggerFactory.getLogger(BASE_DIR, user, "del.log"); logger.info(user + " del"); } private static String getCurrentUser() { Random random = new Random(); int i = random.nextInt(10); if (i % 2 == 0) { return "A" ; } return "B"; }}