这是我的配置文件或 log4j2.properties 文件
#Socket Appender
appender.socket.type=Socket
appender.socket.name=Socket_Appender
appender.socket.host=10.176.250.5
appender.socket.port=9000
appender.socket.layout.type=SerializedLayout
appender.socket.connectTimeoutMillis=2000
appender.socket.reconnectionDelayMillis=1000
appender.socket.protocol=TCP
#Loggers
logger.socket.name=atom
logger.socket.level=debug
logger.socket.appenderRefs=socket
logger.socket.appenderRef.socket.ref=Socket_Appender
接下来我有两个类LogSender和LogListener
它的作业是通过SocketAppender发送日志。
通过Stream发送的是LogEvent对象。
public class LogSender {
public static final Logger LOG = LogManager.getLogger("atom");
public static void main(String[] args) {
LOG.trace("Error 1");
LOG.debug("Error 2");
LOG.info("Error 3");
LOG.warn("Error 4");
LOG.error("Error 5");
LOG.fatal("Error 6");
}
}
这应该接收通过流发送的LogEvent对象。 LogListener使用ObjectInputStream并保存
LogEvent event = null;
private Socket socket1 = null;
private ServerSocket ss = null;
PrintWriter sspw=null;
ObjectInputStream objectInputStream = null;
try {
//Creating Socket and making it listen to a specific port, receiving through streams.
//Servers socket creation and waiting
ss = new ServerSocket(9000);
socket1 = ss.accept();
objectInputStream = new ObjectInputStream(new BufferedInputStream(socket1.getInputStream()));
event = (LogEvent) objectInputStream.readObject();
System.out.println(event.getLoggerName());
System.out.println(event.getLevel());
System.out.println(event.getMessage().getFormattedMessage());
objectInputStream.close();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
输出
原子
DEBUG
错误2
输出是Logger的名称。这意味着我们正在接收LogEvent对象并能够提取记录器信息。我也能够收到实际的日志消息,但只有一个级别弹出,即DEBUG级别。
我也想要所有其他级别。我将如何继续这样做?
我对Log4j2很新,我觉得我在理解中错过了一些东西(只是一种直觉)。
答案 0 :(得分:1)
您没有获得第一个日志(TRACE),因为在您的配置文件log4j2.properties
中,您有logger.socket.level=debug
,但您应该logger.socket.level=trace
来启用级别TRACE。< / p>
关于其他日志,您应该在循环中运行您的侦听器代码:现在您只读取第一个日志。
我没有测试这段代码,但看起来应该是这样的:
LogEvent event = null;
private Socket socket1 = null;
private ServerSocket ss = null;
PrintWriter sspw=null;
ObjectInputStream objectInputStream = null;
try {
//Creating Socket and making it listen to a specific port, receiving through streams.
//Servers socket creation and waiting
ss = new ServerSocket(9000);
socket1 = ss.accept();
objectInputStream = new ObjectInputStream(new BufferedInputStream(socket1.getInputStream()));
while (true) {
event = (LogEvent) objectInputStream.readObject();
System.out.println(event.getLoggerName());
System.out.println(event.getLevel());
System.out.println(event.getMessage().getFormattedMessage());
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (objectInputStream != null) {
objectInputStream.close();
}
}