]> git.ipfire.org Git - people/stevee/guardian.git/blobdiff - modules/Logger.pm
Add LogFacility for logging to a single file.
[people/stevee/guardian.git] / modules / Logger.pm
index 6a70bc37fba82acdce837dc82bd9cc3ae31297b4..2214e477e10d2cdd0c29b40337537d081debf000 100644 (file)
@@ -19,12 +19,13 @@ my %loglevels = (
 # This hash contains the supported log facilities and their corresponding subroutines.
 my %logfacilities = (
        "console" => \&LogFacilityConsole,
+       "file" => \&LogFacilityFile,
        "syslog" => \&LogFacilitySyslog,
 );
 
 
 #
-## The "New" (Logger) function.
+## The "Init" (Logger) function.
 #
 ## This function is responsible to initialize the Logger as a class based object.
 ## It has to be called once before logging can be done.
@@ -32,7 +33,7 @@ my %logfacilities = (
 ## The following arguments must be passed, when initializing a new Logger:
 ## "LogLevel" and "LogFacility" with valid values from above.
 #
-sub New (%) {
+sub Init (%) {
        my ( $class, %args ) = @_;
        my $self = \%args;
 
@@ -81,7 +82,7 @@ sub Log ($$) {
                my $use_facility = $self->{LogFacility};
 
                # Transmit log message to the correct log facility.
-               $logfacilities{$use_facility}->($level, $message);
+               $logfacilities{$use_facility}->($self, $level, $message);
        }
 }
 
@@ -91,7 +92,7 @@ sub Log ($$) {
 ## This really simple function just returns the hash which
 ## contains all supported log levels.
 #
-sub LogLevels () {
+sub GetLogLevels () {
        # Nothing to do, just return the loglevels hash.
        return %loglevels;
 }
@@ -103,6 +104,7 @@ sub LogLevels () {
 ## message to STDOUT.
 #
 sub LogFacilityConsole ($$) {
+       my $self = shift;
        my ($type, $message) = @_;
 
        # Print message on STDOUT.
@@ -115,6 +117,7 @@ sub LogFacilityConsole ($$) {
 ## This log facility sends a given log message to the system log service (syslog).
 #
 sub LogFacilitySyslog ($$) {
+       my $self = shift;
        my ($type, $message) = @_;
 
        # The syslog function works best with an array based input,
@@ -131,4 +134,23 @@ sub LogFacilitySyslog ($$) {
        closelog();
 }
 
+#
+## LogFacilityFile function.
+#
+## This log facility will write any given log messages to a specified log file.
+#
+sub LogFacilityFile ($$) {
+       my $self = shift;
+       my ($type, $message) = @_;
+
+       # Open the logfile for writing.
+       open(LOGFILE, '>>', $self->{LogFile}) or die "Could not write to $self->{LogFile}: $!\n";
+
+       # Write log message to file.
+       print LOGFILE "\[$type\] $message\n";
+
+       # Close filehandle.
+       close(FILE);
+}
+
 1;