欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

动态生成Log

程序员文章站 2022-07-14 12:27:56
...

我们在项目中可能需要一些日志文件。是动态生成的(配置文件是静态的,打印全局的log)。比如我们按照类别来收集用户输入的内容。一个类别一天一个文件。 这时候就可以用代码调用Log4j来生成

 

我们先自定义的LogFactory

package com.bj58.zhaoren.sou.utils;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.log4j.DailyRollingFileAppender;
import org.apache.log4j.Layout;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.log4j.PatternLayout;
import org.apache.log4j.spi.LoggerFactory;

/**
 * 自定义日志工厂
 * @date 2016年3月24日  
 * @author shencl
 */
public class MyLogFactory implements LoggerFactory {
	
	private static Map<String, MyLogFactory> map = new ConcurrentHashMap<String, MyLogFactory>(); 

	private String path;

	private MyLogFactory() {
	}
	
	private MyLogFactory(String path) {
		this.path = path;
	}

	/**
	 * 保证一个路径只产生一个MyLogFactory
	 */
	public synchronized static MyLogFactory getInstance(String path){
		if (map.get(path) != null) {  
            return map.get(path);  
        }  
		return new MyLogFactory(path);
	}
	
	@Override
	public Logger makeNewLoggerInstance(String name) {
		Logger log = Logger.getLogger(name);
		log.setLevel(Level.INFO);
		Layout layout = new PatternLayout("[%d{MM-dd HH:mm:ss,SSS}] %c{10} - %m%n");
		try {
			if (path != null && !path.equals("")) {
				DailyRollingFileAppender fileappender = new DailyRollingFileAppender(layout, path, "'.'yyyy-MM-dd");
				log.addAppender(fileappender);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return log;
	}
}

 

然后看怎么调用

package com.bj58.zhaoren.sou.utils;

import org.apache.log4j.Logger;

/**
 * @author shencl
 */
public class LogTest {
	private static String path = "d:/logs/query/skill.log";
	
	public static void main(String[] args) {
		Logger l = Logger.getLogger(LogTest.class.getName(), MyLogFactory.getInstance(path));
		l.info("aaaaa");
	}
}

 

日志文件在 D:\logs\query\skill.log

输出      [03-15 11:31:23,131] com.bj58.zhaoren.sou.utils.LogTest - aaaaa