java - 如何用Java解析日志文件?

标签 java parsing logfile logparser

我有一个包含这两行数据的文件。

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 的字符串分割函数开始:

Oracle Doc

Look at example 3

我假设您可以将第一列作为 %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 字符串中。这不是最有效的方法,但非常简单。希望这能让您开始解决您的问题。

关于java - 如何用Java解析日志文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31514066/

相关文章:

java - 在java中发出http请求的最简单方法

java - Java判断字符串中是否有多个字符为大写的方法

json - 如何使用嵌套字典反序列化 json?

JavaScript 字符串解析

ruby - 树顶 SGF 解析

java - 每天如何将日志文件存储在目录(具有当前日期的目录名称)中

java - 当某些值为空时,如何从逗号分隔的值列表中提取值?

java - 绑定(bind)线程运行时间

mysql - 用于日志分析的数据库类型?

c++ - 除了 createfile 和 openfile 之外,还有任何用于获取文件句柄的 Windows API?