summaryrefslogtreecommitdiff
path: root/lib/Net/HTTP/Spore/Role/Debug.pm
blob: e229229b401f4b5e89764baed14be39bda8bfb92 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package Net::HTTP::Spore::Role::Debug;

use IO::File;
use Moose::Role;

has trace => (
    is      => 'rw',
    isa     => 'Int',
    lazy    => 1,
    default => sub {
        my $self      = shift;
        my $trace_env = $ENV{SPORE_TRACE} || 0;
        #my @stack = caller; use YAML; warn Dump \@stack;
        my ($fh, $level);
        if ( $trace_env =~ /(\d)=(.+)$/ ) {
            $level = $1;
            $fh = IO::File->new( $2, 'w' )
              or die("Cannot open trace file $1");
        }
        else {
            $level = $trace_env;
            $fh = IO::File->new('>&STDERR')
              or die('Duplication of STDERR for debug output failed (perhaps your STDERR is closed?)');
        }
        $fh->autoflush();
        $self->_trace_fh($fh);
        return $level;
    }
);

has _trace_fh => (
    is      => 'rw',
    isa     => 'GLOB',
);

sub _trace_msg {
    my $self     = shift;
    my $template = shift;
    return unless $self->trace;
    my $fh = $self->_trace_fh();
    print $fh (sprintf( $template, @_ )."\n");
}

sub _trace_verbose {
    my $self = shift;
    return unless $self->trace && $self->trace > 1;
    $self->_trace_msg(@_);
}

1;