简体   繁体   English

如何在Laravel 5中编写单独的日志文件?

[英]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. 我想有一些单独的日志文件来存储我的一些API方法的调试数据。 Something like car_create.log , car_update.log , etc. car_create.logcar_update.log等等。

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. 错误日志记录和文档通知独白是由Laravel使用的底层日志包。 You can use Monolog to do anything you want. 您可以使用Monolog做任何您想做的事情。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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