在spring中使用log4j

  • 引入log4j软件包
  • 配置log4j属性
  • 加载log4j配置文件
  • 默认加载
  • 手动加载
  • 使用logger

本文的整体代码结构是在已经引入spring基本应用的前提下,在spring配置文件中通过@Bean注解创建一个Logger bean,然后在测试代码中使用。

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.net.URL;

import org.apache.log4j.Logger;
import org.apache.logging.log4j.core.config.ConfigurationSource;
import org.apache.logging.log4j.core.config.Configurator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;

@Configuration
@EnableAspectJAutoProxy
@ComponentScan({"com.markey.messageboard.app.impl","com.markey.messageboard.aop"})
public class SpringConfig {
//	@Bean
//	public static PropertySourcesPlaceholderConfigurer placeholderConfigurer(){
//		PropertySourcesPlaceholderConfigurer placeholderConfigurer = new PropertySourcesPlaceholderConfigurer();
//		return placeholderConfigurer;
//	}
	@Bean
	public static Logger logger(){
		String path="/com/log4j.properties";
		URL url=SpringConfig.class.getResource(path);
		ConfigurationSource source;
		try {
			source = new ConfigurationSource(new FileInputStream(new File(url.getPath())),url);
			Configurator.initialize(null, source);
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		Logger logger = Logger.getLogger(SpringConfig.class);
		return logger;
	}
}
import org.apache.log4j.Logger;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.env.Environment;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.markey.messageboard.app.Dosomething;
import com.markey.messageboard.configs.SpringConfig;
import com.markey.messageboard.model.Messageboard;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SpringConfig.class)
//@PropertySource("classpath:/test.properties")
//@PropertySource("classpath:/log4j.properties")
public class helloSpring {
	
	@Autowired
	Environment evn;
	@Autowired
	Dosomething dosomething;
	@Autowired
	Logger logger;
	@Value("${god.hello}") String titleString;
	@Test
	public void testWorld(){
//		System.out.println(evn.containsProperty("god.hello"));
//		Messageboard messageBoard = new Messageboard();
//		messageBoard.setTitle(titleString);
//		System.out.println(dosomething.readWall(messageBoard));
//		dosomething.readWall(messageBoard);
		logger.error("hello,i am error messages");
	}

}

一、引入log4j软件包

使用log4j涉及两个库文件:log4j和log4j-core

mava引用如下:

<!--https://mvnrepository.com/artifact/log4j/log4j -->

<dependency>

   <groupId>log4j</groupId>

   <artifactId>log4j</artifactId>

   <version>1.2.17</version>

</dependency>

<!-- https://mvnrepository.com/artifact/org.apache.logging.log4j/log4j-core-->

<dependency>

   <groupId>org.apache.logging.log4j</groupId>

   <artifactId>log4j-core</artifactId>

   <version>2.7</version>

</dependency>

二、配置log4j属性

log4j配置文件支持xml格式和properites格式,下面为例properites介绍需要配置的内容。

配置文件分为三部分配置:

l  日志级别配置

l  输出目的地配置

l  输出样式配置

1.     日志级别配置

日志级别配置分为两种:根目录级别和包目录基本。

顾名思义,根目录级别就是定义总的日志级别,具体到某个特定的包路径下的类,还可以定制日志级别。

Log4j自定义的日志级别有:OFF >FATAL > ERROR > WARN > INFO > DEBUG > ALL

但是建议只使用ERROR > WARN > INFO > DEBUG这四种。通过在这里定义的级别,您可以控制到应用程序中相应级别的日志信息的开关。比如在这里定 义了 INFO 级别,则应用程序中所有 DEBUG 级别的日志信息将不被打印出来 。

###定义根日志级别为info###
###定义com.markey.messageboard日志级别为debug###

###定义com.markey.messageboard.springtest日志级别为info###
###配置输出目的地###
log4j.rootLogger=info,stdout,errorfile,infofile 
log4j.logger.com.markey.messageboard=DEBUG
log4j.logger.com.markey.messageboard.springtest=info

#console config
log4j.appender.stdout=org.apache.log4j.ConsoleAppender

#errorfile config
log4j.appender.errorfile=org.apache.log4j.DailyRollingFileAppender 
log4j.appender.errorfile.File= c:/logs/app_logs/error.log 

#infofile config
log4j.appender.infofile=org.apache.log4j.DailyRollingFileAppender 
log4j.appender.infofile.File=c:/logs/app_logs/info.log

log4j.rootLogger=info,stdout,errorfile,infofile ###格式为[level] ,appender1,appender2,……
log4j.logger.com.markey.messageboard=DEBUG
log4j.logger.com.markey.messageboard.springtest=info

#console config
log4j.appender.stdout=org.apache.log4j.ConsoleAppender ###定义一个控制台输出目的地
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%m%n
log4j.appender.stdout.encoding=GB18030

#errorfile config
log4j.appender.errorfile=org.apache.log4j.DailyRollingFileAppender ###定义一个每日日志输出目的地
log4j.appender.errorfile.File= c:/logs/app_logs/error.log ###输出文件路径
log4j.appender.errorfile.Threshold=error  ###只有error以上级别的日志才会被输出
log4j.appender.errorfile.DatePattern='.'yyyy-MM-dd ###指定日期格式
log4j.appender.errorfile.Append=true ###指定日志文件以追加方式写入
log4j.appender.errorfile.layout=org.apache.log4j.PatternLayout 
log4j.appender.errorfile.layout.ConversionPattern=[%-5p]|%d|%C|%L|%m%n
log4j.appender.errorfile.encoding=GB18030 ###指定日志文件编码

#infofile config
log4j.appender.infofile=org.apache.log4j.DailyRollingFileAppender 
log4j.appender.infofile.File=c:/logs/app_logs/info.log
log4j.appender.infofile.Threshold=info ###只有error以上级别的日志才会被输出
log4j.appender.infofile.DatePattern='.'yyyy-MM-dd
log4j.appender.infofile.Append=true
log4j.appender.infofile.layout=org.apache.log4j.PatternLayout 
log4j.appender.infofile.layout.ConversionPattern=[%-5p]|%d|%C|%L|%m%n
log4j.additivity.infofile=false
log4j.appender.infofile.encoding=GB18030

public class SpringConfig {
	@Bean
	public static PropertySourcesPlaceholderConfigurer placeholderConfigurer(){
		PropertySourcesPlaceholderConfigurer placeholderConfigurer = new PropertySourcesPlaceholderConfigurer();
		return placeholderConfigurer;
	}
	@Bean
	public static Logger logger(){
		String path="/com/log4j.properties";//定义配置文件路径
		URL url=SpringConfig.class.getResource(path);//转化配置文件路径
		try {
			ConfigurationSource source = new ConfigurationSource(
					new FileInputStream(new File(url.getPath())),url);//找到配置文件
			Configurator.initialize(null, source);//初始化配置
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		Logger logger = Logger.getLogger(SpringConfig.class);
		return logger;
	}
}