create log files by date in slice and test it
authorDobrica Pavlinusic <dpavlin@rot13.org>
Sun, 12 Feb 2012 19:18:58 +0000 (20:18 +0100)
committerDobrica Pavlinusic <dpavlin@rot13.org>
Sun, 12 Feb 2012 19:18:58 +0000 (20:18 +0100)
lib/WarnColor.pm
t/WarnColor.t [new file with mode: 0755]

index 4afb940..cdcf14d 100644 (file)
@@ -3,6 +3,8 @@ package WarnColor;
 use warnings;
 use strict;
 
+use POSIX qw(strftime);
+
 sub BEGIN {
 
        sub port2color {
@@ -13,6 +15,31 @@ sub BEGIN {
                return "\e[${c}m$port\e[0m";
        }
 
+       sub __log {
+               my $log = $ENV{SLICE} ? "$ENV{SLICE}/log/" : '/tmp/';
+
+               my ( $ss,$mm,$hh, $d,$m,$yyyy ) = localtime(time());
+               $yyyy += 1900;
+               $mm   += 1;
+
+               $log .= sprintf("%04d-%02d-%02d.", $yyyy, $m, $d );
+
+               $log .= $ENV{NAME}  ? $ENV{NAME} : $1 if $0 =~ m{([^/]+)$};
+
+               my $line = sprintf("%04d-%02d-%02d %02d:%02d:%02d %s\n", $yyyy,$m,$d, $hh,$mm,$ss, join(' ',@_));
+               $line =~ s/[\r\n]+$/\n/;
+
+               print STDERR "creating $log\n" unless -e $log;
+
+               open(my $fh, '>>', $log);
+               print $fh $line;
+               close $fh;
+
+               print STDERR $line; # XXX debug
+       }
+
+if ( -t STDOUT ) { # colorize only if run from terminal !
+
        $SIG{__WARN__} = sub {
                return unless @_;
                my $msg = join('', @_);
@@ -22,10 +49,28 @@ sub BEGIN {
                $msg =~ s{\[(\d+)\]}{ '[' . port2color($1) . ']' }eg;
                $msg =~ s{(\||=>)}{\e[34m$1\e[0m}g; # blue
                $msg =~ s{(["\{\}\#])}{\e[33m$1\e[0m}g; # yellow
-               print STDERR $msg unless $msg =~ m{^#} && ! $ENV{DEBUG};
+               __log $msg unless $msg =~ m{^#} && ! $ENV{DEBUG};
                return 1;
-       } if -t STDOUT; # colorize only if run from terminal !
+       };
+
+} else {
+
+       $SIG{__WARN__} = sub {
+               __log @_;
+       };
+
+       $SIG{__DIE__} = sub {
+               if($^S) {
+                       # We're in an eval {} and don't want log
+                       # this message but catch it later
+                       return;
+               }
+               __log 'DIE', @_;
+               die @_;
+       };
 
 }
 
+} # BEGIN
+
 1;
diff --git a/t/WarnColor.t b/t/WarnColor.t
new file mode 100755 (executable)
index 0000000..21f70d0
--- /dev/null
@@ -0,0 +1,26 @@
+#!/usr/bin/perl
+use strict;
+use warnings;
+
+use Test::More tests => 4;
+use File::Path qw(remove_tree);
+use Data::Dump qw(dump);
+
+use lib 'lib';
+
+use_ok 'WarnColor';
+
+ok warn('test warn'), 'warn';
+
+remove_tree '/tmp/slice' if -e '/tmp/slice';
+
+mkdir '/tmp/slice';
+mkdir '/tmp/slice/log';
+$ENV{SLICE} = '/tmp/slice';
+$ENV{NAME}  = 'test';
+
+ok warn('slice warn'), 'with ENV';
+
+ok glob('/tmp/slice/log/*'), 'log created';
+
+