Maven项目 Log4j 配置及日志输出到相对路径

1.Maven pom.xml 配置log4j依赖

    
     log4j
     log4j
     1.2.17
    

正确添加依赖后Maven会自动从本地仓库或者远程仓库加载log4j及其依赖的jar包

如果加载完成后项目出现红色感叹号提示

一般表示Maven加载的jar包出现问题,此时在Eclipse的window/Problems视图下查看有哪些jar包出现问题

下载正确的jar包后替换本地仓库相应的jar包即可解决


2.创建log4j配置文件 log4j.properties

log4j.rootLogger = info,A,B

log4j.appender.A = org.apache.log4j.DailyRollingFileAppender
log4j.appender.A.File = ${logPath}\\log.log
log4j.appender.A.Append = true
log4j.appender.A.Threshold = info
log4j.appender.A.DatePattern ='.'yyyy-MM-dd
log4j.appender.A.layout = org.apache.log4j.PatternLayout
log4j.appender.A.layout.ConversionPattern = %d %l - %msg%n

log4j.appender.B = org.apache.log4j.DailyRollingFileAppender
log4j.appender.B.File =${logPath}\\error.log
log4j.appender.B.DatePattern ='.'yyyy-MM-dd
log4j.appender.B.Append = true
log4j.appender.B.Threshold = ERROR
log4j.appender.B.layout = org.apache.log4j.PatternLayout
log4j.appender.B.layout.ConversionPattern = %d %l - %msg%n

在上述代码块中定义了两种log配置

A配置输出到相对路径的log.log文件,用来保存程序运行的info级别日志

B配置输出到相对路径的error.log文件,用来保存程序运行的error级别日志


3.创建程序配置文件实现动态获取相对路径

application.properties

# The logPath when program running 
log-folder=log

4.代码中动态配置路径

public class LogConfig {
	
	private static Logger logger = LogManager.getLogger(LogConfig.class);
	
	private LogConfig(){
	}
	
	public static void setLog(){
		Properties pro = new Properties();
        try {
        	InputStream in = new BufferedInputStream(new FileInputStream(("application.properties")));
			pro.load(in);
			
                        /*创建log文件夹*/
			FileDirectory.creatDirectory(pro.getProperty("log-folder"));
			
			File file=new File(pro.getProperty("log-folder"));
			String logPath=file.getAbsolutePath();
			/*windows系统路径特殊*/
			if(pro.getProperty("system").equals("windows")){
				logPath=logPath.replace("\\", "\\\\");
			}
			System.setProperty("logPath",logPath);
			PropertyConfigurator.configure ("log4j.properties");
			logger.info("Log fold config done");
        } catch (Exception e) {
        	logger.error("error",e);
        }
	}
}

 

你可能感兴趣的:(log4j)