我正在尝试以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就可以提取各个字段并对其进行索引,这样它们就可以搜索了?
在Logstash的conf文件中,添加json过滤器:
filter {
json {
source => message
}
}
或者使用Map并执行以下操作:
Map<String, Object> map = new HashMap<>();
map.put("system", "fedora");
logger.info(Markers.appendEntries(map), "Hello world");
对于
{
"message" : "Hello world",
"system" : "fedora"
}
(省略默认字段)。