Graylog2以UDP形式存储GELF格式的json时无法存储中文

ShinobuChyan
  • 71

想用graylog存系统的登陆日志,java代码如下:

private static void send(String host, int port, Map<String, Object> params) throws Exception {
    if (SOCKET == null) {
        SOCKET = new DatagramSocket();
    }
    InetAddress address = InetAddress.getByName(host);
    String content = JSON.toJSONString(params);
    DatagramPacket packet = new DatagramPacket(content.getBytes("UTF-8"), content.length(), address, port);
    SOCKET.send(packet);
}

其中content字符串如下:

{
  "version":"1.1",
  "host":"test.com",
  "short_message":"loginLog",
  "full_message":"loginLog",
  "_name":"测试",
  "_result":"SUCCESS:登陆成功",
  "_user_id":"f69cf0a3-ad33-4b7f-b770-ea18d615f6a1",
  "_username":"test",
  "_ip":"192.168.1.33"
}

经过反复测试,发下一旦字段中包含了中文,就无法存储成功,但是Graylog的文档中关于GELF的描述如下:

  • _[additional field] string (UTF-8) or number

every field you send and prefix with an underscore (_) will be treated as an additional field. Allowed characters in field names are any word character (letter, number, underscore), dashes and dots. The verifying regular expression is: ^[w.-]*$. Libraries SHOULD not allow to send id as additional field (_id). Graylog server nodes omit this field automatically.

即使用utf-8编码即可。

反复尝试仍然解决不了,前来求助。
望各路大佬给点建议,万分感谢!

回复
阅读 2.3k
1 个回答

解决了。。 非常蠢的错误,只需把java代码改为如下:

private static void send(String host, int port, Map<String, Object> params) throws Exception {
    if (SOCKET == null) {
        SOCKET = new DatagramSocket();
    }
    InetAddress address = InetAddress.getByName(host);
    String content = JSON.toJSONString(params);
    byte[] bytes = content.getBytes("UTF-8");
    DatagramPacket packet = new DatagramPacket(bytes, bytes.length, address, port);
    SOCKET.send(packet);
}

所以问题就在于包含中文的byte[]长度和之前的字符串并不相同。。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
宣传栏