Spring集成Log4J

日志是应用软件中不可缺少的部分,Apache 的开源项目 Log4J 是一个功能强大的日志组件。在 Spring 中使用 Log4J 是非常容易的,下面通过例子演示 Log4J 和 Spring 的集成。

使用 Log4J 之前,需要先导入 log4j-x.y.z.jar 包,Log4J 下载地址:https://logging.apache.org/log4j。

示例

下面使用 Eclipse IDE 演示 Log4J 的使用,步骤如下:

  1. ​ 创建 SpringDemo 项目,并在 src 目录下创建 net.biancheng 包。
  2. ​ 导入 Spring 相关 JAR 包及 log4j-x.y.z.jar。
  3. ​ 在 net.biancheng 包下创建 HelloWorld、MainApp、Beans.xml 和 log4j.properties。
  4. ​ 运行 SpringDemo 项目。

HelloWorld 类代码如下。

1
2
3
4
5
6
7
8
9
10
package net.biancheng;
public class HelloWorld {
private String message;
public void setMessage(String message) {
this.message = message;
}
public void getMessage() {
System.out.println("消息:" + message);
}
}

MainApp 类代码如下。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
package net.biancheng;
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 代码如下。

1
2
3
4
5
6
7
8
<?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="net.biancheng.HelloWorld">
<property name="message" value="Hello,bianchengbang!" />
</bean>
</beans>

log4j.properties 内容如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# 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=D:\\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

运行结果如下:

1
消息:Hello,bianchengbang!

log.out 文件内容如下:

1
2
Going to create HelloWord Obj
Exiting the program

来源——C语言中文网
g/)**