EnsEMBL/Utils/Logger.pm untested

filter: Statementstmt 0.0% 0 / 228 Branchbran 0.0% 0 / 66 Conditioncond 0.0% 0 / 35 Subroutinesub 0.0% 0 / 41 Podpod 0.0% 0 / 32 totaltotal 0.0% 0 / 402 CC 34 SCAR 24.3
CC
34
Cov
0%
log_filehandle
42.0
log_progress
30.0
log_progressbar
20.0
CRAP 11.4
1 =head1 LICENSE
2  
3 See the NOTICE file distributed with this work for additional information
4 regarding copyright ownership.
5  
6 Licensed under the Apache License, Version 2.0 (the "License");
7 you may not use this file except in compliance with the License.
8 You may obtain a copy of the License at
9  
10 http://www.apache.org/licenses/LICENSE-2.0
11  
12 Unless required by applicable law or agreed to in writing, software
13 distributed under the License is distributed on an "AS IS" BASIS,
14 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 See the License for the specific language governing permissions and
16 limitations under the License.
17  
18 =cut
19  
20  
21 =head1 CONTACT
22  
23 Please email comments or questions to the public Ensembl
24 developers list at <http://lists.ensembl.org/mailman/listinfo/dev>.
25  
26 Questions may also be sent to the Ensembl help desk at
27 <http://www.ensembl.org/Help/Contact>.
28  
29 =cut
30  
31 =head1 NAME
32  
33 Bio::EnsEMBL::Utils::ConversionSupport - Utility module for Vega release and
34 schema conversion scripts
35  
36 =head1 SYNOPSIS
37  
38 my $serverroot = '/path/to/ensembl';
39 my $suport = new Bio::EnsEMBL::Utils::ConversionSupport($serverroot);
40  
41 # parse common options
42 $support->parse_common_options;
43  
44 # parse extra options for your script
45 $support->parse_extra_options( 'string_opt=s', 'numeric_opt=n' );
46  
47 # ask user if he wants to run script with these parameters
48 $support->confirm_params;
49  
50 # see individual method documentation for more stuff
51  
52 =head1 DESCRIPTION
53  
54 This module is a collection of common methods and provides helper
55 functions for the Vega release and schema conversion scripts. Amongst
56 others, it reads options from a config file, parses commandline options
57 and does logging.
58  
59 =head1 METHODS
60  
61 =cut
62  
63 package Bio::EnsEMBL::Utils::Logger;
64 $Bio::EnsEMBL::Utils::Logger::VERSION = '114.0.0_50'; # TRIAL
65 $Bio::EnsEMBL::Utils::Logger::VERSION = '114.0.050';
66 use strict;
67 use warnings;
68 no warnings 'uninitialized';
69  
70 use FindBin qw($Bin $Script);
71 use POSIX qw(strftime);
72 use Bio::EnsEMBL::Utils::Argument qw(rearrange);
73 use Bio::EnsEMBL::Utils::Exception qw(throw);
74 use Bio::EnsEMBL::Utils::ScriptUtils qw(parse_bytes);
75 use Carp;
76  
77 my %level_defs = (
78 'error' => 1,
79 'warn' => 2,
80 'warning' => 2,
81 'info' => 3,
82 'debug' => 4,
83 'verbose' => 4,
84 );
85  
86 my @reverse_level_defs = (undef, qw(error warning info debug));
87  
88 =head2 new
89  
90 Arg[1] : String $serverroot - root directory of your ensembl sandbox
91 Example : my $support = new Bio::EnsEMBL::Utils::ConversionSupport(
92 '/path/to/ensembl');
93 Description : constructor
94 Return type : Bio::EnsEMBL::Utils::ConversionSupport object
95 Exceptions : thrown on invalid loglevel
96 Caller : general
97  
98 =cut
99  
100 sub new {
101 my $caller = shift;
102 my $class = ref($caller) || $caller;
103  
104 my ($logfile, $logauto, $logautobase, $logautoid, $logpath, $logappend,
105 $loglevel, $is_component) = rearrange(
106 ['LOGFILE', 'LOGAUTO', 'LOGAUTOBASE', 'LOGAUTOID', 'LOGPATH', 'LOGAPPEND',
107 'LOGLEVEL', 'IS_COMPONENT'], @_);
108
109 my $self = { '_warnings' => 0, };
110 bless ($self, $class);
111  
112 # initialise
113 $self->logfile($logfile);
114 $self->logpath($logpath);
115 $self->logappend($logappend);
116 $self->is_component($is_component);
117  
118 # automatic logfile creation
119 $self->logauto($logauto);
120 $logautoid ||= strftime("%Y%m%d-%H%M%S", localtime);
121 $self->log_auto_id($logautoid);
122 $self->create_auto_logfile($logautobase);
123  
124 $loglevel ||= 'info';
125 if ($loglevel =~ /^\d+$/ and $loglevel > 0 and $loglevel < 5) {
126 $self->{'loglevel'} = $loglevel;
127 } elsif ($level_defs{lc($loglevel)}) {
128 $self->{'loglevel'} = $level_defs{lc($loglevel)};
129 } else {
130 throw('Unknown loglevel: $loglevel.');
131 }
132
133 return $self;
134 }
135  
136  
137 =head2 log_generic
138  
139 Arg[1] : String $txt - the text to log
140 Arg[2] : Int $indent - indentation level for log message
141 Example : my $log = $support->log_filehandle;
142 $support->log('Log foo.\n', 1);
143 Description : Logs a message to the filehandle initialised by calling
144 $self->log_filehandle(). You can supply an indentation level
145 to get nice hierarchical log messages.
146 Return type : true on success
147 Exceptions : thrown when no filehandle can be obtained
148 Caller : general
149  
150 =cut
151  
152 sub log_generic {
153 my ($self, $txt, $indent, $stamped) = @_;
154  
155 $indent ||= 0;
156 my $fh = $self->log_filehandle;
157  
158 # append timestamp and memory usage to log text if requested
159 if ($stamped) {
160 $txt =~ s/^(\n*)(.*)(\n*)$/$2/;
161 $txt = sprintf("%-60s%20s", $txt, $self->time_and_mem);
162 $txt = $1.$txt.$3;
163 }
164
165 # strip off leading linebreaks so that indenting doesn't break
166 $txt =~ s/^(\n*)//;
167
168 # indent
169 $txt = $1." "x$indent . $txt;
170
171 print $fh "$txt";
172
173 return(1);
174 }
175  
176  
177 =head2 error
178  
179 Arg[1] : String $txt - the error text to log
180 Arg[2] : Int $indent - indentation level for log message
181 Example : my $log = $support->log_filehandle;
182 $support->log_error('Log foo.\n', 1);
183 Description : Logs a message via $self->log and exits the script.
184 Return type : none
185 Exceptions : none
186 Caller : general
187  
188 =cut
189  
190 sub error {
191 my ($self, $txt, $indent, $stamped) = @_;
192  
193 return(0) unless ($self->{'loglevel'} >= 1);
194
195 $txt = "ERROR: ".$txt;
196 $self->log_generic($txt, $indent, $stamped);
197
198 $self->log_generic("\nExiting prematurely.\n\n");
199 $self->log_generic("Runtime: ".$self->runtime." ".$self->date_and_mem."\n\n");
200
201 confess($txt);
202 }
203  
204  
205 =head2 warning
206  
207 Arg[1] : String $txt - the warning text to log
208 Arg[2] : Int $indent - indentation level for log message
209 Example : my $log = $support->log_filehandle;
210 $support->log_warning('Log foo.\n', 1);
211 Description : Logs a message via $self->log and increases the warning counter.
212 Return type : true on success
213 Exceptions : none
214 Caller : general
215  
216 =cut
217  
218 sub warning {
219 my ($self, $txt, $indent, $stamped) = @_;
220
221 return(0) unless ($self->{'loglevel'} >= 2);
222
223 $txt = "WARNING: " . $txt;
224 $self->log_generic($txt, $indent, $stamped);
225
226 $self->{'_warnings'}++;
227
228 return(1);
229 }
230  
231  
232 sub info {
233 my ($self, $txt, $indent, $stamped) = @_;
234  
235 return(0) unless ($self->{'loglevel'} >= 3);
236  
237 $self->log_generic($txt, $indent, $stamped);
238 return(1);
239 }
240  
241  
242 =head2 debug
243  
244 Arg[1] : String $txt - the warning text to log
245 Arg[2] : Int $indent - indentation level for log message
246 Example : my $log = $support->log_filehandle;
247 $support->log_verbose('Log this verbose message.\n', 1);
248 Description : Logs a message via $self->log if --verbose option was used
249 Return type : TRUE on success, FALSE if not verbose
250 Exceptions : none
251 Caller : general
252  
253 =cut
254  
255 sub debug {
256 my ($self, $txt, $indent, $stamped) = @_;
257  
258 return(0) unless ($self->{'loglevel'} >= 4);
259  
260 $self->log_generic($txt, $indent, $stamped);
261 return(1);
262 }
263  
264  
265 sub log_progress {
266 my $self = shift;
267 my $name = shift;
268 my $curr = shift;
269 my $indent = shift;
270
271 throw("You must provide a name and the current value for your progress bar")
272 unless ($name and $curr);
273  
274 # return if we haven't reached the next increment
275 return if ($curr < int($self->{'_progress'}->{$name}->{'next'}));
276  
277 my $index = $self->{'_progress'}->{$name}->{'index'};
278 my $num_bins = $self->{'_progress'}->{$name}->{'numbins'};
279 my $percent = $index/$num_bins*100;
280  
281 my $log_str;
282 $log_str .= ' 'x$indent if ($index == 0);
283 $log_str .= "\b"x4;
284 $log_str .= sprintf("%3s%%", $percent);
285 $log_str .= "\n" if ($curr == $self->{'_progress'}->{$name}->{'max_val'});
286  
287 $self->info($log_str);
288  
289 # increment counters
290 $self->{'_progress'}->{$name}->{'index'}++;
291 $self->{'_progress'}->{$name}->{'next'} += $self->{'_progress'}->{$name}->{'binsize'};
292 }
293  
294  
295 sub log_progressbar {
296 my $self = shift;
297 my $name = shift;
298 my $curr = shift;
299 my $indent = shift;
300
301 throw("You must provide a name and the current value for your progress bar")
302 unless ($name and $curr);
303  
304 # return if we haven't reached the next increment
305 return if ($curr < int($self->{'_progress'}->{$name}->{'next'}));
306  
307 my $index = $self->{'_progress'}->{$name}->{'index'};
308 my $num_bins = $self->{'_progress'}->{$name}->{'numbins'};
309 my $percent = $index/$num_bins*100;
310  
311 my $log_str = "\r".(' 'x$indent)."[".('='x$index).(' 'x($num_bins-$index))."] ${percent}\%";
312 $log_str .= "\n" if ($curr == $self->{'_progress'}->{$name}->{'max_val'});
313  
314 $self->info($log_str);
315  
316 # increment counters
317 $self->{'_progress'}->{$name}->{'index'}++;
318 $self->{'_progress'}->{$name}->{'next'} += $self->{'_progress'}->{$name}->{'binsize'};
319 }
320  
321  
322 sub init_progress {
323 my $self = shift;
324 my $max = shift;
325 my $num_bins = shift || 50;
326  
327 throw("You must provide the maximum value for your progress bar")
328 unless (defined($max));
329  
330 # auto-generate a unique name for your progressbar
331 my $name = time . '_' . int(rand(1000));
332  
333 # calculate bin size; we will use 50 bins (2% increments)
334 my $binsize = $max/$num_bins;
335  
336 $self->{'_progress'}->{$name}->{'max_val'} = $max;
337 $self->{'_progress'}->{$name}->{'binsize'} = $binsize;
338 $self->{'_progress'}->{$name}->{'numbins'} = $num_bins;
339 $self->{'_progress'}->{$name}->{'next'} = 0;
340 $self->{'_progress'}->{$name}->{'index'} = 0;
341  
342 return $name;
343 }
344  
345  
346 =head2 log_filehandle
347  
348 Arg[1] : (optional) String $mode - file access mode
349 Example : my $log = $support->log_filehandle;
350 # print to the filehandle
351 print $log 'Lets start logging...\n';
352 # log via the wrapper $self->log()
353 $support->log('Another log message.\n');
354 Description : Returns a filehandle for logging (STDERR by default, logfile if
355 set from config or commandline). You can use the filehandle
356 directly to print to, or use the smart wrapper $self->log().
357 Logging mode (truncate or append) can be set by passing the
358 mode as an argument to log_filehandle(), or with the
359 --logappend commandline option (default: truncate)
360 Return type : Filehandle - the filehandle to log to
361 Exceptions : thrown if logfile can't be opened
362 Caller : general
363  
364 =cut
365  
366 sub log_filehandle {
367 my ($self, $mode) = @_;
368
369 unless ($self->{'_log_filehandle'}) {
370 $mode ||= '>';
371 $mode = '>>' if ($self->logappend);
372
373 my $fh = \*STDERR;
374
375 if (my $logfile = $self->logfile) {
376 if (my $logpath = $self->logpath) {
377 unless (-e $logpath) {
378 system("mkdir -p $logpath") == 0 or
379 throw("Can't create log dir $logpath: $!\n");
380 }
381
382 $logfile = "$logpath/".$self->logfile;
383 }
384
385 open($fh, "$mode", $logfile) or
386 throw("Unable to open $logfile for writing: $!");
387 }
388  
389 $self->{'_log_filehandle'} = $fh;
390 }
391  
392 return $self->{'_log_filehandle'};
393 }
394  
395  
396 =head2 extract_log_identifier
397  
398 Arg[1] :
399 Example :
400 Description :
401 Return type :
402 Exceptions :
403 Caller :
404 Status :
405  
406 =cut
407  
408 sub extract_log_identifier {
409 my $self = shift;
410  
411 if (my $logfile = $self->logfile) {
412 $logfile =~ /.+\.([^\.]+)\.log/;
413 return $1;
414 } else {
415 return undef;
416 }
417 }
418  
419  
420 =head2 init_log
421  
422 Example : $support->init_log;
423 Description : Opens a filehandle to the logfile and prints some header
424 information to this file. This includes script name, date, user
425 running the script and parameters the script will be running
426 with.
427 Return type : Filehandle - the log filehandle
428 Exceptions : none
429 Caller : general
430  
431 =cut
432  
433 sub init_log {
434 my $self = shift;
435 my $params = shift;
436  
437 # get a log filehandle
438 my $log = $self->log_filehandle;
439  
440 # remember start time
441 $self->{'_start_time'} = time;
442  
443 # don't log parameters if this script is run by another one
444 if ($self->logauto or ! $self->is_component) {
445 # print script name, date, user who is running it
446 my $hostname = `hostname`;
447 chomp $hostname;
448 my $script = "$hostname:$Bin/$Script";
449 my $user = `whoami`;
450 chomp $user;
451 $self->info("Script: $script\nDate: ".$self->date."\nUser: $user\n");
452  
453 # print parameters the script is running with
454 if ($params) {
455 $self->info("Parameters:\n\n");
456 $self->info($params);
457 }
458 }
459  
460 return $log;
461 }
462  
463  
464 =head2 finish_log
465  
466 Example : $support->finish_log;
467 Description : Writes footer information to a logfile. This includes the
468 number of logged warnings, timestamp and memory footprint.
469 Return type : TRUE on success
470 Exceptions : none
471 Caller : general
472  
473 =cut
474  
475 sub finish_log {
476 my $self = shift;
477
478 $self->info("\nAll done for $Script.\n");
479 $self->info($self->warning_count." warnings. ");
480 $self->info("Runtime: ".$self->runtime." ".$self->date_and_mem."\n\n");
481
482 return(1);
483 }
484  
485  
486 sub runtime {
487 my $self = shift;
488  
489 my $runtime = "n/a";
490  
491 if ($self->{'_start_time'}) {
492 my $diff = time - $self->{'_start_time'};
493 my $sec = $diff % 60;
494 $diff = ($diff - $sec) / 60;
495 my $min = $diff % 60;
496 my $hours = ($diff - $min) / 60;
497
498 $runtime = "${hours}h ${min}min ${sec}sec";
499 }
500  
501 return $runtime;
502 }
503  
504  
505 =head2 date_and_mem
506  
507 Example : print LOG "Time, memory usage: ".$support->date_and_mem."\n";
508 Description : Prints a timestamp and the memory usage of your script.
509 Return type : String - timestamp and memory usage
510 Exceptions : none
511 Caller : general
512  
513 =cut
514  
515 sub date_and_mem {
516 my $date = strftime "%Y-%m-%d %T", localtime;
517 my $mem = `ps -p $$ -o vsz |tail -1`;
518 chomp $mem;
519 $mem = parse_bytes($mem*1000);
520 return "[$date, mem $mem]";
521 }
522  
523  
524 sub time_and_mem {
525 my $date = strftime "%T", localtime;
526 my $mem = `ps -p $$ -o vsz |tail -1`;
527 chomp $mem;
528 $mem = parse_bytes($mem*1000);
529 $mem =~ s/ //;
530 return "[$date|$mem]";
531 }
532  
533  
534 =head2 date
535  
536 Example : print "Date: " . $support->date . "\n";
537 Description : Prints a nicely formatted timestamp (YYYY-DD-MM hh:mm:ss)
538 Return type : String - the timestamp
539 Exceptions : none
540 Caller : general
541  
542 =cut
543  
544 sub date {
545 return strftime "%Y-%m-%d %T", localtime;
546 }
547  
548  
549 =head2 mem
550  
551 Example : print "Memory usage: " . $support->mem . "\n";
552 Description : Prints the memory used by your script. Not sure about platform
553 dependence of this call ...
554 Return type : String - memory usage
555 Exceptions : none
556 Caller : general
557  
558 =cut
559  
560 sub mem {
561 my $mem = `ps -p $$ -o vsz |tail -1`;
562 chomp $mem;
563 return $mem;
564 }
565  
566  
567 =head2 warning_count
568  
569 Example : print LOG "There were ".$support->warnings." warnings.\n";
570 Description : Returns the number of warnings encountered while running the
571 script (the warning counter is increased by $self->log_warning).
572 Return type : Int - number of warnings
573 Exceptions : none
574 Caller : general
575  
576 =cut
577  
578 sub warning_count {
579 my $self = shift;
580 return $self->{'_warnings'};
581 }
582  
583  
584 =head2 logfile
585  
586 Arg[1] :
587 Example :
588 Description : Getter and setter for the logfile
589 Return type :
590 Exceptions :
591 Caller :
592 Status :
593  
594 =cut
595  
596 sub logfile {
597 my $self = shift;
598 $self->{'_logfile'} = shift if (@_);
599 return $self->{'_logfile'};
600 }
601  
602  
603 =head2 log_auto_id
604  
605 Arg[1] :
606 Example :
607 Description :
608 Return type :
609 Exceptions :
610 Caller :
611 Status :
612  
613 =cut
614  
615 sub log_auto_id {
616 my $self = shift;
617 $self->{'_log_auto_id'} = shift if (@_);
618 return $self->{'_log_auto_id'};
619 }
620  
621  
622 sub logauto {
623 my $self = shift;
624 $self->{'_log_auto'} = shift if (@_);
625 return $self->{'_log_auto'};
626 }
627  
628  
629 =head2 create_auto_logfile
630  
631 Arg[1] :
632 Example :
633 Description :
634 Return type :
635 Exceptions :
636 Caller :
637 Status : At Risk
638 : under development
639  
640 =cut
641  
642 sub create_auto_logfile {
643 my $self = shift;
644 my $logautobase = shift;
645  
646 # do nothing if automatic logfile generation isn't set
647 return unless ($self->logauto);
648  
649 # an explicit logfile name overrides LOGAUTO
650 return if ($self->logfile);
651  
652 # argument check
653 unless ($logautobase) {
654 throw('Need a base logfile name for auto-generating logfile.');
655 }
656  
657 # create a logfile name
658 $self->logfile("${logautobase}_".$self->log_auto_id.".log");
659 }
660  
661  
662 =head2 logpath
663  
664 Arg[1] :
665 Example :
666 Description :
667 Return type :
668 Exceptions :
669 Caller :
670 Status :
671  
672 =cut
673  
674 sub logpath {
675 my $self = shift;
676 $self->{'_logpath'} = shift if (@_);
677 return $self->{'_logpath'};
678 }
679  
680  
681 =head2 logappend
682  
683 Arg[1] :
684 Example :
685 Description :
686 Return type :
687 Exceptions :
688 Caller :
689 Status :
690  
691 =cut
692  
693 sub logappend {
694 my $self = shift;
695 $self->{'_logappend'} = shift if (@_);
696 return $self->{'_logappend'};
697 }
698  
699  
700 =head2 is_component
701  
702 Arg[1] :
703 Example :
704 Description :
705 Return type :
706 Exceptions :
707 Caller :
708 Status :
709  
710 =cut
711  
712 sub is_component {
713 my $self = shift;
714 $self->{'_is_component'} = shift if (@_);
715 return $self->{'_is_component'};
716 }
717  
718  
719 sub loglevel {
720 my $self = shift;
721 return $reverse_level_defs[$self->{'loglevel'}];
722 }
723  
724  
725 #
726 # deprecated methods (left here for backwards compatibility
727 #
728 sub log_error {
729 return $_[0]->error(@_);
730 }
731  
732 sub log_warning {
733 return $_[0]->warning(@_);
734 }
735  
736 sub log {
737 return $_[0]->info(@_);
738 }
739  
740 sub log_verbose {
741 return $_[0]->debug(@_);
742 }
743  
744 sub log_stamped {
745 return $_[0]->log(@_, 1);
746 }
747  
748  
749  
750 1;
751