[英]How to parse a log file in Java?
我有一个包含这两行数据的文件。
Jan 1 22:54:17 drop %LOGSOURCE% >eth1 rule: 7; rule_uid: {C1336766-9489- 4049-9817-50584D83A245}; src: 70.77.116.190; dst: %DSTIP%; proto: tcp; product: VPN-1 & FireWall-1; service: 445; s_port: 2612;
Jan 1 23:02:56 accept %LOGSOURCE% >eth1 inzone: External; outzone: Local; rule: 3; rule_uid: {723F81EF-75C9-4CBB-8913-0EBB3686E0F7}; service_id: icmp-proto; ICMP: Echo Request; src: 24.188.22.101; dst: %DSTIP%; proto: icmp; ICMP Type: 8; ICMP Code: 0; product: VPN-1 & FireWall-1;
我真的可以知道将它们解析为不同列的代码是什么吗? 一个问题是
eth1 rule:7;
eth1 inzone: External; outzone: Local;
我想让它们属于同一列。 我真的需要一些绝望的帮助,因为我没有编程知识,而且我受命这样做> <
您可能会从Java的字符串拆分函数开始:
我假设您可以将第一列作为从%LOGSOURCE%之后的开头到“>”的所有内容。 我还猜想还有其他的列会合并在一起,最后您只希望每行有一定数量的列。
您可以使用如下代码:
//a line of the log can be split on '>' and ';' for the other columns of interest
//logLine is a line off the your log, I'm assuming it's a string object
string[] splitLine = logLine.split("[>;]+");
//I'm pretending there are 7 columns, for simplicity sake I'm using an ArrayList
// of string arrays (ArraList<string[]>) that would get declared
//above all this called logList
string[] logEntry = new string[7];
//Save the time stamp of the log entry by iterating through splitLine
for(int counter1 = 0; counter1 < splitLine.length; counter1++)
{
//Timestamp column
if(counter1 == 0)
logEntry[0] = splitLine[counter1];
//First column
if(counter1 == 1)
logEntry[1] = splitLine[counter1];
//Logic to determine what needs to get appended to second column,
//could be many if statements
if(...)
logEntry[1] += splitLine[counter1];
//Logic to determine what starts third column
if(...)
logEntry[2] = splitLine[counter1];
//Logic to determine what needs to get appended to third column,
//could be many if statements
if(...)
logEntry[2] += splitLine[counter1];
//And so on... till you fill all your columns up or as much as you want
}
//Add your columned log to your list for use after you've parsed up the file
logList.add(logEntry);
您可能会将所有这些逻辑都放在了for循环中,该循环不断从日志中捕获一行到代码示例顶部使用的logLine字符串中。 这不是最有效的方法,但是非常简单。 希望这可以帮助您开始解决您的问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.