How to use log4j2 JMSAppender with ActiveMQ

2019-08-07 01:25发布

问题:

I am struggling to write a simple POC program that logs messages to a Queue. All tutorials and Q&As I find (here and here) use log4j version 1.2 and they put messages onto a Topic and not onto a queue. My requirement is to log to a queue.

I followed the documentation mentioned on the official site, but was not able to get it working.

I have log4j2 and ActiveMQ JARs on my classpath, I have created the queue "logQueue", I am able to see the queue in the ActiveMQ web console and when I try execute the program to write the logs, I get the following error:

ERROR Error creating JmsManager using ConnectionFactory [ConnectionFactory] and Destination [logQueue]. javax.naming.NoInitialContextException: Need to specify class name in environment or system property, or as an applet parameter, or in an application resource file:  java.naming.factory.initial
    at javax.naming.spi.NamingManager.getInitialContext(NamingManager.java:662)
    at javax.naming.InitialContext.getDefaultInitCtx(InitialContext.java:313)

It clearly looks like some JNDI issue, but am not able to figure out what. As per the log4j 1.2 tutorials, I also added the jndi.properties file to my classpath with the value

queue.logQueue=logQueue

but thats not helping apparently. Below is my log4j2.xml

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="warn" name="MyApp" packages="">
  <Appenders>
    <JMS name="jmsQueue" destinationBindingName="logQueue"
         factoryBindingName="ConnectionFactory"
         providerURL="tcp://localhost:61616"/>
  </Appenders>
  <Loggers>
    <Root level="all">
      <AppenderRef ref="jmsQueue"/>
    </Root>
  </Loggers>
</Configuration>

Thanks !

回答1:

Adding factoryName="org.apache.activemq.jndi.ActiveMQInitialContextFactory" to the JMS element solved the problem.

The final JMS element in the log4j2.xml looks like this:

<JMS name="jmsQueue" destinationBindingName="logQueue"
        factoryName="org.apache.activemq.jndi.ActiveMQInitialContextFactory"
        factoryBindingName="ConnectionFactory"
        providerURL="tcp://localhost:61616"/>


回答2:

I have got an error during the initialization of the appender, so I tried to write my own instead of using the existing xml configuration.

Dependencies versions :

  • ActiveMQ 5.12.1 client
  • log4j-core-2.5
  • slf4j-1.7.12

Java class:

copy the class and put it anywhere in your project,

package com.towersoft.eagleserver;

import java.io.Serializable;

import javax.jms.DeliveryMode;
import javax.jms.Destination;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.logging.log4j.core.Filter;
import org.apache.logging.log4j.core.Layout;
import org.apache.logging.log4j.core.LogEvent;
import org.apache.logging.log4j.core.appender.AbstractAppender;
import org.apache.logging.log4j.core.config.plugins.Plugin;
import org.apache.logging.log4j.core.config.plugins.PluginAttribute;
import org.apache.logging.log4j.core.config.plugins.PluginElement;
import org.apache.logging.log4j.core.config.plugins.PluginFactory;
import org.apache.logging.log4j.core.layout.PatternLayout;


@Plugin(name = "JMSQueueAppender", category = "Core", elementType = "appender", printObject = true)
public class JMSQueueAppender extends AbstractAppender {

//    private static Logger logger = Logger.getLogger("JMSQueueAppender");
    private String brokerUri = "failover://tcp://localhost:61616";
    private String queueName = "logQueue";
    Session session;

    ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(this.brokerUri);
    javax.jms.Connection connection;
    Destination destination;
    MessageProducer producer;


    private void init() {
        try {

            connection = connectionFactory.createConnection();
            connection.start();
            // Create a Session
            session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            destination = session.createQueue(this.queueName);
            producer = session.createProducer(destination);
            producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    protected JMSQueueAppender(String name, Filter filter,
            Layout<? extends Serializable> layout, final boolean ignoreExceptions) {
        super(name, filter, layout, ignoreExceptions);
        init();
    }

    @Override
    public void append(LogEvent le) {
        try {
            if (connection == null) {
                init();
            }
            TextMessage message = session.createTextMessage(le.getMessage().getFormattedMessage());
            // Tell the producer to send the message
            producer.send(message);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void stop() {
        super.stop(); 
        try {
            session.close();
            connection.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @PluginFactory
    public static JMSQueueAppender createAppender(
            @PluginAttribute("name") String name,
            @PluginElement("Layout") Layout<? extends Serializable> layout,
            @PluginElement("Filter") final Filter filter) {
        if (name == null) {
            LOGGER.error("No name provided for MyCustomAppenderImpl");
            return null;
        }
        if (layout == null) {
            layout = PatternLayout.createDefaultLayout();
        }
        return new JMSQueueAppender(name, filter, layout, true);
    }
}

log4j2.xml :

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
    <Appenders>
        <Console name="Console" target="SYSTEM_OUT">
            <PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
        </Console>
        <JMSQueueAppender name="jmsQueue"/>
    </Appenders>
    <Loggers>
        <Root level="debug">
            <AppenderRef ref="Console"/>
            <AppenderRef ref="jmsQueue"/>
        </Root>
        <Logger name="org.quartz" level="ERROR"/>
        <Logger name="com.zaxxer" level="ERROR"/>
        <Logger name="org.apache.activemq" level="ERROR"/>
    </Loggers>
</Configuration>


回答3:

I had exactly this problem. Solved by adding a file to my maven resources directory called jndi.properties with contents ...

topic.logTopic=logTopic
queue.logQueue=logQueue

Clearly the actual names used can be modified. In my case my appender could be ...

<JMS name="jmsQueue" 
            destinationBindingName="logQueue" 
            factoryName="org.apache.activemq.jndi.ActiveMQInitialContextFactory"
            factoryBindingName="ConnectionFactory"
            providerURL="tcp://localhost:61616"
            userName="admin"
            password="admin">
            <SyslogLayout />
          </JMS>

Note: I had to modify the layout of the appender to avoid a serialization error ( other possible values are ... JSONLayout, YamlLayout, HtmlLayout etc).

Hope this helps.