Bushikot Bushikot - 2 months ago 53
PHP Question

How can I write separate log files in Laravel 5?

I'd like to have separate log files to store debug data for some of my API methods. Something like

car_create.log
,
car_update.log
, etc.

Can I achieve this with the built-in logging functionality? Isn't it some kind of wrong approach? Because it seems like almost nobody have same issues. Any advice or suggestions will be much appreciated!

Answer

Yes, separate log files are possible.

The Errors & Logging documentation informs that Monolog is the underlying logging package used by Laravel. You can use Monolog to do anything you want.

Example Logging Helper

<?php

namespace App\Helpers\Common;

use Monolog\Logger;
use Monolog\Handler\StreamHandler;
use Carbon\Carbon;

class FileLogger extends Logger
{
    protected $path = null;

    public function __construct($name, $level = 'DEBUG', $path = null, array $processors = [ ])
    {
        $tz = static::$timezone = new \DateTimeZone(config('app.timezone'));
        $handlers = [ ];
        parent::__construct($name, $handlers, $processors);

        $dtObj = Carbon::now($tz);

        if ( ! $path) {
            $path = $name . '-' . $dtObj->format('Y-m-d') . '.log';
        }

        $path = $this->path = storage_path('logs/' . $path);

        $this->addStream($path, $level);

        return $this;
    }

    public static function getLevelNum($level)
    {
        return static::getLevels()[ strtoupper($level) ];
    }

    public function addStream($path, $level = 'DEBUG')
    {
        if ( ! is_int($level)) {
            $level = static::getLevelNum($level);
        }
        $this->pushHandler(new StreamHandler($path, $level));

        return $this;
    }

    public function addRecord($level, $message, array $context = array())
    {
        if ( ! is_int($level)) {
            $level = static::getLevelNum($level);
        }

        parent::addRecord($level, $message, $context);

        return $this;
    }
}

Example Usage

use App\Helpers\Common\FileLogger;

// ...

$level = 'DEBUG';

$logger = new FileLogger('NAME', $level);

$logger->addRecord($level, $message, $context);