Laravel logs are stored in different files according to different types.

1. Reason: Because other third-party packages are involved, such as WeChat payment, etc., it is difficult to find if the logs are kept together.

2. Implementation class

<?php

namespace App\helpers;

use Illuminate\Foundation\Application;
use Monolog\Handler\RotatingFileHandler;
use Monolog\Logger;

/**
 * @method static void needSolve($msg, array $context = [], $type = 'info')
 * @method static void queueJob($msg, array $context = [], $type = 'info')
 * @method static void pay($msg, array $context = [], $type = 'info')
 * @method static void jPush($msg, array $context = [], $type = 'info')
 * @method static void map($msg, array $context = [], $type = 'info')
 */
class SimpleLogger
{
    /**
     * @var Logger
     */
    private static $monolog;

    public static function getMonolog()
    {
        if (!self::$monolog instanceof Logger) {
            self::$monolog = new Logger(self::channel());
        }
        return self::$monolog;
    }

    public static function __callStatic($name, $arguments)
    {
        static::write($arguments[0], isset($arguments[2]) ? $arguments[2] : 'info', $name, $arguments[1]);
    }

    protected static function write($msg, $type, $category, $context = [])
    {
        $file = static::getCommonLogDir($category);
        $monolog = self::getMonolog();
        $monolog->pushHandler(new RotatingFileHandler($file));
        // 将类别记录到日志中
        $monolog->pushProcessor(function ($record)use ($category){
            $record['level_name'] = "{$record['level_name']}.[{$category}]";
            return $record;
        });
        $monolog->$type($msg, $context);
    }

    /**
     * 获取日志存储路径
     * @param $category
     * @param bool $noDate
     * @return string
     */
    public static function getCommonLogDir($category, $noDate = false)
    {
        $log = storage_path('logs' . DIRECTORY_SEPARATOR . $category . DIRECTORY_SEPARATOR . $category . '.log');
        if (!$noDate) {
            $date = date('Ymd');
            $log = storage_path('logs' . DIRECTORY_SEPARATOR . $category . DIRECTORY_SEPARATOR . $category . $date . '.log');
        }
        return $log;
    }

    protected static function channel()
    {
        /** @var Application $app */
        $app = app();
        if ($app->bound('config') &&
            $channel = $app->make('config')->get('app.log_channel')) {
            return $channel;
        }

        return $app->bound('env') ? $app->environment() : 'production';
    }
}

3. Examples of class usage:

 SimpleLogger::needSolve('需要解决的日志'.date('Y-m-d H:i:s',time()),['name'=>'张三','sex'=>'男']);

4. Display the results:

Guess you like

Origin blog.csdn.net/qiuqiuLovecode/article/details/103892238