ZF2 custom logfile, set username

135 views Asked by At

How can I make custom log (using Zend2) and set username to every log event. Here is my example how I`m trying:

public function log( )
{

    $log_file = 'path/to/logfile.log';

    $format = '%timestamp% %priorityName% (%username%) %message%';
    $formatter = new Zend\Log\Formatter\Simple($format);
    $formatter->setDateTimeFormat('H:i:s');

    $formatter->format( array('username'=> SET_USER_NAME ));

    $logWriter = new LogWriter($log_file);
    $logWriter->setFormatter($formatter);

    $logger = new Logger;
    $logger->addWriter( $logWriter );

    return $logger;
}

I tried the following

$this->log()->info(" Log message " );

And result is:

11:33:54 INFO (%username%) Log message

Thanks!

1

There are 1 answers

0
lku On

You can use third parameter of log method extra - array of extra data, which are converted to json and automatically added to log message by formatter (Zend\Log\Formatter\Simple::format)

Simple example:

$writer = new \Zend\Log\Writer\Stream('php://output');
$logger = new \Zend\Log\Logger();
$logger->addWriter($writer);

$logger->info('Informational message', ['user' => 'administrator']);

Outputs something like this:

2014-12-01T13:00:00+00:00 INFO (6): Informational message {"user":"administrator"}