通过SocketAppender从Log4j读取日志

时间:2014-02-10 10:55:51

标签: java ruby logging log4j

我有测试记录器:

package com.howtodoinjava;

import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;

public class Log4jSocketAppenderExample {
    static Logger logger = Logger.getLogger(Log4jSocketAppenderExample.class);

    public static void main(String[] args) throws InterruptedException {
        int i = 0;
        while (true) {
            // PropertiesConfigurator is used to configure logger from
            // properties file
            PropertyConfigurator.configure("log4j.properties");

            // These logs will be sent to socket server as configured in
            logger.error("Log4j socket appender test run successfully!!");
            Log4jSocketAppenderExample obj = new Log4jSocketAppenderExample();
            obj.testFunction();

            System.out.println(i++);
            Thread.sleep(5000);
        }
    }

    public void testFunction() {
        logger.info("TEST FUNCTION LOGS !");
    }
}

和log4j的属性

log4j.rootLogger=DEBUG, server
log4j.appender.server=org.apache.log4j.net.SocketAppender
log4j.appender.server.Port=4712
log4j.appender.server.RemoteHost=localhost
log4j.appender.server.ReconnectionDelay=10000

现在,如果我在命令行中启动SimpleSocketServer:

java -classpath C:\log4j-1.2.14.jar org.apache.log4j.net.SimpleSocketServer 4712 log4j-server.properties

使用log4j-server.properties,如:

log4j.rootLogger=DEBUG, file
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.File=logfile.log
log4j.appender.file.MaxFileSize=1MB
log4j.appender.file.MaxBackupIndex=1
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=[%d] [%t] [%m]%n

将Log4jSocketAppenderExample的日志写入文件logfile.log

现在,我想编写一个简单的套接字服务器来接收像SimpleSocketServer

这样的日志

我试过了:

require 'socket'               # Get sockets from stdlib
server = TCPServer.open('localhost',4712)  # Socket to listen on port 2000
filelog = File.open("filelog.log","a")
loop {                         # Servers run forever
  socket = server.accept       # Wait for a client to connect
    while line = socket.gets
      filelog.puts line # Prints whatever the client enters on the server's output
    end
    filelog.puts "--------------------------------"

}

filelog.log现在由LogEvent序列化的字符串版本编写,它看起来像:

¬í sr !org.apache.log4j.spi.LoggingEventóò¹#tµ? 
Z mdcCopyLookupRequiredZ ndcLookupRequiredJ     timeStampL categoryNamet Ljava/lang/String;L locationInfot #Lorg/apache/log4j/spi/LocationInfo;L mdcCopyt Ljava/util/Hashtable;L ndcq ~ L renderedMessageq ~ L 
threadNameq ~ L 
throwableInfot +Lorg/apache/log4j/spi/ThrowableInformation;xp    DóJêt ,com.howtodoinjava.Log4jSocketAppenderExamplepppt -Log4j socket appender test run successfully!!t mainpw  œ@pxysr !org.apache.log4j.spi.LoggingEventóò¹#tµ? 
Z mdcCopyLookupRequiredZ ndcLookupRequiredJ     timeStampL categoryNamet Ljava/lang/String;L locationInfot #Lorg/apache/log4j/spi/LocationInfo;L mdcCopyt Ljava/util/Hashtable;L ndcq ~ L renderedMessageq ~ L 
threadNameq ~ L 
throwableInfot +Lorg/apache/log4j/spi/ThrowableInformation;xp    DóJêt ,com.howtodoinjava.Log4jSocketAppenderExamplepppt TEST FUNCTION LOGS !t mainpw  N pxy

那么,我如何只从SocketAppender获取日志消息?

1 个答案:

答案 0 :(得分:0)

我解决了我的问题,需要包含一些java类来从socket

中读取对象
require 'socket'  
require "java"
require "C:\\log4j-1.2.14.jar"
require "jruby/serialization"
require 'date'

# Get sockets from stdlib
server = TCPServer.open('localhost',4712)  # Socket to listen on port 2000
filelog = File.open("filelog.log","a")
loop {                         # Servers run forever
  socket = server.accept       # Wait for a client to connect
  ois = JRubyObjectInputStream.new(java.io.BufferedInputStream.new(socket.to_inputstream))
    begin
        # NOTE: event_raw is org.apache.log4j.spi.LoggingEvent
                event = Hash.new
                log4j_obj = ois.readObject
                event["messsage"] = log4j_obj.getRenderedMessage
                event["path"] = log4j_obj.getLoggerName
                event["priority"] = log4j_obj.getLevel.toString
                event["logger_name"] = log4j_obj.getLoggerName
                event["thread"] = log4j_obj.getThreadName
                event["time"] = Time.at(log4j_obj.timeStamp).utc.to_datetime

                event.each do |key,value|
                    puts "-#{key}--#{value}"
                end
                puts "--------------------------------------------"
    rescue => e
        puts "---------#{e.inspect}"
    end
}