在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.Env
版权声明:本文为u012578322原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。