Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change

Re: Parsing a log file

by reasonablekeith (Deacon)
on Nov 27, 2007 at 17:13 UTC ( #653314=note: print w/replies, xml ) Need Help??

in reply to Parsing a log file

Your data seems a bit too ambiguous to parse easily. You can't, as in your example, just split on white space, as your 'msg' data field is an unquoted string (so you'll get a seperate field for each word in the string). Your best option is to get the log file tab delimited (I'm guessing it isn't at the moment), and stop reading this post.

However, if you don't have control of the data, you'll just have to take a stab. With the assumption that the first four fileds don't have spaces in them, and that the key/value data that follows doesn't have any '='s in the data, then you could do something like this...

#!/usr/bin/perl use Data::Dumper; while(<DATA>) { chomp; my ($log_date, $log_time, $something, $ip_address, $keyed_data_str +ing ) = split /\s+/, $_, 5; my %keyed_data_hash; while( $keyed_data_string =~ s/\s*(\w+)=\s*([^=]*)$/ $keyed_data_h +ash{$1} = $2; ''/xsge) { 1 } print Dumper($log_date, $log_time, $something, $ip_address, \%keye +d_data_hash); } __DATA__ 2007-11-16 16:05:40 Local1.Alert id=firewall time= +"2007-11-16 16:03:37" fw=WS2000-Store 02 pri=1 proto=6(tcp) src=128.2 +.2.200 dst= mid= 1013 mtp= 2 msg=TCP connection request + received is invalid, dropping packet Src 23 Dst 4631 from EXT n/w ag +ent=Firewall
$VAR1 = '2007-11-16'; $VAR2 = '16:05:40'; $VAR3 = 'Local1.Alert'; $VAR4 = ''; $VAR5 = { 'msg' => 'TCP connection request received is invalid, drop +ping packet Src 23 Dst 4631 from EXT n/w', 'proto' => '6(tcp)', 'time' => '"2007-11-16 16:03:37"', 'src' => '', 'mtp' => '2', 'mid' => '1013', 'fw' => 'WS2000-Store 02', 'agent' => 'Firewall', 'id' => 'firewall', 'pri' => '1', 'dst' => '' };
... which works by pulling off the easy four first fields, and then works from the end of the rest of the data, creating a key pair hash.

It's pretty ugly, but with your data, I don't see a way around it.

my name's not Keith, and I'm not reasonable.

Log In?

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://653314]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others avoiding work at the Monastery: (6)
As of 2022-08-08 06:59 GMT
Find Nodes?
    Voting Booth?

    No recent polls found