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 !
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:
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 :
Java class:
copy the class and put it anywhere in your project,
log4j2.xml :
I had exactly this problem. Solved by adding a file to my maven resources directory called jndi.properties with contents ...
Clearly the actual names used can be modified. In my case my appender could be ...
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.