Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses

Re: Removing old records from log files

by tachyon (Chancellor)
on Aug 22, 2001 at 14:56 UTC ( #106912=note: print w/replies, xml ) Need Help??

in reply to Removing old records from log files

The general method is as you state:

my $find_this = qr/$arbitray data/; open OLD, $log or die $!; open NEW, ">$new_log" or die $!; while (<OLD>) { next unless /$find_this/; print NEW $_ while <OLD>; } close OLD; close NEW; rename $new_log, $log or die $!;

With this code we use the quote regex operator to only compile our regex once to speed it up. We next away until we find our condition and then dump the rest of the file using another while so we never re-enter out outer loop.

Assuming you are using this you have some options:

First you could set up a cron to automatically rename your logfile every X hours - presumably you are just grabbing the last X days/hour/minutes of data so this save you the need.

Alternatively you could check the file size every X hours and record the number. You then use seek LOG, $position, 0 to blast straight to your starting point. The first line will be a partial (probably) so you need to consider that.

As yet another option you can use seek LOG, $offset, $whence If whence is 0 then a positive offset of x gets you x bytes into the file immediately. If $whence is 2 the a negative offset -x gets you to -x bytes from the end. Either way you read in a full line and then use the old halving the difference to find you start point. It's like the guess a number between 1 and 128. You start at 64 higher 96 higher 112 lower 104 higher 108 higher 110 higher - tada must be 111. Thus we have found the number in 7 tries - a big gain on trying all 128 options. The bigger the file the better this will work as it is a geometrical method of finding the start rather than a linear one. The efficiency gain will be highest if the bit you want is a small % of the total file as you still have to write out the new file.

Often when people post their real code we can offer suggestion that increase speed significantly. Hint {smile}




Log In?

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

How do I use this? | Other CB clients
Other Users?
Others about the Monastery: (5)
As of 2020-06-05 12:10 GMT
Find Nodes?
    Voting Booth?
    Do you really want to know if there is extraterrestrial life?

    Results (37 votes). Check out past polls.