summaryrefslogtreecommitdiff
path: root/lib/PerlDaemon/Logger.pm
blob: 7cdafc6b19fce1cc7819c32c28c02d382fa49af4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
package PerlDaemon::Logger;

use strict;
use warnings;
use threads;
use threads::shared;

use Shell qw(mv);
use POSIX qw(strftime);

$| = 1;

our $SELF;

$SIG{'USR2'} = sub {
        $SELF->flushlogs();
};

sub new ($$) {
	my ($class, $conf) = @_;

        die "Instance already exists" if defined $SELF;
	$SELF = bless { conf => $conf }, $class;

        $SELF->{queue} = [];
        share $SELF->{queue};

        return $SELF;
}

sub logmsg ($$) {
	my ($self, $msg) = @_;
	my $conf = $self->{conf};
        my $logline = localtime()." (PID $$): $msg\n";


        { lock $self->{queue};
                push @{$self->{queue}}, $logline;
        }

        $self->flushlogs();

        return undef;
}

sub flushlogs ($$) {
	my ($self, $msg) = @_;
	my $conf = $self->{conf};
	my $logfile = $conf->{'daemon.logfile'};

        { lock $self->{queue};
	        open my $fh, ">>$logfile" or die "Can't write logfile $logfile: $!\n";
                for my $logline (@{$self->{queue}}) {
                        print $fh $logline;
                        print $logline if $conf->{'daemon.daemonize'} ne 'yes';
                }
	        close $fh;
                @{$self->{queue}} = ();
        }

        return undef;
}

sub err ($$) {
	my ($self, $msg) = @_;
	$self->logmsg($msg);
	die "$msg\n";
}

sub warn ($$) {
	my ($self, $msg) = @_;
	$self->logmsg("WARNING: $msg");

        return undef;
}

sub rotatelog ($) {
	my $self = shift;
	my $conf = $self->{conf};
	my $logfile = $conf->{'daemon.logfile'};

	$self->logmsg('Rotating logfile');

	my $timestr = strftime "%Y%m%d-%H%M%S", localtime();
	mv($logfile, "$logfile.$timestr");	

        return undef;
}

1;