1a40fee4b4323d24cd0cd3aa2f769eb3faa359e5
[cloudstore.git] / lib / WarnColor.pm
1 package WarnColor;
2
3 use warnings;
4 use strict;
5
6 use POSIX qw(strftime);
7
8 sub BEGIN {
9
10         sub port2color {
11                 my $port = shift;
12                 return "\e[1m0\e[0m" if $port == 0;
13
14                 my $c = ( $port % 6 ) + 31;
15                 return "\e[${c}m$port\e[0m";
16         }
17
18         sub __log {
19                 my $log = $ENV{SLICE} ? "$ENV{SLICE}/log/" : '/tmp/';
20
21                 my ( $ss,$mm,$hh, $d,$m,$yyyy ) = localtime(time());
22                 $yyyy += 1900;
23                 $m    += 1;
24
25                 $log .= sprintf("%04d-%02d-%02d.", $yyyy, $m, $d );
26
27                 $log .= $ENV{NAME}  ? $ENV{NAME} : $1 if $0 =~ m{([^/]+)$};
28
29                 my $line = sprintf("%04d-%02d-%02d %02d:%02d:%02d %s\n", $yyyy,$m,$d, $hh,$mm,$ss, join(' ',@_));
30                 $line =~ s/[\r\n]+$/\n/;
31
32                 print STDERR "creating $log\n" unless -e $log;
33
34                 open(my $fh, '>>', $log);
35                 if ( $fh ) {
36                         print $fh $line;
37                         close $fh;
38                 } else {
39                         print STDERR $line;
40                 }
41         }
42
43 if ( -t STDOUT ) { # colorize only if run from terminal !
44
45         $SIG{__WARN__} = sub {
46                 return unless @_;
47                 my $msg = join('', @_);
48                 if ( $msg =~ s{ line (\d+)\.}{ +$1} ) {
49                         $msg =~ s{^(.+)( at .+)}{\e[31m$1\e[0m$2} if $msg !~ m{^#};
50                 }
51                 $msg =~ s{\[(\d+)\]}{ '[' . port2color($1) . ']' }eg;
52                 $msg =~ s{(\||=>)}{\e[34m$1\e[0m}g; # blue
53                 $msg =~ s{(["\{\}\#])}{\e[33m$1\e[0m}g; # yellow
54                 __log $msg unless $msg =~ m{^#} && ! $ENV{DEBUG};
55                 return 1;
56         };
57
58 } else {
59
60         $SIG{__WARN__} = sub {
61                 __log @_;
62         };
63
64         $SIG{__DIE__} = sub {
65                 if($^S) {
66                         # We're in an eval {} and don't want log
67                         # this message but catch it later
68                         return;
69                 }
70                 __log 'DIE', @_;
71                 die @_;
72         };
73
74 }
75
76 } # BEGIN
77
78 1;