| 1 | package Class::Component::Component::Plaggerize::Log; | ||
| 2 | use strict; | ||
| 3 | use warnings; | ||
| 4 | |||
| 5 | use Encode (); | ||
| 6 | my $TERM_ANSICOLOR_ENABLED = eval { use Term::ANSIColor; 1; }; | ||
| 7 | |||
| 8 | |||
| 9 | my %levels = ( | ||
| 10 | debug => 1, | ||
| 11 | warn => 2, | ||
| 12 | info => 3, | ||
| 13 | error => 4, | ||
| 14 | ); | ||
| 15 | |||
| 16 | sub setup_config { | ||
| 17 | my $class = shift; | ||
| 18 | my $config = $class->NEXT( setup_config => @_ ); | ||
| 19 | |||
| 20 | $config->{global} = {} unless $config->{global}; | ||
| 21 | $config->{global}->{log} = {} unless $config->{global}->{log}; | ||
| 22 | $config->{global}->{log}->{level} = 'debug' unless $config->{global}->{log}->{level}; | ||
| 23 | |||
| 24 | %levels = %{ $config->{global}->{log}->{levels} } if ref($config->{global}->{log}->{levels}) eq 'HASH'; | ||
| 25 | |||
| 26 | $config; | ||
| 27 | } | ||
| 28 | |||
| 29 | sub log { | ||
| 30 | my ($self, $level, $msg, %opt) = @_; | ||
| 31 | $self->NEXT( log => @_ ); | ||
| 32 | |||
| 33 | my $conf = $self->conf->{global}->{log}; | ||
| 34 | return unless ( $levels{$level} || 0 ) >= ( $levels{$conf->{level}} || 0 ); | ||
| 35 | |||
| 36 | # hack to get the original caller as Plugin | ||
| 37 | my $caller = $opt{caller}; | ||
| 38 | unless ($caller) { | ||
| 39 | my $i = 0; | ||
| 40 | while (my $c = caller($i++)) { | ||
| 41 | last if $c !~ /Plugin/; | ||
| 42 | $caller = $c; | ||
| 43 | } | ||
| 44 | $caller ||= caller(3); | ||
| 45 | } | ||
| 46 | |||
| 47 | my $fh = defined($conf->{fh}) ? $conf->{fh} : \*STDOUT; | ||
| 48 | my $ansicolor = defined($conf->{ansicolor}) ? $conf->{ansicolor} : 'red'; | ||
| 49 | |||
| 50 | chomp($msg); | ||
| 51 | if ( $conf->{encoding} ) { | ||
| 52 | $msg = Encode::decode_utf8($msg) unless utf8::is_utf8($msg); | ||
| 53 | $msg = Encode::encode( $conf->{encoding}, $msg ); | ||
| 54 | } | ||
| 55 | |||
| 56 | local $| = 1; | ||
| 57 | print $fh Term::ANSIColor::color($ansicolor) if $ansicolor && $TERM_ANSICOLOR_ENABLED; | ||
| 58 | print $fh "$caller [$level] $msg\n"; | ||
| 59 | print $fh Term::ANSIColor::color("reset") if $ansicolor && $TERM_ANSICOLOR_ENABLED; | ||
| 60 | } | ||
| 61 | |||
| 62 | 1; |