所以我为 Log4J 创建了一个自定义的 appender,它基本上与 socketappender 做同样的事情,但使用的是 UDP 而不是 TCP。但是,我无法让日志显示日期。我认为 .properties 文件可能存在问题,但我不确定是什么。特别是因为我知道 .properties 文件在某种程度上可以工作,因为这是测试程序知道要使用哪个附加程序的方式。但是,它没有使用 .properties 文件中指定的布局。任何帮助/建议将不胜感激!
附加代码:
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import org.apache.log4j.AppenderSkeleton;
import org.apache.log4j.spi.LoggingEvent;
public /*static*/ class UDPAppender extends AppenderSkeleton {
@Override
protected void append(LoggingEvent event) {
String message = null;
event.getProperties();
StringBuilder formatedMessage = new StringBuilder();
formatedMessage.append("Level:");
formatedMessage.append(event.getLevel());
formatedMessage.append(", FILE:");
formatedMessage.append(event.getLocationInformation().getFileName());
formatedMessage.append(", Thread Id:");
formatedMessage.append(event.getLocationInformation().getLineNumber());
formatedMessage.append(", ERROR: ");
formatedMessage.append(event.getMessage().toString());
message = formatedMessage.toString();
DatagramSocket clientSocket = null;
//creating DatagramSocket to send logger info to socket; if not created, will print Stack Trace
try {
clientSocket = new DatagramSocket();
} catch (SocketException e) {
e.printStackTrace();
}
InetAddress IPAddress = null;
//get InetAddress for sending packet
try {
IPAddress = InetAddress.getByName("localhost");
} catch (UnknownHostException e) {
e.printStackTrace();
}
byte[] sendData = new byte[1024];
sendData = message.getBytes(); //convert from String to bytes so that message can be sent through datagrampacket
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 27770); //address packet
try {
clientSocket.send(sendPacket); //send packet to the socket addressed above
} catch (IOException e) {
e.printStackTrace();
}
clientSocket.close(); //need to close
}
public void close() {
}
public boolean requiresLayout() {
return true;
}
}
测试代码:
import org.apache.log4j.*;
public class Tester {
private static final Logger log2 = Logger.getLogger("REMOTE");
public static void main(String[] args) {
//configures using the .properties file user creates
PropertyConfigurator.configure("log4j.properties");
log2.info("This is info message");
System.out.println("Logging complete");
//prints to console to let user know logging completed successfully
LogManager.shutdown();
//closes logs once logging is complete
}
}
.properties 文件:
log4j.logger.REMOTE=DEBUG, REMOTE
log4j.appender.REMOTE=custom.UDPAppender
log4j.appender.REMOTE.layout=org.apache.log4j.PatternLayout
log4j.appender.REMOTE.layout.ConversionPattern=%d{MMMM dd HH:mm:ss}, %d{yyyy} %F %L %m %t