| 1 | package Lab::Connection::Log; | ||
| 2 | #ABSTRACT: Role adding logging capability to connections | ||
| 3 | $Lab::Connection::Log::VERSION = '3.899'; | ||
| 4 | use v5.20; | ||
| 5 | |||
| 6 | use warnings; | ||
| 7 | use strict; | ||
| 8 | |||
| 9 | use Role::Tiny; | ||
| 10 | |||
| 11 | use YAML::XS; | ||
| 12 | use Data::Dumper; | ||
| 13 | use autodie; | ||
| 14 | use Carp; | ||
| 15 | |||
| 16 | use Lab::Connection::LogMethodCall qw(dump_method_call); | ||
| 17 | |||
| 18 | around 'new' => sub { | ||
| 19 | my $orig = shift; | ||
| 20 | my $proto = shift; | ||
| 21 | my $class = ref($proto) || $proto; | ||
| 22 | my $twin = undef; | ||
| 23 | |||
| 24 | # getting fields and _permitted from parent class | ||
| 25 | my $self = $class->$orig(@_); | ||
| 26 | |||
| 27 | $self->_construct($class); | ||
| 28 | |||
| 29 | # open the log file | ||
| 30 | my $logfile = $self->logfile(); | ||
| 31 | if ( not defined $logfile ) { | ||
| 32 | croak 'missing "logfile" parameter in connection'; | ||
| 33 | } | ||
| 34 | |||
| 35 | # FIXME: Currently it's not possible to have a filehandle in %fields, as | ||
| 36 | # this breaks the dclone used in Sweep.pm. | ||
| 37 | open my $fh, '>', $self->logfile(); | ||
| 38 | close $fh; | ||
| 39 | |||
| 40 | return $self; | ||
| 41 | |||
| 42 | }; | ||
| 43 | |||
| 44 | sub dump_ref { | ||
| 45 | my $self = shift; | ||
| 46 | my $ref = shift; | ||
| 47 | open my $fh, '>>', $self->logfile(); | ||
| 48 | print {$fh} Dump($ref); | ||
| 49 | close $fh; | ||
| 50 | } | ||
| 51 | |||
| 52 | for my $method ( | ||
| 53 | qw/Clear Write Read Query BrutalRead LongQuery BrutalQuery | ||
| 54 | timeout block_connection unblock_connection is_blocked/ | ||
| 55 | ) { | ||
| 56 | around $method => sub { | ||
| 57 | my $orig = shift; | ||
| 58 | my $self = shift; | ||
| 59 | my $retval = $self->$orig(@_); | ||
| 60 | |||
| 61 | # Inside the around modifier, we need to skip 2 levels to get to the | ||
| 62 | # true caller. | ||
| 63 | my $caller = caller(2); | ||
| 64 | if ( $caller !~ /Lab::Connection.*/ ) { | ||
| 65 | |||
| 66 | my $index = $self->log_index(); | ||
| 67 | |||
| 68 | my $log = dump_method_call( $index, $method, @_ ); | ||
| 69 | |||
| 70 | $log->{retval} = $retval; | ||
| 71 | $self->dump_ref($log); | ||
| 72 | |||
| 73 | $self->log_index( ++$index ); | ||
| 74 | } | ||
| 75 | return $retval; | ||
| 76 | }; | ||
| 77 | } | ||
| 78 | |||
| 79 | 1; | ||
| 80 | |||
| 81 | __END__ |