如何使用 log4j JMS 追加器与 ActiveMQ Classic
常见问题解答 > 使用 Apache ActiveMQ Classic > 如何使用 log4j JMS 追加器与 ActiveMQ Classic
Log4j JMS 追加器 可以用来将日志消息发送到 JMS 代理。要将 ActiveMQ Classic 用作消息的目标,您需要正确配置 JMS 追加器。下面的代码示例展示了示例配置
log4j.rootLogger=INFO, stdout, jms
## Be sure that ActiveMQ Classic messages are not logged to 'jms' appender
log4j.logger.org.apache.activemq=INFO, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d %-5p %c - %m%n
## Configure 'jms' appender. You'll also need jndi.properties file in order to make it work
log4j.appender.jms=org.apache.log4j.net.JMSAppender
log4j.appender.jms.InitialContextFactoryName=org.apache.activemq.jndi.ActiveMQInitialContextFactory
log4j.appender.jms.ProviderURL=tcp://127.0.0.1:61616
log4j.appender.jms.TopicBindingName=logTopic
log4j.appender.jms.TopicConnectionFactoryBindingName=ConnectionFactory
重要的是不要将 ActiveMQ Classic 日志发送到 JMS 追加器,因为这会导致错误,因为代理将在连接建立之前需要进行日志记录。您还需要一个 JNDI 配置,以便追加器可以找到合适的主题来发送日志消息。示例 jndi.properties
文件可能如下所示
topic.logTopic=logTopic
最后,您可以订阅主题并监听日志消息
public class Log4jJMSAppenderExample implements MessageListener {
public Log4jJMSAppenderExample() throws Exception {
// create a logTopic topic consumer
ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("tcp://127.0.0.1:61616");
Connection conn = factory.createConnection();
Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
conn.start();
MessageConsumer consumer = sess.createConsumer(sess.createTopic("logTopic"));
consumer.setMessageListener(this);
// log a message
Logger log = Logger.getLogger(Log4jJMSAppenderExample.class);
log.info("Test log");
// clean up
Thread.sleep(1000);
consumer.close();
sess.close();
conn.close();
System.exit(1);
}
public static void main(String[] args) throws Exception {
new Log4jJMSAppenderExample();
}
public void onMessage(Message message) {
try {
// receive log event in your consumer
LoggingEvent event = (LoggingEvent)((ActiveMQObjectMessage)message).getObject();
System.out.println("Received log [" + event.getLevel() + "]: "+ event.getMessage());
} catch (Exception e) {
e.printStackTrace();
}
}
}
请注意,追加器会将日志事件包装在对象消息中,因此您可以提取信息,例如记录器名称、级别,当然还有消息。
从 ActiveMQ Classic 5.3 开始,此示例包含在标准发行版中。您可以通过执行以下命令运行它
ant log4j-jms
在 example/
文件夹中。您应该能够看到以下输出作为结果
log4j-jms:
[echo] Running a Log4j JMS Appender example
[java] 2009-08-11 13:58:46,767 INFO Log4jJMSAppenderExample - Test log
[java] Received log [INFO]: Test log
[java] Java Result: 1