ConsoleLogger.pm

filter: Statementstmt 92.5% 272 / 294 Branchbran 82.5% 99 / 120 Conditioncond 74.0% 40 / 54 MC/DCmcdc 58.0% 18 / 31 Subroutinesub 87.7% 43 / 49 Podpod 100% 2 / 2 totaltotal 86.1% 474 / 550 CC 90 SCAR 22.9
CC
90
Cov
88%
_parse_body
28.3
_log_cookies
17.0
_build_term_width
12.2
CRAP 9.9
« ConsoleLogger/Easy.pm ↑ Summary ConsoleLogger/Everywhere.pm »
1 package LWP::ConsoleLogger;
2  
3 14 ▶use Moo;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 14 ▶use MooX::StrictConstructor;
Subroutine BEGIN: called CC=1 SCAR=0.0
5  
6 14 ▶use 5.006;
Subroutine BEGIN: called CC=1 SCAR=0.0
7  
8 14 our $VERSION = '1.000003';
9  
10 14 ▶use Data::Printer { end_separator => 1, hash_separator => ' => ' };
Subroutine BEGIN: called CC=1 SCAR=0.0
11 14 ▶use DateTime ();
Subroutine BEGIN: called CC=1 SCAR=0.0
12 14 ▶use Encode ();
Subroutine BEGIN: called CC=1 SCAR=0.0
13 14 ▶use HTML::Restrict ();
Subroutine BEGIN: called CC=1 SCAR=0.0
14 14 ▶use HTTP::Body ();
Subroutine BEGIN: called CC=1 SCAR=0.0
15 14 ▶use HTTP::CookieMonster ();
Subroutine BEGIN: called CC=1 SCAR=0.0
16 14 ▶use JSON::MaybeXS qw( decode_json );
Subroutine BEGIN: called CC=1 SCAR=0.0
17 14 ▶use List::AllUtils qw( any apply none );
Subroutine BEGIN: called CC=1 SCAR=0.0
18 14 ▶use Log::Dispatch ();
Subroutine BEGIN: called CC=1 SCAR=0.0
19 14 ▶use Module::Load::Conditional qw( can_load );
Subroutine BEGIN: called CC=1 SCAR=0.0
20 14 ▶use Parse::MIME qw( parse_mime_type );
Subroutine BEGIN: called CC=1 SCAR=0.0
21 14 ▶use Ref::Util qw( is_arrayref is_blessed_ref is_ref );
Subroutine BEGIN: called CC=1 SCAR=0.0
22 14 ▶use Term::Size::Any ();
Subroutine BEGIN: called CC=1 SCAR=0.0
23 14 ▶use Term::Table 0.013 ();
Subroutine BEGIN: called CC=1 SCAR=0.0
24 14 ▶use Try::Tiny qw( catch try );
Subroutine BEGIN: called CC=1 SCAR=0.0
25 14 ▶use Types::Common::Numeric qw( PositiveInt );
Subroutine BEGIN: called CC=1 SCAR=0.0
26 14 ▶use Types::Standard qw( ArrayRef Bool CodeRef InstanceOf );
Subroutine BEGIN: called CC=1 SCAR=0.0
27 14 ▶use URI::QueryParam qw();
Subroutine BEGIN: called CC=1 SCAR=0.0
28  
29 14 my $json_regex = qr{vnd.*\+json};
30  
31 14 has content_pre_filter => (
32 is => 'rw',
33 isa => CodeRef,
34 );
35  
36 14 has dump_content => (
37 is => 'rw',
38 isa => Bool,
39 default => 0,
40 );
41  
42 14 has dump_cookies => (
43 is => 'rw',
44 isa => Bool,
45 default => 0,
46 );
47  
48 14 has dump_headers => (
49 is => 'rw',
50 isa => Bool,
51 default => 1,
52 );
53  
54 14 has dump_params => (
55 is => 'rw',
56 isa => Bool,
57 default => 1,
58 );
59  
60 14 has dump_status => (
61 is => 'rw',
62 isa => Bool,
63 default => 1,
64 );
65  
66 14 has dump_text => (
67 is => 'rw',
68 isa => Bool,
69 default => 1,
70 );
71  
72 14 has dump_title => (
73 is => 'rw',
74 isa => Bool,
75 default => 1,
76 );
77  
78 14 has dump_uri => (
79 is => 'rw',
80 isa => Bool,
81 default => 1,
82 );
83  
84 14 has headers_to_redact => (
85 is => 'rw',
86 isa => ArrayRef,
87 lazy => 1,
88 builder => '_build_headers_to_redact',
89 );
90  
91 has html_restrict => (
92 is => 'rw',
93 isa => InstanceOf ['HTML::Restrict'],
94 lazy => 1,
95 3 ▶ default => sub { HTML::Restrict->new },
Subroutine __ANON__: called CC=1 SCAR=0.0
96 14 );
97  
98 has logger => (
99 is => 'rw',
100 isa => InstanceOf ['Log::Dispatch'],
101 lazy => 1,
102 handles => { _debug => 'debug' },
103 18 ▶ default => sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
104 18 return Log::Dispatch->new(
105 outputs => [
106 [ 'Screen', min_level => 'debug', newline => 1, utf8 => 1, ],
107 ],
108 );
109 },
110 14 );
111  
112 14 has params_to_redact => (
113 is => 'rw',
114 isa => ArrayRef,
115 lazy => 1,
116 builder => '_build_params_to_redact',
117 );
118  
119 14 has pretty => (
120 is => 'rw',
121 isa => Bool,
122 default => 1,
123 );
124  
125 14 has term_width => (
126 is => 'rw',
127 isa => PositiveInt,
128 required => 0,
129 lazy => 1,
130 builder => '_build_term_width',
131 );
132  
133 14 has text_pre_filter => (
134 is => 'rw',
135 isa => CodeRef,
136 );
137  
138 34 ▶sub _build_headers_to_redact {
Subroutine _build_headers_to_redact: called CC=2 SCAR=7.2
139 34 my $self = shift;
140 return $ENV{LWPCL_REDACT_HEADERS}
141 34 ▶ ? [ split m{,}, $ENV{LWPCL_REDACT_HEADERS} ]
Branch: 1 branch
BranchTrueFalseTotal
$ENV{'LWPCL_REDACT_HEADERS'} ? : 0 34 34
142 : [];
143 }
144  
145 3 ▶sub _build_params_to_redact {
Subroutine _build_params_to_redact: called CC=2 SCAR=7.2
146 3 my $self = shift;
147 return $ENV{LWPCL_REDACT_PARAMS}
148 3 ▶ ? [ split m{,}, $ENV{LWPCL_REDACT_PARAMS} ]
Branch: 1 branch
BranchTrueFalseTotal
$ENV{'LWPCL_REDACT_PARAMS'} ? : 0 3 3
149 : [];
150 }
151  
152 38 ▶sub request_callback {
Subroutine request_callback: called CC=5 SCAR=16.1
Pod documented
153 38 my $self = shift;
154 38 my $req = shift;
155 38 shift;
156  
157 38 ▶ if ( $self->dump_uri ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->dump_uri) 36 2 38
158 36 my $uri_without_query = $req->uri->clone;
159 36 $uri_without_query->query(undef);
160  
161 36 $self->_debug( $req->method . q{ } . $uri_without_query . "\n" );
162 }
163  
164 38 ▶ if ( $req->method eq 'GET' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($req->method eq 'GET') { } 32 6 38
165 32 $self->_log_params( $req, 'GET' );
166 }
167 else {
168 6 $self->_log_params( $req, $_ ) for ( 'GET', $req->method );
169 }
170  
171 38 $self->_log_headers( 'request (before sending)', $req->headers );
172  
173 # This request might have a body.
174 38 ▶ return unless $req->content;
Branch: 1 branch
BranchTrueFalseTotal
unless $req->content 32 6 38
175  
176 6 $self->_log_content($req);
177 6 $self->_log_text($req);
178 6 return;
179 }
180  
181 39 ▶sub response_callback {
Subroutine response_callback: called CC=5 SCAR=16.1
Pod documented
182 39 my $self = shift;
183 39 my $res = shift;
184 39 my $ua = shift;
185  
186 39 $self->_log_headers( 'request (after sending)', $res->request->headers );
187  
188 39 ▶ if ( $self->dump_status ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->dump_status) 37 2 39
189 37 $self->_debug( '==> ' . $res->status_line . "\n" );
190 }
191 39 ▶ if ( $self->dump_title && $ua->can('title') && $ua->title ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->dump_title and $ua->can("title") and $ua->title) 2 37 39
Condition100%6/6
$self->dump_title and $ua->can("title") and $ua->title
!ll&&!rl&&r
3162
$self->dump_title and $ua->can("title")
!ll&&!rl&&r
2298
MC/DC100%3/3
$self->dump_title and $ua->can("title") and $ua->title
$self->dump_title $ua->can("title") $ua->title
Truth table100%4/4
A and B and C
A= $self->dump_titleB= $ua->can("title")C= $ua->title
ABCresult
0XX0
10X0
1100
1111
192 2 $self->_debug(
193 'Title: ' . $self->_decode_header_value( $ua->title ) . "\n" );
194 }
195  
196 39 $self->_log_headers( 'response', $res->headers );
197 39 $self->_log_cookies( 'response', $ua->cookie_jar, $res->request->uri );
198  
199 39 $self->_log_content($res);
200 39 $self->_log_text($res);
201 39 return;
202 }
203  
204 294 ▶sub _decode_header_value {
Subroutine _decode_header_value: called CC=5 SCAR=16.1
205 294 my ( $self, $val ) = @_;
206 294 ▶ return $val unless defined $val && length $val;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $val and length $val 13 281 294
Condition100%3/3
defined $val and length $val
!ll&&!rl&&r
112281
MC/DC100%2/2
defined $val and length $val
defined $val length $val
Truth table100%3/3
A and B
A= defined $valB= length $val
ABresult
0X0
100
111
207 281 ▶ return $val if utf8::is_utf8($val);
Branch: 1 branch
BranchTrueFalseTotal
if utf8::is_utf8($val) 3 278 281
208  
209 278 my $decoded = eval { Encode::decode( 'UTF-8', $val, Encode::FB_CROAK ) };
210 278 ▶ return $decoded if defined $decoded;
Branch: 1 branch
BranchTrueFalseTotal
if defined $decoded 277 1 278
211 1 return Encode::decode( 'iso-8859-1', $val ); # never fails on byte strings
212 }
213  
214 116 ▶sub _log_headers {
Subroutine _log_headers: called CC=9 SCAR=22.9
215 116 my ( $self, $type, $headers ) = @_;
216  
217 116 ▶ return if !$self->dump_headers;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->dump_headers 10 106 116
218  
219 106 ▶ unless ( $self->pretty ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->pretty) 7 99 106
220 7 my $out = q{};
221 7 foreach my $name ( $headers->header_field_names ) {
222 0 ▶ if ( any { $name eq $_ } @{ $self->headers_to_redact } ) {
Subroutine __ANON__: not called CC=1 SCAR=0.6
Branch: 1 branch
BranchTrueFalseTotal
if (&any(sub { $name eq $_; } , @{$self->headers_to_redact;})) 0 10 10
223 0 $out .= "$name: [REDACTED]\n";
224 0 next;
225 }
226 10 for my $val ( $headers->header($name) ) {
227 11 ▶ $val = q{} unless defined $val;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $val 0 11 11
228 11 $out .= "$name: " . $self->_decode_header_value($val) . "\n";
229 }
230 }
231 7 $self->_debug($out);
232 7 return;
233 }
234  
235 99 my @rows;
236 99 foreach my $name ( sort $headers->header_field_names ) {
237 my $val
238 0 ▶ = ( any { $name eq $_ } @{ $self->headers_to_redact } )
Subroutine __ANON__: not called CC=1 SCAR=0.6
Branch: 1 branch
BranchTrueFalseTotal
&any(sub { $name eq $_; } , @{$self->headers_to_redact;}) ? : 0 266 266
239 ? '[REDACTED]'
240 : $self->_decode_header_value( $headers->header($name) );
241 266 push @rows, [ $name, $val ];
242 }
243  
244 99 $self->_draw_table( [ ucfirst $type . ' Header', 'Value' ], \@rows );
245 }
246  
247 44 ▶sub _log_params {
Subroutine _log_params: called CC=11 SCAR=24.3
248 44 my ( $self, $req, $type ) = @_;
249  
250 44 ▶ return if !$self->dump_params;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->dump_params 3 41 44
251  
252 41 my %params;
253 41 my $uri = $req->uri;
254  
255 41 ▶ if ( $type eq 'GET' ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($type eq 'GET') { } 36 5 41
elsif ($req->header('Content-Length')) { } 4 1 5
256 36 my @params = $uri->query_param;
257 36 ▶ return unless @params;
Branch: 1 branch
BranchTrueFalseTotal
unless @params 36 0 36
258  
259 0 $params{$_} = [ $uri->query_param($_) ] for @params;
260 }
261  
262 elsif ( $req->header('Content-Length') ) {
263 4 my $content_type = $req->header('Content-Type');
264 4 my $body = HTTP::Body->new(
265 $content_type,
266 $req->header('Content-Length')
267 );
268 4 $body->add( $req->content );
269 4 %params = %{ $body->param };
270  
271 4 ▶ unless ( keys %params ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (keys %params) 1 3 4
272 1 $self->_draw_table(
273 [ $type . ' Raw Body' ],
274 [ [ $req->content ] ],
275 );
276  
277 1 my @rows;
278 1 $self->_parse_body( $req->content, $content_type, \@rows );
279 1 $self->_draw_table( [ $type . ' Parsed Body' ], \@rows );
280 }
281 }
282  
283 5 my @rows;
284 5 foreach my $name ( sort keys %params ) {
285 my @values
286 0 ▶ = ( any { $name eq $_ } @{ $self->params_to_redact } )
Subroutine __ANON__: not called CC=1 SCAR=1.2
Branch: 1 branch
BranchTrueFalseTotal
is_arrayref($params{$name}) ? : 0 5 5
287 ? '[REDACTED]'
288 0 : is_arrayref( $params{$name} ) ? @{ $params{$name} }
289 5 ▶ : $params{$name};
Branch: 1 branch
BranchTrueFalseTotal
&any(sub { $name eq $_; } , @{$self->params_to_redact;}) ? : 0 5 5
290  
291 5 push @rows, [ $name, $_ ] for sort @values;
292 }
293  
294 5 $self->_draw_table( [ 'Key', 'Value' ], \@rows, "$type Params:\n" );
295 }
296  
297 39 ▶sub _log_cookies {
Subroutine _log_cookies: called CC=17 SCAR=28.4
298 39 my $self = shift;
299 39 my $type = shift;
300 39 my $jar = shift;
301 39 my $uri = shift;
302  
303 39 ▶ return if !$self->dump_cookies || !$jar || !is_blessed_ref($jar);
Branch: 1 branch
BranchTrueFalseTotal
unless $self->dump_cookies and $jar and is_blessed_ref($jar) 18 21 39
Condition83%5/6
$self->dump_cookies and $jar and is_blessed_ref($jar)
!ll&&!rl&&r
18021
$self->dump_cookies and $jar
!ll&&!rl&&r
61221
MC/DC66%2/3
$self->dump_cookies and $jar and is_blessed_ref($jar)
$self->dump_cookies $jar is_blessed_ref($jar)
Truth table75%3/4
A and B and C
A= $self->dump_cookiesB= $jarC= is_blessed_ref($jar)
ABCresult
0XX0
10X0
1100
1111
304  
305 21 ▶ if ( $jar->isa('HTTP::Cookies') ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($jar->isa('HTTP::Cookies')) { } 18 3 21
elsif ($jar->isa('HTTP::CookieJar')) { } 2 1 3
306 18 my $monster = HTTP::CookieMonster->new($jar);
307 18 my @cookies = $monster->all_cookies;
308  
309 18 my @methods = (
310 'key', 'val', 'path', 'domain',
311 'path_spec', 'secure', 'expires'
312 );
313  
314 18 foreach my $cookie (@cookies) {
315 1 my @rows;
316 1 foreach my $method (@methods) {
317 7 my $val = $cookie->$method;
318 7 ▶ if ($val) {
Branch: 1 branch
BranchTrueFalseTotal
if ($val) 5 2 7
319 5 ▶ $val = DateTime->from_epoch( epoch => $val )
Branch: 1 branch
BranchTrueFalseTotal
if $method eq "expires" 1 4 5
320 if $method eq 'expires';
321 5 ▶ $val = $self->_decode_header_value($val)
Branch: 1 branch
BranchTrueFalseTotal
unless is_ref($val) 4 1 5
322 unless is_ref($val); # leave DateTime objects alone
323 5 push @rows, [ $method, $val ];
324 }
325 }
326  
327 $self->_draw_table(
328 1 [ 'Key', 'Value' ],
329 \@rows,
330 ucfirst $type . " Cookie:\n",
331 );
332 }
333 }
334 elsif ( $jar->isa('HTTP::CookieJar') ) {
335 2 my @cookies = $jar->cookies_for($uri);
336 2 for my $cookie (@cookies) {
337 1 my @rows;
338 1 for my $key ( sort keys %{$cookie} ) {
339 8 my $val = $cookie->{$key};
340 8 ▶ if ( $val && $key =~ m{expires|_time} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($val and $key =~ /expires|_time/) 3 5 8
Condition66%2/3
$val and $key =~ /expires|_time/
!ll&&!rl&&r
053
MC/DC50%1/2
$val and $key =~ /expires|_time/
$val $key =~ /expires|_time/
Truth table66%2/3
A and B
A= $valB= $key =~ /expires|_time/
ABresult
0X0
100
111
341 3 $val = DateTime->from_epoch( epoch => $val );
342 }
343 8 ▶ $val = $self->_decode_header_value($val)
Branch: 1 branch
BranchTrueFalseTotal
if defined $val and not is_ref($val) 5 3 8
Condition66%2/3
defined $val and not is_ref($val)
!ll&&!rl&&r
035
MC/DC50%1/2
defined $val and not is_ref($val)
defined $val not is_ref($val)
Truth table66%2/3
A and not(B)
A= defined $valB= not is_ref($val)
ABresult
0X0
100
111
344 if defined $val && !is_ref($val);
345 8 push @rows, [ $key, $val ];
346 }
347  
348 $self->_draw_table(
349 [ 'Key', 'Value' ],
350 \@rows,
351 1 sprintf( '%s Cookie (%s)', ucfirst($type), $cookie->{name} ),
352 );
353 }
354 }
355 }
356  
357 72 ▶sub _get_content {
Subroutine _get_content: called CC=8 SCAR=20.9
358 72 my $self = shift;
359 72 my $r = shift;
360  
361 72 ▶ my $content
Branch: 1 branch
BranchTrueFalseTotal
$r->can('decoded_content') ? : 72 0 72
362 = $r->can('decoded_content') ? $r->decoded_content : $r->content;
363 72 ▶ return unless $content;
Branch: 1 branch
BranchTrueFalseTotal
unless $content 2 70 72
364  
365 70 my $content_type = $r->header('Content-Type');
366 70 ▶ return $content unless $content_type;
Branch: 1 branch
BranchTrueFalseTotal
unless $content_type 0 70 70
367  
368 70 ▶ my ( $type, $subtype ) = apply { lc $_ } parse_mime_type($content_type);
Subroutine __ANON__: called CC=1 SCAR=0.0
369 70 ▶ if (
Branch: 2 branches
BranchTrueFalseTotal
if ($type ne 'text' and &none(sub { $_ eq $subtype; } , 'javascript', 'html', 'json', 'xml', 'soap+xml', 'x-www-form-urlencoded') and not $subtype =~ /$json_regex/) { } 2 68 70
elsif ($self->content_pre_filter) { } 2 66 68
Condition83%5/6
$type ne "text" and &none(sub { $_ eq $subtype; } , "javascript", "html", "json", "xml", "soap+xml", "x-www-form-urlencoded") and not $subtype =~ /$json_regex/
!ll&&!rl&&r
6802
$type ne "text" and &none(sub { $_ eq $subtype; } , "javascript", "html", "json", "xml", "soap+xml", "x-www-form-urlencoded")
!ll&&!rl&&r
52162
MC/DC66%2/3
$type ne "text" and &none(sub { $_ eq $subtype; } , "javascript", "html", "json", "xml", "soap+xml", "x-www-form-urlencoded") and not $subtype =~ /$json_regex/
$type ne "text" &none(sub { $_ eq $subtype; } , "javascript", "html", "json", "xml", "soap+xml", "x-www-form-urlencoded") not $subtype =~ /$json_regex/
Truth table75%3/4
A and B and not(C)
A= $type ne "text"B= &none(sub { $_ eq $subtype; } , "javascript", "html", "json", "xml", "soap+xml", "x-www-form-urlencoded")C= not $subtype =~ /$json_regex/
ABCresult
0XX0
10X0
1100
1111
370 ( $type ne 'text' )
371 && (
372 64 ▶ none { $_ eq $subtype } (
Subroutine __ANON__: called CC=1 SCAR=0.0
373 'javascript', 'html', 'json', 'xml', 'soap+xml',
374 'x-www-form-urlencoded',
375 )
376 )
377 && $subtype !~ m{$json_regex}
378 ) {
379 2 $content = $self->_redaction_message($content_type);
380 }
381 elsif ( $self->content_pre_filter ) {
382 2 $content = $self->content_pre_filter->( $content, $content_type );
383 }
384  
385 70 return $content;
386 }
387  
388 45 ▶sub _log_content {
Subroutine _log_content: called CC=4 SCAR=13.9
389 45 my $self = shift;
390 45 my $r = shift;
391  
392 45 ▶ return unless $self->dump_content;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->dump_content 9 36 45
393  
394 36 my $content = $self->_get_content($r);
395  
396 36 ▶ return unless $content;
Branch: 1 branch
BranchTrueFalseTotal
unless $content 1 35 36
397  
398 35 ▶ unless ( $self->pretty ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->pretty) 1 34 35
399 1 $self->_debug("Content\n\n$content\n\n");
400 1 return;
401 }
402  
403 34 $self->_draw_table( ['Content'], [ [$content] ] );
404 }
405  
406 45 ▶sub _log_text {
Subroutine _log_text: called CC=8 SCAR=20.8
407 45 my $self = shift;
408 45 my $r = shift; # HTTP::Request or HTTP::Response
409  
410 45 ▶ return unless $self->dump_text;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->dump_text 9 36 45
411 36 my $content = $self->_get_content($r);
412 36 ▶ return unless $content;
Branch: 1 branch
BranchTrueFalseTotal
unless $content 1 35 36
413  
414 35 my $content_type = $r->header('Content-Type');
415  
416 # If a pre_filter converts HTML to text, for example, we don't want to
417 # reprocess the text as HTML.
418  
419 35 ▶ if ( $self->text_pre_filter && $r->isa('HTTP::Response') ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->text_pre_filter and $r->isa("HTTP::Response")) 26 9 35
Condition100%3/3
$self->text_pre_filter and $r->isa("HTTP::Response")
!ll&&!rl&&r
4526
MC/DC100%2/2
$self->text_pre_filter and $r->isa("HTTP::Response")
$self->text_pre_filter $r->isa("HTTP::Response")
Truth table100%3/3
A and B
A= $self->text_pre_filterB= $r->isa("HTTP::Response")
ABresult
0X0
100
111
420 26 ( $content, my $type )
421 = $self->text_pre_filter->( $content, $content_type, $r->base );
422 26 ▶ $content_type = $type if $type;
Branch: 1 branch
BranchTrueFalseTotal
if $type 14 12 26
423 }
424  
425 35 ▶ return unless $content;
Branch: 1 branch
BranchTrueFalseTotal
unless $content 13 22 35
426  
427 22 ▶ unless ( $self->pretty ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->pretty) 1 21 22
428 1 $self->_debug("Text\n\n$content\n\n");
429 1 return;
430 }
431  
432 21 my @rows;
433 21 $self->_parse_body( $content, $content_type, \@rows );
434 21 $self->_draw_table( ['Text'], \@rows );
435 }
436  
437 22 ▶sub _parse_body {
Subroutine _parse_body: called CC=18 SCAR=33.4
438 22 my $self = shift;
439 22 my $content = shift;
440 22 my $content_type = shift;
441 22 my $rows = shift;
442  
443 # Is this maybe JSON?
444 22 ▶ try {
Subroutine __ANON__: called CC=1 SCAR=0.0
445 22 decode_json($content);
446  
447 # If we get this far, it's valid JSON.
448 4 $content_type = 'application/json';
449 22 };
450  
451 # nothing to do here
452 22 ▶ unless ($content_type) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($content_type) 0 22 22
453 0 push @{$rows}, [$content];
454 0 return;
455 }
456  
457 22 ▶ my ( $type, $subtype ) = apply { lc $_ } parse_mime_type($content_type);
Subroutine __ANON__: called CC=1 SCAR=0.0
458 22 ▶ unless ($subtype) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($subtype) 0 22 22
459 0 push @{$rows}, [$content];
460 0 return;
461 }
462  
463 22 ▶ if ( $subtype eq 'html' ) {
Branch: 6 branches
BranchTrueFalseTotal
if ($subtype eq 'html') { } 7 15 22
elsif ($subtype eq 'xml') { } 0 15 15
elsif ($subtype eq 'json' or $subtype =~ /$json_regex/) { } 4 11 15
elsif ($type and $type eq 'application' and $subtype eq 'javascript') { } 2 9 11
elsif ($type and $type eq 'application' and $subtype eq 'x-www-form-urlencoded') { } 2 7 9
elsif (not $type or $type ne 'text') { } 1 6 7
464 7 $content = $self->html_restrict->process($content);
465 7 $content =~ s{\s+}{ }g;
466 7 $content =~ s{\n{2,}}{\n\n}g;
467  
468 7 ▶ return if !$content;
Branch: 1 branch
BranchTrueFalseTotal
unless $content 0 7 7
469 }
470 elsif ( $subtype eq 'xml' ) {
471 0 ▶ if ( can_load( modules => { 'XML::Simple' => 0 } ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (can_load("modules", {"XML::Simple", 0})) 0 0 0
472 0 ▶ try {
Subroutine __ANON__: not called CC=1 SCAR=6.9
473 0 my $pretty = XML::Simple::XMLin( $content, KeepRoot => 1 );
474 0 $content = np( $pretty, return_value => 'dump' );
475 }
476 0 ▶ catch { push @{$rows}, ["Error parsing XML: $_"] };
Subroutine __ANON__: not called CC=1 SCAR=6.9
477 }
478 }
479 ▶ elsif ( $subtype eq 'json' || $subtype =~ m{$json_regex} ) {
Condition66%2/3
$subtype eq "json" or $subtype =~ /$json_regex/
l!l&&r!l&&!r
4011
MC/DC50%1/2
$subtype eq "json" or $subtype =~ /$json_regex/
$subtype eq "json" $subtype =~ /$json_regex/
Truth table66%2/3
A or B
A= $subtype eq "json"B= $subtype =~ /$json_regex/
ABresult
1X1
011
000
480 4 ▶ try {
Subroutine __ANON__: called CC=1 SCAR=0.0
481 4 $content = decode_json($content);
482 4 $content = np( $content, return_value => 'dump' );
483 }
484 0 ▶ catch { push @{$rows}, ["Error parsing JSON: $_"] };
Subroutine __ANON__: not called CC=1 SCAR=2.6
485 }
486 ▶ elsif ( $type && $type eq 'application' && $subtype eq 'javascript' ) {
Condition83%5/6
$type and $type eq "application" and $subtype eq "javascript"
!ll&&!rl&&r
722
$type and $type eq "application"
!ll&&!rl&&r
074
MC/DC66%2/3
$type and $type eq "application" and $subtype eq "javascript"
$type $type eq "application" $subtype eq "javascript"
Truth table75%3/4
A and B and C
A= $typeB= $type eq "application"C= $subtype eq "javascript"
ABCresult
0XX0
10X0
1100
1111
487  
488 # clean it up a bit, and print some of it
489 2 $content =~ s{^\s*}{}mg;
490 2 ▶ if ( length $content > 253 ) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $content > 253) 2 0 2
491 2 $content = substr( $content, 0, 252 ) . '...';
492 }
493 }
494 ▶ elsif ($type
Condition66%4/6
$type and $type eq "application" and $subtype eq "x-www-form-urlencoded"
!ll&&!rl&&r
702
$type and $type eq "application"
!ll&&!rl&&r
072
MC/DC33%1/3
$type and $type eq "application" and $subtype eq "x-www-form-urlencoded"
$type $type eq "application" $subtype eq "x-www-form-urlencoded"
Truth table50%2/4
A and B and C
A= $typeB= $type eq "application"C= $subtype eq "x-www-form-urlencoded"
ABCresult
0XX0
10X0
1100
1111
495 && $type eq 'application'
496 && $subtype eq 'x-www-form-urlencoded' ) {
497  
498 # Pretend we have query params.
499 2 my $uri = URI->new( '?' . $content );
500 2 $content = np( $uri->query_form_hash );
501 }
502 ▶ elsif ( !$type || $type ne 'text' ) {
Condition66%2/3
not $type or $type ne "text"
l!l&&r!l&&!r
016
MC/DC50%1/2
not $type or $type ne "text"
not $type $type ne "text"
Truth table66%2/3
not(A) or B
A= not $typeB= $type ne "text"
ABresult
1X1
011
000
503  
504 # Avoid things like dumping gzipped content to the screen
505 1 $content = $self->_redaction_message($content_type);
506 }
507  
508 22 $content =~ s{^\\ }{}; # don't prefix HashRef with Data::Printer's slash
509 22 push @{$rows}, [$content];
510 }
511  
512 3 ▶sub _redaction_message {
Subroutine _redaction_message: called CC=1 SCAR=0.0
513 3 my $self = shift;
514 3 my $content_type = shift;
515 3 return sprintf '[ REDACTED by %s. Do not know how to display %s. ]',
516 __PACKAGE__, $content_type;
517 }
518  
519 33 ▶sub _build_term_width {
Subroutine _build_term_width: called CC=6 SCAR=25.0
520 33 my ($self) = @_;
521  
522 # cargo culted from Plack::Middleware::DebugLogging
523 33 my $width = eval '
524 my ($columns, $rows) = Term::Size::Any::chars;
525 return $columns;
526 ';
527  
528 33 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 33 33
529 $width = $ENV{COLUMNS}
530 if exists( $ENV{COLUMNS} )
531 0 ▶ && $ENV{COLUMNS} =~ m/^\d+$/;
Branch: 1 branch
BranchTrueFalseTotal
if exists $ENV{"COLUMNS"} and $ENV{"COLUMNS"} =~ /^\d+$/ 0 0 0
Condition0%0/3
exists $ENV{"COLUMNS"} and $ENV{"COLUMNS"} =~ /^\d+$/
!ll&&!rl&&r
000
MC/DC0%0/2
exists $ENV{"COLUMNS"} and $ENV{"COLUMNS"} =~ /^\d+$/
exists $ENV{"COLUMNS"} $ENV{"COLUMNS"} =~ /^\d+$/
Truth table0%0/3
A and B
A= exists $ENV{"COLUMNS"}B= $ENV{"COLUMNS"} =~ /^\d+$/
ABresult
0X0
100
111
532 }
533  
534 33 ▶ $width = 80 unless ( $width && $width >= 80 );
Branch: 1 branch
BranchTrueFalseTotal
unless $width and $width >= 80 33 0 33
Condition33%1/3
$width and $width >= 80
!ll&&!rl&&r
3300
MC/DC0%0/2
$width and $width >= 80
$width $width >= 80
Truth table33%1/3
A and B
A= $widthB= $width >= 80
ABresult
0X0
100
111
535 33 return $width;
536 }
537  
538 163 ▶sub _draw_table {
Subroutine _draw_table: called CC=3 SCAR=11.0
539 163 my ( $self, $captions, $rows, $preamble ) = @_;
540  
541 163 ▶ return unless @{$rows};
Branch: 1 branch
BranchTrueFalseTotal
unless @{$rows;} 4 159 163
542  
543 159 ▶ $self->_debug($preamble) if $preamble;
Branch: 1 branch
BranchTrueFalseTotal
if $preamble 5 154 159
544  
545 159 my $table = Term::Table->new(
546 header => $captions,
547 rows => $rows,
548 max_width => $self->term_width,
549 allow_overflow => 1,
550 pad => 0,
551 sanitize => 0,
552 );
553  
554 159 $self->_debug( join "\n", $table->render );
555 }
556  
557 14 1;
558  
559 =pod
560  
561 =encoding UTF-8
562  
563 =head1 NAME
564  
565 LWP::ConsoleLogger - LWP tracing and debugging
566  
567 =head1 VERSION
568  
569 version 1.000003
570  
571 =head1 SYNOPSIS
572  
573 The simplest way to get started is by adding L<LWP::ConsoleLogger::Everywhere>
574 to your code and then just watching your output.
575  
576 use LWP::ConsoleLogger::Everywhere ();
577  
578 If you need more control, look at L<LWP::ConsoleLogger::Easy>.
579  
580 use LWP::ConsoleLogger::Easy qw( debug_ua );
581 use WWW::Mechanize;
582  
583 my $mech = WWW::Mechanize->new; # or LWP::UserAgent->new() etc
584 my $console_logger = debug_ua( $mech );
585 $mech->get( 'https://metacpan.org' );
586  
587 # now watch the console for debugging output
588 # turn off header dumps
589 $console_logger->dump_headers( 0 );
590  
591 $mech->get( $some_other_url );
592  
593 To get down to the lowest level, use LWP::ConsoleLogger directly.
594  
595 my $ua = LWP::UserAgent->new( cookie_jar => {} );
596 my $console_logger = LWP::ConsoleLogger->new(
597 dump_content => 1,
598 dump_text => 1,
599 content_pre_filter => sub {
600 my $content = shift;
601 my $content_type = shift;
602  
603 # mangle content here
604 # ...
605  
606 return $content;
607 },
608 );
609  
610 $ua->default_header(
611 'Accept-Encoding' => scalar HTTP::Message::decodable() );
612  
613 $ua->add_handler( 'response_done',
614 sub { $console_logger->response_callback( @_ ) } );
615 $ua->add_handler( 'request_send',
616 sub { $console_logger->request_callback( @_ ) } );
617  
618 # now watch debugging output to your screen
619 $ua->get( 'http://nytimes.com/' );
620  
621 Sample output might look like this.
622  
623 GET http://www.nytimes.com/2014/04/24/technology/fcc-new-net-neutrality-rules.html
624  
625 GET params:
626 +-----+-------+
627 | Key | Value |
628 +-----+-------+
629 | _r | 1 |
630 | hp | |
631 +-----+-------+
632  
633 +-----------------+--------------------------------+
634 | Request Header | Value |
635 +-----------------+--------------------------------+
636 | Accept-Encoding | gzip |
637 | Cookie2 | $Version="1" |
638 | Referer | http://www.nytimes.com?foo=bar |
639 | User-Agent | WWW-Mechanize/1.73 |
640 +-----------------+--------------------------------+
641  
642 ==> 200 OK
643  
644 Title: The New York Times - Breaking News, World News & Multimedia
645  
646 +--------------------------+-------------------------------+
647 | Response Header | Value |
648 +--------------------------+-------------------------------+
649 | Accept-Ranges | bytes |
650 | Age | 176 |
651 | Cache-Control | no-cache |
652 | Channels | NytNow |
653 | Client-Date | Fri, 30 May 2014 22:37:42 GMT |
654 | Client-Peer | 170.149.172.130:80 |
655 | Client-Response-Num | 1 |
656 | Client-Transfer-Encoding | chunked |
657 | Connection | keep-alive |
658 | Content-Encoding | gzip |
659 | Content-Type | text/html; charset=utf-8 |
660 | Date | Fri, 30 May 2014 22:37:41 GMT |
661 | NtCoent-Length | 65951 |
662 | Server | Apache |
663 | Via | 1.1 varnish |
664 | X-Cache | HIT |
665 | X-Varnish | 1142859770 1142854917 |
666 +--------------------------+-------------------------------+
667  
668 +----------------------------------------------------------+
669 | Text |
670 +----------------------------------------------------------+
671 | F.C.C., in a Shift, Backs Fast Lanes for Web Traffic... |
672 +----------------------------------------------------------+
673  
674 =head1 DESCRIPTION
675  
676 It can be hard (or at least tedious) to debug mechanize scripts. LWP::Debug is
677 deprecated. It suggests you write your own debugging handlers, set up a proxy
678 or install Wireshark. Those are all workable solutions, but this module exists
679 to save you some of that work. The guts of this module are stolen from
680 L<Plack::Middleware::DebugLogging>, which in turn stole most of its internals
681 from L<Catalyst>. If you're new to LWP::ConsoleLogger, I suggest getting
682 started with the L<LWP::ConsoleLogger::Easy> wrapper. This will get you up and
683 running in minutes. If you need to tweak the settings that
684 L<LWP::ConsoleLogger::Easy> chooses for you (or if you just want to be fancy),
685 please read on.
686  
687 Since this is a debugging library, I've left as much mutable state as possible,
688 so that you can easily toggle output on and off and otherwise adjust how you
689 deal with the output.
690  
691 =head1 CONSTRUCTOR
692  
693 =head2 new()
694  
695 The following arguments can be passed to new(), although none are required.
696 They can also be called as methods on an instantiated object. I'll list them
697 here and discuss them in detail below.
698  
699 =over 4
700  
701 =item * C<< dump_content => 0|1 >>
702  
703 =item * C<< dump_cookies => 0|1 >>
704  
705 =item * C<< dump_headers => 0|1 >>
706  
707 =item * C<< dump_params => 0|1 >>
708  
709 =item * C<< dump_status => 0|1 >>
710  
711 =item * C<< dump_text => 0|1 >>
712  
713 =item * C<< dump_title => 0|1 >>
714  
715 =item * C<< dump_text => 0|1 >>
716  
717 =item * C<< dump_uri => 0|1 >>
718  
719 =item * C<< content_pre_filter => sub { ... } >>
720  
721 =item * C<< headers_to_redact => ['Authentication', 'Foo'] >>
722  
723 =item * C<< params_to_redact => ['token', 'password'] >>
724  
725 =item * C<< text_pre_filter => sub { ... } >>
726  
727 =item * C<< html_restrict => HTML::Restrict->new( ... ) >>
728  
729 =item * C<< logger => Log::Dispatch->new( ... ) >>
730  
731 =item * C<< pretty => 0|1 >>
732  
733 =item * C<< term_width => $integer >>
734  
735 =back
736  
737 =head1 SUBROUTINES/METHODS
738  
739 =head2 dump_content( 0|1 )
740  
741 Boolean value. If true, the actual content of your response (HTML, JSON, etc)
742 will be dumped to your screen. Defaults to false.
743  
744 =head2 dump_cookies( 0|1 )
745  
746 Boolean value. If true, the content of your cookies will be dumped to your
747 screen. Defaults to false.
748  
749 =head2 dump_headers( 0|1 )
750  
751 Boolean value. If true, both request and response headers will be dumped to
752 your screen. Defaults to true.
753  
754 Headers are dumped in alphabetical order.
755  
756 =head2 dump_params( 0|1 )
757  
758 Boolean value. If true, both GET and POST params will be dumped to your screen.
759 Defaults to true.
760  
761 Params are dumped in alphabetical order.
762  
763 =head2 dump_status( 0|1 )
764  
765 Boolean value. If true, dumps the HTTP response code for each page being
766 visited. Defaults to true.
767  
768 =head2 dump_text( 0|1 )
769  
770 Boolean value. If true, dumps the text of your page after both the
771 content_pre_filter and text_pre_filters have been applied. Defaults to true.
772  
773 =head2 dump_title( 0|1 )
774  
775 Boolean value. If true, dumps the titles of HTML pages if your UserAgent has
776 a C<title> method and if it returns something useful. Defaults to true.
777  
778 =head2 dump_uri( 0|1 )
779  
780 Boolean value. If true, dumps the URI of each page being visited. Defaults to
781 true.
782  
783 =head2 pretty ( 0|1 )
784  
785 Boolean value. If disabled, request headers, response headers, content and text
786 sections will be dumped without using tables. Handy for copy/pasting JSON etc
787 for faking responses later. Defaults to true.
788  
789 =head2 content_pre_filter( sub { ... } )
790  
791 Subroutine reference. This allows you to manipulate content before it is
792 dumped. A common use case might be stripping headers and footers away from
793 HTML content to make it easier to detect changes in the body of the page.
794  
795 $easy_logger->content_pre_filter(
796 sub {
797 my $content = shift;
798 my $content_type = shift; # the value of the Content-Type header
799 if ( $content_type =~ m{html}i
800 && $content =~ m{<!--\scontent\s-->(.*)<!--\sfooter}msx ) {
801 return $1;
802 }
803 return $content;
804 }
805 );
806  
807 Try to make sure that your content mangling doesn't return broken HTML as that
808 may not play well with L<HTML::Restrict>.
809  
810 =head2 request_callback
811  
812 Use this handler to set up console logging on your requests.
813  
814 my $ua = LWP::UserAgent->new;
815 $ua->add_handler(
816 'request_send',
817 sub { $console_logger->request_callback(@_) }
818 );
819  
820 This is done for you by default if you set up your logging via
821 L<LWP::ConsoleLogger::Easy>.
822  
823 =head2 response_callback
824  
825 Use this handler to set up console logging on your responses.
826  
827 my $ua = LWP::UserAgent->new;
828 $ua->add_handler(
829 'response_done',
830 sub { $console_logger->response_callback(@_) }
831 );
832  
833 This is done for you by default if you set up your logging via
834 L<LWP::ConsoleLogger::Easy>.
835  
836 =head2 text_pre_filter( sub { ... } )
837  
838 Subroutine reference. This allows you to manipulate text before it is dumped.
839 A common use case might be stripping away duplicate whitespace and/or newlines
840 in order to improve formatting. Keep in mind that the C<content_pre_filter>
841 will have been applied to the content which is passed to the text_pre_filter.
842 The idea is that you can strip away an HTML you don't care about in the
843 content_pre_filter phase and then process the remainder of the content in the
844 text_pre_filter.
845  
846 $easy_logger->text_pre_filter(
847 sub {
848 my $content = shift;
849 my $content_type = shift; # the value of the Content-Type header
850 my $base_url = shift;
851  
852 # do something with the content
853 # ...
854  
855 return ( $content, $new_content_type );
856 }
857 );
858  
859 If your C<text_pre_filter()> converts from HTML to plain text, be sure to
860 return the new content type (text/plain) when you exit the sub. If you do not
861 do this, HTML formatting will then be applied to your plain text as is
862 explained below.
863  
864 If this is HTML content, L<HTML::Restrict> will be applied after the
865 text_pre_filter has been run. LWP::ConsoleLogger will then strip away some
866 whitespace and newlines from processed HTML in its own opinionated way, in
867 order to present you with more readable text.
868  
869 =head2 html_restrict( HTML::Restrict->new( ... ) )
870  
871 If the content_type indicates HTML then HTML::Restrict will be used to strip
872 tags from your content in the text rendering process. You may pass your own
873 HTML::Restrict object, if you like. This would be helpful in situations where
874 you still do want to have some tags in your text.
875  
876 =head2 logger( Log::Dispatch->new( ... ) )
877  
878 By default all data will be dumped to your console (as the name of this module
879 implies) using Log::Dispatch. However, you may use your own Log::Dispatch
880 module in order to facilitate logging to files or any other output which
881 Log::Dispatch supports.
882  
883 =head2 term_width( $integer )
884  
885 By default this module will try to find the maximum width of your terminal and
886 use all available space when displaying tabular data. You may use this
887 parameter to constrain the tables to an arbitrary width.
888  
889 =head1 CAVEATS
890  
891 I've written this to suit my needs and there are a lot of things I haven't
892 considered. For example, I'm mostly assuming that the content will be text,
893 HTML, JSON or XML.
894  
895 The test suite is not very robust either. If you'd like to contribute to this
896 module and you can't find an appropriate test, do add something to the example
897 folder (either a new script or alter an existing one), so that I can see what
898 your patch does.
899  
900 =head1 AUTHOR
901  
902 Olaf Alders <olaf@wundercounter.com>
903  
904 =head1 COPYRIGHT AND LICENSE
905  
906 This software is Copyright (c) 2014 by MaxMind, Inc.
907  
908 This is free software, licensed under:
909  
910 The Artistic License 2.0 (GPL Compatible)
911  
912 =cut
913  
914 __END__
« ConsoleLogger/Easy.pm ↑ Summary ConsoleLogger/Everywhere.pm »