一、添加log4j的依赖
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
二、读取配置文件
PropertyConfigurator.configure("conf/log4j.properties");
说明:log4j的配置文件放在项目根目录下的conf文件夹下。打成jar包的时候,是不会包含到jar包里面的。放到linux系统上的话,要在jar包的同级目录下,新建conf文件夹,再将log4j.properties配置文件上传。其他的配置文件同理。
三、使用Logger打印日志
private static Logger logger = Logger.getLogger(YourClass.class);
logger.info("需要打印的日志信息");
四、log4j配置文件(仅供参考)
#log4j.rootLogger=INFO, CONSOLE,LOCALFILE
log4j.rootLogger=INFO,CONSOLE,LOCALFILE
#log4j.logger.CONSOLE.testlog4j.App = DEBUG,test3
# A1 is set to be a ConsoleAppender which outputs to System.out.
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
# A1 uses PatternLayout.
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
# The conversion pattern uses format specifiers. You might want to
# change the pattern an watch the output format change.
log4j.appender.CONSOLE.layout.ConversionPattern=%d{HH:mm:ss,SSS} %-5p [%t] %1c %3x - %m%n
# A1 is set to be a ConsoleAppender which outputs to System.out.
log4j.appender.LOCALFILE=org.apache.log4j.DailyRollingFileAppender
# A1 uses PatternLayout.
log4j.appender.LOCALFILE.layout=org.apache.log4j.PatternLayout
# The conversion pattern uses format specifiers. You might want to
# change the pattern an watch the output format change.
log4j.appender.LOCALFILE.layout.ConversionPattern=%d{HH:mm:ss,SSS} %-5p [%t] %1c %3x - %m%n
log4j.appender.LOCALFILE.File=target/audit
log4j.appender.LOCALFILE.DatePattern='.'yyyy-MM-dd'.log'
五、普通配置文件的读取(config.properties)
public static String getConfigValue(String key) {
Properties property = new Properties();
InputStream inputStream = null;
InputStreamReader reader = null;
try {
inputStream = new FileInputStream("./conf/config.properties");
reader = new InputStreamReader(inputStream, "utf-8");
} catch (Exception e) {
inputStream = PropertiesUtilLocal.class.getClassLoader().getResourceAsStream("config.properties");
if (inputStream != null) {
try {
reader = new InputStreamReader(inputStream, "utf-8");
} catch (UnsupportedEncodingException e1) {
logger.error("new InputStreamReader(inputStream,'utf-8') fail" + e.getLocalizedMessage());
}
}
if (inputStream == null) {
return null;
}
}
try {
property.load(reader);
return property.getProperty(key);
} catch (IOException e) {
logger.error(e.getLocalizedMessage());
return null;
} finally {
try {
inputStream.close();
} catch (IOException e1) {
logger.error(e1.getLocalizedMessage());
}
}
}
觉得有用的赞一下呗!