PHP code example of shays / logger

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

    

shays / logger example snippets


use Shays\Logger;
use Shays\Logger\Stream\FileStream;

$log = (new Logger('MyApp'))->addStream(new FileStream('application.log'));
$log->notice('Log message');

use DateTimeZone;
use Shays\Logger;
use Shays\Logger\Stream\FileStream;

$log = (new Logger('MyApp'))
    ->addStream(new FileStream('application.log'))
    ->setTimezone(new DateTimeZone('Europe/London'));

$log->notice('Log message');

use Shays\Logger;
use Shays\Logger\Stream\FileStream;

$log = (new Logger('MyApp'))
    ->addStream(new FileStream('application.log'))
    ->addContext([
        'environment' => 'local',
    ]);

$log->notice('Log message');

// Simple log context added
$log->notice('User not found', ['id' => 123]);

// Adding captured exception information
try {
    // Trying an API connection
} catch (\Throwable $e) {
    $log->error('API connection failed', ['exception' => $e]);   
}

 use Shays\Logger;
 use Shays\Logger\LogLevel;
 use Shays\Logger\Stream\FileStream;
 
 $log = (new Logger('MyApp'))
     ->addStream(new FileStream('application.log', LogLevel::ERROR));

// This won't be logged to the file
$log->notice('Log message');
 

// CustomLogLevel.php

class CustomLogLevel {
    /** @var int New progress log level (e.g. for logging cron task requests) */
	const PROGRESS = 50;
}
 

 use CustomLogLevel;
 use Shays\Logger;
 use Shays\Logger\Stream\FileStream;
 
 $log = (new Logger('MyApp'))
     ->addStream(new FileStream('application.log', CustomLogLevel::PROGRESS))
     ->addLogLevel(CustomLogLevel::PROGRESS, 'PROGRESS');

// This is now possible to call it directly 
$log->progress('Log message');
 

// MyCustomHandler.php

use Shays\Logger\Handlers\LogHandlerInterface;
use Shays\Logger\LogInterface;
use Shays\Logger\LogLevel;

class MyCustomHandler implements LogHandlerInterface
{
    public function handle(LogInterface $log): void
    {
        // Do anything with the log object 
        // (e.g. get the message, context, etc)
        // (read more about the Log object below)
    }

    public function shouldHandle(LogInterface $log): bool
    {
        // e.g. handle notices and the more severe logs 
	    return $log->getLevel() >= LogLevel::NOTICE;
    }
}
 

use MyCustomHandler;
use Shays\Logger;
 
$log = (new Logger('MyApp'))
    ->addHandler(new MyCustomHandler());

// XmlStream.php

use Shays\Logger\LogInterface;
use Shays\Logger\Stream\StreamInterface;

class XmlStream implements StreamInterface
{
	/** @var int Lowest log level for handling log */
	private $lowestLevel;

	public function __construct(int $lowestLevel)
	{
        $this->lowestlevel = $lowestLevel;
	}

	public function write(string $log): void
	{
	    // Write the serialized log to the database or system file
	}

	public function shouldWrite(LogInterface $log): bool
	{
	    return $log->getLevel() >= $this->lowestLevel;
	}
}

use Shays\Logger;
use XmlStream;
 
 $log = (new Logger('MyApp'))
     ->addStream(new XmlStream(LogLevel::ERROR));
 

// XmlSerializer.php

use Shays\Logger\LogInterface;
use Shays\Logger\Serializer\SerializerInterface;
use Symfony\Component\Serializer\Encoder\XmlEncoder;

class XmlSerializer implements SerializerInterface
{
    private $encoder;

    public function __construct()
    {
        $this->encoder = new XmlEncoder();
    }

    public function serialize(LogInterface $log)
    {
        // Serialize the data to XML format which would
        // be then passed to the streaming classes.

        // The $log->toArray() method is transforming the
        // log object to an array with the relevant
        // log information, ready to be serialized
        return $this->encoder->encode($log->toArray(), 'xml');
    }
}

use XmlSerializer;
use XmlStream;
use Shays\Logger;
 
 $log = (new Logger('MyApp', new XmlSerializer()))
     ->addStream(new XmlStream(LogLevel::ERROR));

class MyCustomHandler implements LogHandlerInterface
{
    public function handle(LogInterface $log): void
    {
        // Handle log
    }
}

$log->getMessage();

$log->getChannel();

$log->getLevel();

$log->getLevelName();

$log->getTimestamp();

$log->getAllContext();

// Check if exists
$log->hasContext('userId');

// Get the context
$log->getContext('userId');

// Gets the log message
$log->get('message');

// Gets the log level
$log->get('level');

// Gets the userId context (fallback to context)
$log->get('userId');

// CustomLog.php
use Shays\Logger\Log;

class CustomLog extends Log
{
    public function toArray(): array
    {
        $context = $this->getAllContext();
        // Remove environment from context (which will be used on the top array level)
        unset($context['environment']);
        return [
            'timestamp' => $this->getTimestamp(),
            'level' => $this->getLevel(),
            'message' => $this->getMessage(),
            'levelName' => $this->getLevelName(),
            'environment' => $this->getContext('environment'),
            'additionalData' => $context,
        ];
    }
}

use CustomLog;
use Shays\Logger;
use Shays\Logger\Stream\FileStream;
 
 $log = (new Logger('MyApp', null, CustomLog::class))
    ->addStream(new FileStream('application.log'))
    ->addContext([
        'environment' => 'debug',
        'ipAddress' => '127.0.0.1',
    ]);

$log->info('Info message');