PHP code example of mougrim / php-logger

1. Go to this page and download the library: Download mougrim/php-logger library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

mougrim / php-logger example snippets


use Mougrim\Logger\Appender\AppenderStream;
use Mougrim\Logger\Layout\LayoutPattern;
use Mougrim\Logger\Layout\LayoutSimple;
use Mougrim\Logger\Logger;

Logger::configure([
    'policy' => [
        'ioError' => 'trigger_error', // ignore, trigger_warn, trigger_error, exception or exit
        'configurationError' => 'exception'
    ],
    'layouts' => [
        'simple' => [
            'class' => LayoutSimple::class,
        ],
        'pattern' => [
            'class' => LayoutPattern::class,
            'pattern' => '{date:Y/m/d} [{level}] {logger} {location:file:line, class.function} {mdc:key} {mdc} {ndc}: {message} {ex}',
        ],
    ],
    'appenders' => [
        'stream' => [
            'class' => AppenderStream::class,
            'stream' => 'php://stdout',
            // pass useLock and useLockShortMessage true for enable lock
            'useLock' => false,
            'useLockShortMessage' => false,
            'minLevel' => Logger::DEBUG,
            'maxLevel' => Logger::FATAL,
            'layout' => 'simple',
        ],
    ],
    'loggers' => [
        'logger' => [
            'appenders' => ['stream'],
            'addictive' => false,
            'minLevel' => Logger::TRACE,
            'maxLevel' => Logger::FATAL,
        ],
    ],
    'root' => [
        'appenders' => ['stream'],
    ]
]);

Logger::getLogger('logger')->trace("hello world");
Logger::getLogger('logger')->debug("hello world");
Logger::getLogger('logger')->info("hello world");
Logger::getLogger('logger')->warn("hello world");
Logger::getLogger('logger')->fatal("hello world");
Logger::getLogger('logger')->log(Logger::DEBUG, "hello world");

LoggerMDC::put("request", $i++);
Logger::getLogger('accesslog')->info("new request");
Logger::getLogger('db')->info("execute sql");

# in some web log : cat log | grep 12412
accesslog [request=12412] new request
db [request=12412] execute sql

$logger = Logger::getLogger('db');
$timer = $logger->timer();
$pdo->exec('select * from foo');
$timer->info("sql executed at {time}"); // rendered at