使用 jsonrpc4j 记录 JSON-RPC 调用

Logging JSON-RPC calls using jsonrpc4j

我敢肯定,如果您使用过 jsonrpc4j(在 spring 容器 之外),您会识别出以下标准模式。

public class MyServletJsonRpc extends HttpServlet {
   private MyService myService;
   private JsonRpcServer jsonRpcServer;

   @Override
   protected void doPost(HttpServletRequest request
                      , HttpServletResponse response) throws IOException {
      jsonRpcServer.handle(request, response);
   }
   @Override
   public void init(ServletConfig config) {
       myService = new MyServiceImpl();
       jsonRpcServer = new JsonRpcServer(myService, MyService.class);
       jsonRpcServer.set...
   }

我正在尝试创建一个包含所有 JSON 请求和 JSON 响应的日志文件。即我想在反序列化之前记录传入的 JSON RPC 请求,并在序列化后立即记录输出请求。

我一直在通读代码,似乎没有一个很好的简单方法可以做到这一点。有人可以帮忙吗?

我想出的(可行的)解决方案使用了某种装饰,但我对此并不满意:

public class MyServletJsonRpc extends HttpServlet {
   private MyService myService;
   private JsonRpcServer jsonRpcServer;

   @Override
   protected void doPost(HttpServletRequest request
                      , HttpServletResponse response) throws IOException {
      jsonRpcServer.handle(request, response);
   }
   @Override
   public void init(ServletConfig config) {
       myService = new MyServiceImpl();
       ObjectMapper mapper = new MyObjectMapper(null, null, null);
       jsonRpcServer = new MyJsonRpcServer(mapper, myService, null);
       jsonRpcServer.set...
   }
}

使用以下 2 个重载 类:

class MyObjectMapper extends ObjectMapper {
    private static final Logger L = LoggerFactory.getLogger(MyObjectMapper.class);

    public MyObjectMapper(JsonFactory jf, DefaultSerializerProvider sp, DefaultDeserializationContext dc) {
        super(jf, sp, dc);
    }

    @Override
    public void writeValue(OutputStream out, Object value) throws IOException, JsonGenerationException,
JsonMappingException {
        super.writeValue(out, value);
        L.info("Out: " + writeValueAsString(value));
    }

}

class MyJsonRpcServer extends JsonRpcServer {
    private static final Logger L = LoggerFactory.getLogger(MyJsonRpcServer.class);

    public MyJsonRpcServer(ObjectMapper mapper, Object handler, Class<?> remoteInterface) {
        super(mapper, handler, remoteInterface);
    }

    @Override
    public void handleNode(JsonNode node, OutputStream ops) throws IOException {
        L.info("In: " + (node == null ? "(null)" : node.toString()));
        super.handleNode(node, ops);
    }
}

我认为这看起来和感觉起来都像是一个令人讨厌的黑客攻击。有更好的方法吗?

库支持使用 InvocationListenerhttps://github.com/briandilley/jsonrpc4j/blob/master/src/main/java/com/googlecode/jsonrpc4j/InvocationListener.java

您可以在您的 servlet init() 方法中将它添加到服务器,所有调用都将通过它。

这是 setter:https://github.com/briandilley/jsonrpc4j/blob/cfdaea92fedf7b43be9d93420df168fe69a5a4fa/src/main/java/com/googlecode/jsonrpc4j/JsonRpcBasicServer.java#L994

所以只需致电 server.setInvocationListener 就可以了。

更新:将日志级别设置为 DEBUG 现在将启用带有负载的日志。