如何解析日志文件并将数据加载到数据库中


how to parse a log file and load data into a database

如何解析文本文件以提取数据,包括日期,并将其加载到数据库表data_table中?

这是我的文本文档log.txt:

127.0.0.1 1.255.255.255 - - [30/Sep/2014:23:58:33 +0200] GET http://www.google.com HTTP/1.1 200 u:123456789 ourl:http://google.com/image ac:text ssl:1
127.0.0.1 1.255.255.255 - - [30/Sep/2014:23:58:33 +0200] GET http://www.google.com HTTP/1.1 200 u:123456789 new_data ourl:http://google.com/image ac:text ssl:1
...

这两行非常相似,但第二行是新值new_data

在我的数据库表中有以下列:

|IP_1|IP_2|date_time|URL|HTTP_version|port|USER_ID|new_data|OURL|ac|ssl|

SQL代码

Load data local infile 'D:/log.txt' into table `data_table` fields terminated by ' ' lines terminated by ''n'

如何从文本文件中解析'-','-','+0200','GET'?如果行中没有值,我应该如何填充列new_data(最好的解决方案应该用NULL填充)?

如果你能给我一些想法,我将不胜感激。也可以是PHP脚本。

由于添加了PHP标志,我在这里提出了一个PHP解决方案:

$line = "127.0.0.1 1.255.255.255 - - [30/Sep/2014:23:58:33 +0200] GET http://www.google.com HTTP/1.1 200 u:123456789 new_data ourl:http://google.com/image ac:text ssl:1";
if( preg_match('/^([^''s]+)''s([^''s]+)''s''-''s''-''s''[([^'']]+)'']''s[A-Z]+''s([^''s]+)''s([^''s]+)''s([^''s]+)''su:([^''s]+)''s([^''s]+)''sourl:([^''s]+)''sac:([^''s]+)''sssl:([^''s]+)/',$line,$m) )
{  
$v= array();
$v['IP_1']=$m[1];
$v['IP_2']=$m[2];
$v['date_time']=$m[3];
$v['URL']=$m[4];
$v['HTTP_version']=$m[5];
$v['HTTPcode']=$m[6];
$v['USER_ID']=$m[7];
$v['new_data']=$m[8];
$v['OURL']=$m[9];
$v['ac']=$m[10];
$v['ssl']=$m[11];
print_r($v);
}

注意:它不是端口,而是HTTP返回代码。

您可以在上了解更多关于PCRE的信息http://php.net/manual/en/book.pcre.php

首先,在文件上file_get_contents()并将其内容保存在变量中,然后在'r'nexplode()。现在您可以循环这些内容,如下所示:

// ... inside the loop:
// $log = $allLines[$i] where $i is an iterator.
// Example log value: Client IP - - [31/Aug/2017:05:48:10 +0400] "GET / HTTP/1.1" 200 1020 "http://website.com/dir" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36"
$parser = explode('"', $log);
$ip = explode(" - - ", $parser[0]);
$ip = $ip[0];
$info = $parser[1];
$location = $parser[3];
$browser = $parser[5];
echo "<tr>
    <td>IP</td>
    <td>Info</td>
    <td>Location</td>
    <td>Browser</td>
  </tr>
  <tr>
    <td>$ip</td>
    <td>$info</td>
    <td>$location</td>
    <td>$browser</td>
  </tr>";