如何在Windows XP上使用Perl存档.log文件?

时间:2011-04-22 19:49:37

标签: windows perl logging archiving

以一种尽可能简单的方式,我想知道是否有人知道如何在Windows XP目录中存档.log文件,只需使用当前“localtime()”作为文件名的一部分命名它们? (不要假设日志文件存在锁定。)我尝试了各种不同的方法,但无法解决它......并且网上没有很好的例子。

以下是我要找的内容:

for (all files > that 1 day old)   
  rename file  to  file.[datestamp].log
end

4 个答案:

答案 0 :(得分:2)

嗯,这看起来很容易,我可能误解了一些东西。任务是将例如“yada.log”移动到“yada.2011-05-04.log”?那怎么样:

use strict;
use warnings;

use File::Copy;
use POSIX qw(strftime);

my $dir = $ARGV[0] or die "Usage: $0 <directory>";
my $now_string = strftime "%Y-%m-%d_%H%M%S", localtime;

opendir DIR, $dir or die $!;
my @files = readdir DIR;

chdir $dir or die $!;
for my $file (@files) {
    next if (-d $file);
    next unless ($file =~ /^(.*)(\.log)$/i);
    my $dst = $1 . "." . $now_string . $2;
    move ($file, $dst) or die "Failed to move $file: $!";
}

答案 1 :(得分:0)

opendir(FILES, '*logdir*');
my @files = readdir FILES;
closedir(FILES);
foreach(@files){
    system "move $_ $_.".localtime().".log" if -A $_ > *age*;
}

答案 2 :(得分:0)

感谢TLP,我最终是这样做的!这个脚本在第12行上有问题,但它几乎没有用。

use strict; 
use warnings;
use File::Copy; 
use POSIX qw(strftime); 

my $dir;
my $file;

if ( @ARGV = 2 ) { 
  print "Two args accepted."; 
  $dir = $ARGV[0] or die "Usage: <directory> <filename>";
  $file = $ARGV[1] or die "Usage: <directory> <filename>";
  goto runblock; 
}
else { print "Number of arguments must be 2: directory filename\n"; goto fail; }

runblock: print "Renaming $file .\n";

chdir $dir or die $!;
my $now_string = strftime "%Y-%m-%d_%H%M%S", localtime; 
if (-e $file) {
  if (-A $file > 7 ) {
    my $dst = "siteAlive." . $now_string . ".log"; 
    move($file, $dst) or die "Failed to move $file: $!";
    goto endscript;
  }
} 

fail: print "Failed to rename $file . Try again.\n" ;
endscript: print "End of script.\n";

答案 3 :(得分:0)

也许有些模块可以为您完成此操作,例如Logfile::Rotate