don't timestamp lines which allready have timestamp at beginning
[cloudstore.git] / lib / WarnColor.pm
index 4afb940..4f1b7b8 100644 (file)
@@ -3,6 +3,8 @@ package WarnColor;
 use warnings;
 use strict;
 
+use POSIX qw(strftime);
+
 sub BEGIN {
 
        sub port2color {
@@ -13,6 +15,39 @@ 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;
+               $m    += 1;
+
+               $log .= sprintf("%04d-%02d-%02d.", $yyyy, $m, $d );
+
+               $log .= $ENV{NAME}  ? $ENV{NAME} : $1 if $0 =~ m{([^/]+)$};
+
+               my $line = join(' ', @_);
+               if ( $line =~ s{^(?:\e\[\d+m)+(\d\d\d\d)\W(\d\d)\W(\d\d) (\d\d:\d\d:\d\d)}{$1-$2-$3 $4} ) {
+                       # have timestamp allready
+               } else {
+                       my $time = sprintf("%04d-%02d-%02d %02d:%02d:%02d", $yyyy,$m,$d, $hh,$mm,$ss);
+                       $line = "$time $line";
+               }
+
+               $line =~ s/[\r\n]+$/\n/;
+
+               print STDERR "creating $log\n" unless -e $log;
+
+               if ( open(my $fh, '>>', $log) ) {
+                       print $fh $line;
+                       close $fh;
+               } else {
+                       print STDERR $line;
+               }
+       }
+
+if ( -t STDOUT ) { # colorize only if run from terminal !
+
        $SIG{__WARN__} = sub {
                return unless @_;
                my $msg = join('', @_);
@@ -22,10 +57,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;