1package Minilla::Logger;
2use strict;
3use warnings;
4use utf8;
5use parent qw(Exporter);
6
7use Term::ANSIColor qw(colored);
8require Win32::Console::ANSI if $^O eq 'MSWin32';
9
10use Minilla::Errors;
11
12our @EXPORT = qw(debugf infof warnf errorf);
13
14our $COLOR;
15
16use constant { DEBUG => 1, INFO => 2, WARN => 3, ERROR => 4 };
17
18our $Colors = {
19    DEBUG,   => 'green',
20    WARN,    => 'yellow',
21    INFO,    => 'cyan',
22    ERROR,   => 'red',
23};
24
25sub _printf {
26    my $type = pop;
27    my($temp, @args) = @_;
28    _print(sprintf($temp, map { defined($_) ? $_ : '-' } @args), $type);
29}
30
31sub _print {
32    my($msg, $type) = @_;
33    return if $type == DEBUG && !Minilla->debug;
34    $msg = colored $msg, $Colors->{$type} if defined $type && $COLOR;
35    my $fh = $type && $type >= WARN ? *STDERR : *STDOUT;
36    print {$fh} $msg;
37}
38
39sub infof {
40    _printf(@_, INFO);
41}
42
43sub warnf {
44    _printf(@_, WARN);
45}
46
47sub debugf {
48    _printf(@_, DEBUG);
49}
50
51sub errorf {
52    my(@msg) = @_;
53    _printf(@msg, ERROR);
54
55    my $fmt = shift @msg;
56    Minilla::Error::CommandExit->throw(sprintf($fmt, @msg));
57}
58
591;
60
61