PHP code example of devdot / monolog-parser

1. Go to this page and download the library: Download devdot/monolog-parser 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/ */

    

devdot / monolog-parser example snippets



use Devdot\Monolog\Parser;

// create a new parser bound to the given file
$parser = new Parser('test.log');

// retrieve the log records and print them
$records = $parser->get();
foreach($records as $record) {
    printf('Logged %s at %s with message: %s',
        $record->level,
        $record->datetime->format('Y-m-d H:i:s'),
        $record->message,
    );
}


use Devdot\Monolog\Parser;

$records = Parser::new('test.log')->get();

// ...

$parser = new Parser();
$parser = Parser::new(); // equivalent to new Parser()

$parser = Parser::new();
$parser->setFile('test.log'); // throws FileNotFoundException if file does not exist
$parser->isReady(); // true. The file is ready to be parsed

$parser = Parser::new()->setFile('test.log');
$records = $parser->parse()->get();
$records = $parser->get(); // this will return the records from cache
$records = $parser->parse()->get(); // this will re-parse the file

$parser = Parser::new()->setFile('test.log');
$records = $parser->get(); // this will parse the file
$records = $parser->clear()->get(); // this will re-parse the file
$records = $parser->get(false); // this will re-parse the file

$parser = new Parser();
$records = $parser->parse('[2023-01-01] test.DEBUG: message')->get();

$records = Parser::new('test.log')->get();
$first = $records[0]; // access the records just like an array
foreach($records as $record) {
    $record->datetime; // object of type DateTimeImmutable
    $record->channel; // string
    $record->message; // string
    $record->context; // object, empty array by default (decoded JSON)
    $record->extra; // object or array, empty array by default (decoded JSON)
}

// use provided patterns
$parser = Parser::new()->setPattern(Parser::PATTERN_LARAVEL);
// or build your regex with named subpatterns like this:
$parser->setPattern('/^\[(?<datetime>.*?)\] (?<message>.*?) \| (?<channel>\w+).(?<level>\w+)$/m');

$parser = Parser::new();
// set a single option
$parser->setOptions(Parser::OPTION_SORT_DATETIME);
// set multiple options
$parser->setOptions(Parser::OPTION_SKIP_EXCEPTIONS + Parser::OPTION_JSON_AS_TEXT);
// reset the parser to default settings
$parser->setOptions(Parser::OPTION_NONE);