简体   繁体   中英

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!

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM