diff --git a/scripts/ZoneMinder/lib/ZoneMinder/Logger.pm b/scripts/ZoneMinder/lib/ZoneMinder/Logger.pm index f85eb5b192..6cdfadcb06 100644 --- a/scripts/ZoneMinder/lib/ZoneMinder/Logger.pm +++ b/scripts/ZoneMinder/lib/ZoneMinder/Logger.pm @@ -617,11 +617,13 @@ sub logPrint { # Turn this off because zDbConnect will do logging calls. my $oldlevel = $this->{databaseLevel}; $this->{databaseLevel} = NOLOG; - if ( ! ZoneMinder::Database::zmDbConnect() ) { + my $connected = ZoneMinder::Database::zmDbConnect(); + # Restore the level even when the connection is down so later calls retry. + $this->{databaseLevel} = $oldlevel; + if ( ! $connected ) { #print(STDERR "Can't log to database: "); return; } - $this->{databaseLevel} = $oldlevel; } my $sql = 'INSERT INTO Logs ( TimeKey, Component, ServerId, Pid, Level, Code, Message, File, Line ) VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ? )'; diff --git a/tests/perl/test_logger_db_outage.pl b/tests/perl/test_logger_db_outage.pl new file mode 100644 index 0000000000..b6afa2452b --- /dev/null +++ b/tests/perl/test_logger_db_outage.pl @@ -0,0 +1,71 @@ +#!/usr/bin/perl +use strict; +use warnings; +use FindBin; +use lib "$FindBin::Bin/../../scripts/ZoneMinder/lib"; + +use ZoneMinder::Logger qw(:all); +use ZoneMinder::Database; + +my $failures = 0; +my $passes = 0; + +sub check { + my ($name, $got, $want) = @_; + if ((defined $got ? $got : '') eq (defined $want ? $want : '')) { + $passes++; + print "ok - $name\n"; + } else { + $failures++; + print "NOT OK - $name: got '".(defined $got ? $got : '')."' want '".(defined $want ? $want : '')."'\n"; + } +} + +{ + package FakeSth; + sub execute { + my $self = shift; + push(@main::inserted, [@_]); + return 1; + } +} +{ + package FakeDbh; + sub ping { return $main::dbUp; } + sub prepare_cached { return bless({}, 'FakeSth'); } + sub errstr { return 'fake'; } +} + +our $dbUp = 1; +our @inserted; +{ + no warnings 'redefine'; + *ZoneMinder::Database::zmDbConnect = sub { + return unless $main::dbUp; + $ZoneMinder::Database::dbh = bless({}, 'FakeDbh'); + return $ZoneMinder::Database::dbh; + }; +} + +logInit(id=>'zm_test_dboutage', termLevel=>NOLOG, fileLevel=>NOLOG, syslogLevel=>NOLOG, databaseLevel=>NOLOG); +my $logger = ZoneMinder::Logger::fetch(); +$logger->{databaseLevel} = INFO; +$logger->level(INFO); +$ZoneMinder::Database::dbh = bless({}, 'FakeDbh'); + +Info('before the outage'); +check('a row is written while the database is up', scalar(@inserted), 1); + +$dbUp = 0; +Info('during the outage'); +check('nothing is written while the database is down', scalar(@inserted), 1); +check('the database level is kept', logDatabaseLevel(), INFO); + +$dbUp = 1; +Info('after the outage'); +check('logging to the database resumes', scalar(@inserted), 2); + +logTerm(); + +print "\n$passes passed, $failures failed\n"; +exit($failures ? 1 : 0);