ConsoleLogger.pm

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