Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling
 
PerlMonks  

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 128.2.2.40 id=firewall time= +"2007-11-16 16:03:37" fw=WS2000-Store 02 pri=1 proto=6(tcp) src=128.2 +.2.200 dst=128.2.100.106 mid= 1013 mtp= 2 msg=TCP connection request + received is invalid, dropping packet Src 23 Dst 4631 from EXT n/w ag +ent=Firewall
OUTPUT
$VAR1 = '2007-11-16'; $VAR2 = '16:05:40'; $VAR3 = 'Local1.Alert'; $VAR4 = '128.2.2.40'; $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' => '128.2.2.200', 'mtp' => '2', 'mid' => '1013', 'fw' => 'WS2000-Store 02', 'agent' => 'Firewall', 'id' => 'firewall', 'pri' => '1', 'dst' => '128.2.100.106' };
... 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?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others romping around the Monastery: (4)
As of 2020-04-10 07:15 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    The most amusing oxymoron is:
















    Results (49 votes). Check out past polls.

    Notices?