package com.demo.product;
import org.apache.log4j.Logger;
public class Main{
private static final Logger logger = Logger.getLogger(Main.class);
public static void main(String[] args) throws Exception {
// just log a message
logger.info("Info Log.");
logger.warn("Warn Log");
logger.error("Error Log.");
System.exit(0);
}
}
这个Main类和普通的logger调用一样,仅仅负责打印日志。有没有觉得太简单了呢?
Logging项目
来看看项目结构图:
为了让监听器一直活着,我把Logging写成了一个Web项目,跑在Tomcat上。index.jsp就是个Hello World字符串而已,用来验证Logging活着。注意,在Logging项目中,已没有Product项目中的log4j.properties和jndi.properties两个文件。
来看看另外几个文件:
pom.xml(每个包的目的都写在注释里了):
<!-- Use to cast object to LogEvent when received a log -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<!-- Use to receive jms message -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jms</artifactId>
<version>4.0.0.RELEASE</version>
</dependency>
<!-- Use to load spring.xml -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>4.0.0.RELEASE</version>
</dependency>
<!-- ActiveMQ lib -->
<dependency>
<groupId>org.apache.activemq</groupId>
<artifactId>activemq-core</artifactId>
<version>5.7.0</version>
</dependency>
web.xml
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring.xml</param-value>
</context-param>
<!-- Use to load spring.xml -->
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
spring.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="
">
<bean>
<property ref="connectionFactory"/>
</bean>
<bean>
<property ref="targetConnectionFactory"/>
</bean>
<bean>
<property value="tcp://localhost:61616"/>
</bean>
<!-- As JMSAppender only support the topic way to send messages,
thus queueDestination here is useless.
<bean>
<constructor-arg value="queue" />
</bean>
-->
<bean>
<constructor-arg value="logTopic" />
</bean>
<bean>
<property ref="connectionFactory" />
<!-- <property ref="queueDestination" /> -->
<property ref="topicDestination" />
<property ref="logMessageListener" />
</bean>
<bean/>
</beans>