unix - multiple using openlog php

916

I use logging in my project, at first, then I initialize some object, I use openlog function with specific ident, and then use syslog to write all I need. But I have one problem, there are some external requests inside objects, and I wanna change ident for them, so I try to do something like:

openlog($ident, LOG_PID, LOG_USER);
syslog(LOG_DEBUG, $data);
....
// external request in other place, where $ident is not available
openlog($newIdent, LOG_PID, LOG_USER);
syslog(LOG_DEBUG, $data);
closelog();
// here I wanna change openlog to initial value
openlog(?, LOG_PID, LOG_USER);

So how can I get first openlog ident, or Is it another method to do the same thing?

16

Answer

Solution:

Here's some code that I think works. I'm using a singleton classLogger:

<?

class Logger {
    private $idents = [];

    public static function Instance()
    {
        static $inst = null;
        if ($inst === null) {
            $inst = new Logger();
        }
        return $inst;
    }

    private function __construct()
    {

    }

    function openlog($ident, $option = LOG_PID, $facility = LOG_USER) {
        array_unshift($this->idents, $ident);
        return openlog($ident, $option, $facility);
    }

    function closelog() {
        closelog();
        array_shift($this->idents);
        if ($this->idents) {
            return openlog($this->idents[0]);
        }
    }
}

$logger = Logger::Instance();

$ident = 'id1';

$logger->openlog($ident, LOG_PID, LOG_USER);

$data = 'test1';
syslog(LOG_DEBUG, $data); // Logs to 'id1'


$newIdent = 'id2';
$logger->openlog($newIdent, LOG_PID, LOG_USER);

$data = 'test2';
syslog(LOG_DEBUG, $data); // Logs to 'id2'
$logger->closelog();

$data = 'test3';
syslog(LOG_DEBUG, $data); // Logs to 'id1'

$logger->closelog();
$data = 'test4';
syslog(LOG_DEBUG, $data); // Logs to the default ident
$logger->closelog();

People are also looking for solutions to the problem: php - Typo3 Plugin Inline Records in Frontend Controller

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.