[英]parse json objects from a log file
我想從我的日志文件中解析JSON對象。 為了使用JSON Parser,我的完整文件必須為JSON格式,而我卻不是這種情況。 有什么辦法可以逐行解析文件並獲取JSON對象。 以下是我的日志文件格式:
2015-10-19 11:24:35:701 INFO BrokerTcpClient:28 - Set destination
2015-10-19 11:24:35:929 DEBUG BrokerTcpClient:32 - received data: {type=data, payload={
"core" : [ {
"id" : {
"datatype" : "http://www.w3.org/2001/hk#long",
"type" : "gh",
"value" : "gh"
},
"entity" : {
"type" : "uri",
"value" : "http://fg.fg.com/ext/g/fg"
},
"Sno" : {
"type" : "literal",
"value" : "fg"
}]
2015-10-19 11:24:35:701 INFO BrokerTcpClient:28 - Set destination
2015-10-19 11:24:35:929 DEBUG BrokerTcpClient:32
"core" : [ {
"id" : {
"datatype" : "http://www.w3.org/2001/hk#long",
"type" : "gh",
"value" : "gh"
},
"entity" : {
"type" : "uri",
"value" : "http://fg.fg.com/ext/g/fg"
},
"Sno" : {
"type" : "literal",
"value" : "fg"
}]
任何人都可以幫助我如何獲取JSON對象嗎? 當我嘗試解析一行JSON對象時,拋出異常。
這是一個適用於發布的示例日志的解決方案。
import java.io.*;
import com.fasterxml.jackson.databind.*;
public class JSONTest {
public static void main(String[] args) {
String logFilename = "C://Temp/sample.log";
String line, json = "";
try (BufferedReader br = new BufferedReader(new FileReader(logFilename))) {
while ((line = br.readLine()) != null) {
if (isLogLine(line)) {
if (!json.isEmpty()) {
parseJson(json);
json = "";
}
} else {
json += line;
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static boolean isLogLine(String line) {
return line.matches("^\\d{4}\\-\\d{2}\\-\\d{2}\\s\\d{2}:\\d{2}:\\d{2}:\\d{3}.+$");
}
public static void parseJson(String json) throws Exception {
if (!json.startsWith("{") && !json.endsWith("}")) json = "{" + json + "}";
ObjectMapper om = new ObjectMapper();
System.out.println(om.readValue(fixJson(json), Object.class));
}
public static String fixJson(String json) {
return "{" + json.replace("}]", "}}]") + "}";
}
}
筆記:
您是否研究過logstash( https://www.elastic.co/products/logstash )? 它可以解決此問題,以及可能在嘗試解析日志時遇到的其他問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.