Spring 如何集成Log4J呢?
日志功能简介
日志是所有软件中必须拥有的功能,下文讲述Spring中集成Log4j的示例分享,如下所示:
集成Log4j前,需准备以下步骤:
下载相应的jar包https://logging.apache.org/log4j
log4j-x.y.z.jar
采用以下的方法集成Log4j
- 创建 SpringDemo 项目
- 在 src 目录下创建 com.java265 包
- 导入 Spring 相关 JAR 包及 log4j-x.y.z.jar
- 在 com.java265 包下创建 HelloWorld、MainApp、Beans.xml 和 log4j.properties
- 运行 SpringDemo 项目
package com.java265;
public class HelloWorld {
private String message;
public void setMessage(String message) {
this.message = message;
}
public void getMessage() {
System.out.println("消息:" + message);
}
}
MainApp 类
package com.java265;
import org.apache.log4j.Logger;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MainApp {
static Logger log = Logger.getLogger(MainApp.class.getName());
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");
log.info("Going to create HelloWord Obj");
HelloWorld obj = (HelloWorld) context.getBean("helloWorld");
obj.getMessage();
log.info("Exiting the program");
}
}
Beans.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> <bean id="helloWorld" class="com.java265.HelloWorld"> <property name="message" value="Hello,java265!" /> </bean> </beans>log4j.properties配置内容如下
# Define the root logger with appender file log4j.rootLogger = DEBUG, FILE # Define the file appender log4j.appender.FILE=org.apache.log4j.FileAppender # Set the name of the file log4j.appender.FILE.File=E:\\log.out # Set the immediate flush to true (default) log4j.appender.FILE.ImmediateFlush=true # Set the threshold to debug mode log4j.appender.FILE.Threshold=debug # Set the append to false, overwrite log4j.appender.FILE.Append=false # Define the layout for file appender log4j.appender.FILE.layout=org.apache.log4j.PatternLayout log4j.appender.FILE.layout.conversionPattern=%m%n运行结果---
消息:Hello,java265!
log.out 文件内容如下。
Going to create HelloWord Obj
Exiting the program
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。


