4

我正在尝试以 JSON 格式输出我的记录器,这样我就可以消除在我的 ELK 堆栈中使用过滤器的需要。它似乎确实有效。

这是我所拥有的

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.json.simple.JSONObject; 

public class MyApp {

   static Logger logger = LoggerFactory.getLogger(MyApp.class);

   @SuppressWarnings("unchecked")
   public static void main(String[] args) {
      // TODO Auto-generated method stub
      JSONObject obj = new JSONObject();
      JSONObject obj2 = new JSONObject();


      obj.put("name","foo");
      obj.put("num",new Integer(100));
      obj.put("balance",new Double(1000.21));
      obj.put("is_vip",new Boolean(true));

      obj2.put("ob2name","bar");
      obj2.put("ob2num",new Integer(200));

      obj.put("names", obj2);


      logger.info("{}", obj);

   }

}

输出到我的 file.log

{"@timestamp":"2016-07-27T17:51:08.331+01:00","@version":1,"thread_name":"main","logger_name":"MyApp","level":"INFO","level_value":20000,"HOSTNAME":"gman","message":"{\"names\":{\"ob2num\":200,\"ob2name\":\"bar\"},\"balance\":1000.21,\"is_vip\":true,\"num\":100,\"name\":\"foo\"}"}

输出到 logstash 控制台

{
     "@timestamp" => "2016-07-27T16:51:08.331Z",
       "@version" => 1,
    "thread_name" => "main",
    "logger_name" => "MyApp",
          "level" => "INFO",
    "level_value" => 20000,
       "HOSTNAME" => "gman",
        "message" => "{\"names\":{\"ob2num\":200,\"ob2name\":\"bar\"},\"balance\":1000.21,\"is_vip\":true,\"num\":100,\"name\":\"foo\"}",
           "host" => "gman",
           "path" => "C:\\apps\\dots\\logs\\file.log"
}

我的问题

该消息似乎以字符串形式输出,我如何将其输出为 JSON,以便 Elasticsearch 可以获取各个字段并将它们编入索引,以便它们可以被搜索?

4

2 回答 2

1

在 Logstash 的 conf 文件中,添加 json 过滤器:

filter {
    json {
        source => message
    }
}
于 2016-07-27T17:28:18.720 回答
1

或者使用地图并做一些这样的想法:

Map<String, Object> map = new HashMap<>();
map.put("system", "fedora");
logger.info(Markers.appendEntries(map), "Hello world");

为了

{
  "message" : "Hello world",
  "system" : "fedora"
}

(省略默认字段)。

于 2018-04-18T14:25:35.173 回答