[Perl] last logs v1.3

作者:reistlin 发布时间:January 27, 2011 分类:原创文章

作者: reistlin
来源: http://www.reistlin.com/blog/128
更新时间: 2011.01
版权声明: 原创文章.转载请保留作者信息和原文完整.谢绝任何方式的摘要

perl.gif

googlecode1.gifgooglecode2.gif
[https://reistlin.googlecode.com/svn/trunk/perl/last_logs2.pl]

#!/usr/bin/perl
 
# name: last_logs v1.3
# author: reistlin
# website: www.reistlin.com
# date: 2011.02.28
 
use strict;
use Data::Dumper;
use Time::Local;
 
# debug switch
my $debug = 0;
 
 
####################
# Configuration
####################
 
# check logfile
my $check_file = "/home/reistlin/error.log";
 
# access.log = 1 / error.log = 2 / php_error.log = 3
my $check_type = 2;
 
 
####################
# Initialization
####################
 
my @check_array; my $check_day; my $check_hour; my $regular_day; my $regular_hour;
 
# set LANG=en_US.UTF-8
$ENV{''LANG''} = ''LANG=en_US.UTF-8'';
 
if ( $check_type == 1 ) {
	# access.log
	$check_day = `date "+%d/%b/%Y"`;
	$check_hour = `date -d "1 hours ago" "+%H"`;
	chomp $check_day;
	chomp $check_hour;
	$regular_day = ''\s\[(\d{2}\/[a-zA-Z]{3}\/\d{4})'';
	$regular_hour = ''\:(\d{2})\:\d{2}\:\d{2}\s'';
} elsif ( $check_type == 2 ) {
	# error.log
	$check_day = `date "+%Y/%m/%d"`;
	$check_hour = `date -d "1 hours ago" "+%H"`;
	chomp $check_day;
	chomp $check_hour;
	$regular_day = ''^(\d{4}\/\d{2}\/\d{2})'';
	$regular_hour = ''\s(\d{2})\:\d{2}\:\d{2}\s'';
} elsif ( $check_type == 3 ) {
	# php_error.log
	$check_day = `date "+%d-%b-%Y"`;
	$check_hour = `date -d "1 hours ago" "+%H"`;
	chomp $check_day;
	chomp $check_hour;
	$regular_day = ''^\[(\d{2}\-[a-zA-Z]{3}\-\d{4})'';
	$regular_hour = ''\s(\d{2})\:\d{2}\:\d{2}\]\s'';
} else {
	print "[ERROR] Check logfile type error!\n";
	print "[ERROR] Please reset the logfile type!\n";
	print "[INFO] access.log = 1\n";
	print "[INFO] error.log = 2\n";
	print "[INFO] php_error.log = 3\n";
	exit;
}
 
 
####################
# Check logfile
####################
 
if ( ! -e $check_file ) {
	print "[Error] $check_file $!\n";
	exit;
}
 
 
####################
# Open logfile
####################
 
open(FILE, $check_file);
 
while (<FILE>) {
	$_ =~ m/$regular_day/;
	# check day
	if ( $1 eq $check_day ) {
		push(@check_array, $_);
	}
}
 
close(FILE);
 
 
####################
# Search logs
####################
 
if ( @check_array ) {
	foreach my $line (@check_array) {
		$line =~ m/$regular_hour/;
		# check hour
		if ( $1 eq $check_hour ) {
			print $line;
		}
	}
}

标签: perl

评论已关闭