Configuring a Java Application to log to TraceListener
Requirements
- log4j version 2.0 (download it from here)
Application build requirements:
- add a reference to the log4j.jar to your application
Application configuration
pogrammatic configuration:
import org.apache.log4j.*;
import org.apache.log4j.net.UDPAppender;
import org.apache.log4j.xml.XMLLayout;
...
public static void main(String[] args)
{
// configure an UdpAppender with XML Layout
xmll.setLocationInfo(true);
// log to the local machine as a remotehost and on port 9991
UDPAppender udpApp = new UDPAppender("localhost", 9991);
XMLLayout xmll = new XMLLayout();
xmll.SetLocationInfo(true);
udpApp.setLayout(xmll);
udpApp.setEncoding("default");
BasicConfigurator.configure(udpApp);
// log a debug string to TraceListener
Logger.getLogger("MainForm").info("Hello from log4j.");
}
configuration through a XML configuration file:
import org.apache.log4j.*;
import org.apache.log4j.joran.JoranConfigurator;
public static void main(String[] args)
{
JoranConfigurator jc = new JoranConfigurator();
jc.doConfigure("c:/LogConfig.xml", LogManager.getLoggerRepository());
Logger.getLogger("MainForm").info("Hello from log4j.");
}
XML configuration file:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration >
<log4j:configuration xmlns:log4j='http://jakarta.apache.org/log4j/'>
<appender name="UDPAppender" class="org.apache.log4j.net.UDPAppender">
<param name="RemoteHost" value="localhost"/>
<param name="Port" value="9991"/>
<param name="Encoding" value="default"/>
<layout class="org.apache.log4j.xml.XMLLayout">
<param name="LocationInfo" value="true"/>
</layout>
</appender>
<root>
<appender-ref ref="UDPAppender" />
</root>
</log4j:configuration>