Jerry's WIKIJerry's WIKI
Overview
  • ๐Ÿž Web
  • ๐Ÿ“ Components
  • ๐Ÿ’ก Skills
  • ๐ŸŽฑ Specification
  • ๐Ÿ–ฅ Workflows
  • ๐Ÿ›  Tools
  • ๐ŸŒ๏ธ Linux
  • ๐Ÿ“ฆ Container
  • โ™จ๏ธ Language
Coffee
  • ็ฎ€ไฝ“ไธญๆ–‡
  • English
GitHub
Overview
  • ๐Ÿž Web
  • ๐Ÿ“ Components
  • ๐Ÿ’ก Skills
  • ๐ŸŽฑ Specification
  • ๐Ÿ–ฅ Workflows
  • ๐Ÿ›  Tools
  • ๐ŸŒ๏ธ Linux
  • ๐Ÿ“ฆ Container
  • โ™จ๏ธ Language
Coffee
  • ็ฎ€ไฝ“ไธญๆ–‡
  • English
GitHub
  • ๐Ÿ“ž Event Mechanism

    • Event Roles and Considerations
    • Code Example
  • โฐ Crontab
  • โ›“ Processes
  • ๐Ÿ“ File System
  • ๐Ÿ•“ Cache
  • ๐Ÿ“ฉ Queue

    • Queue Usage
    • Notes
  • ๐Ÿšฆ Signal
  • ๐Ÿ“ค GuzzleHttp
  • ๐Ÿ“‰ Rate Limiter
  • โŒ Exception
  • ๐Ÿ–จ Logs
  • ๐Ÿ“ก Command
  • ๐Ÿ” WebSocket

Logs

Index

  • Install Dependencies
  • Log Config
  • Encapsulation Of The Call.

ใ€Tipใ€‘

  • The log handling Handler includes Monolog\Handler\StreamHandler and Monolog\Handler\RotatingFileHandler, where the configuration is for a processor that rotates based on the date.
  • Logs of INFO level and above will be written to the info log, and logs of ERROR level and above will be written to the error log. The logs are split by day.
  • Hyperf has referenced some content from monolog. For more details, see: Monolog.

Install Dependencies

composer require hyperf/logger

Log Config

config/autoload/logger.php


<?php

declare(strict_types=1);
use Monolog\Level;

return [
    'default' => [
        'handlers' => [
            // ่ฎฐๅฝ•INFO็บงๅˆซๅŠไปฅไธŠ็ญ‰็บงๆ—ฅๅฟ—
            [
                'class' => Monolog\Handler\RotatingFileHandler::class,
                'constructor' => [
                    'filename' => BASE_PATH . '/runtime/logs/info.log',
                    'level' => Level::Info,
                ],
                'formatter' => [
                    'class' => Monolog\Formatter\LineFormatter::class,
                    'constructor' => [
                        'format' => "[%datetime%]|[%channel%]|[%level_name%]|[%message%]|[%context%]\n",
                        'dateFormat' => 'Y-m-d H:i:s',
                        'allowInlineLineBreaks' => true,
                    ],
                ],
            ],
            // ่ฎฐๅฝ•ERRORๅŠไปฅไธŠๆ—ฅๅฟ—
            [
                'class' => Monolog\Handler\RotatingFileHandler::class,
                'constructor' => [
                    'filename' => BASE_PATH . '/runtime/logs/error.log',
                    'level' => Level::Error,
                ],
                'formatter' => [
                    'class' => Monolog\Formatter\LineFormatter::class,
                    'constructor' => [
                        'format' => "[%datetime%]|[%channel%]|[%level_name%]|[%message%]|[%context%]\n",
                        'dateFormat' => 'Y-m-d H:i:s',
                        'allowInlineLineBreaks' => true,
                    ],
                ],
            ],
        ],
    ],
];

Example:

Encapsulation Of The Call.

<?php

declare(strict_types=1);

namespace App\Lib\Log;

use App\Constants\ConstCode;
use App\Job\ReportLogJob;
use App\Lib\RedisQueue\RedisQueueFactory;
use Carbon\Carbon;
use Hyperf\Context\ApplicationContext;
use Hyperf\Contract\StdoutLoggerInterface;
use Hyperf\Coroutine\Coroutine;
use Hyperf\Logger\LoggerFactory;
use Hyperf\Stringable\Str;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;
use Psr\Log\LoggerInterface;

/**
 * @method static void info(string $msg, array $content = [], string $straceString = '')
 * @method static void warning(string $msg, array $content = [], string $straceString = '')
 * @method static void error(string $msg, array $content = [], string $straceString = '')
 * @method static void alert(string $msg, array $content = [], string $straceString = '')
 * @method static void critical(string $msg, array $content = [], string $straceString = '')
 * @method static void emergency(string $msg, array $content = [], string $straceString = '')
 * @method static void notice(string $msg, array $content = [], string $straceString = '')
 */
class Log
{
    /**
     * ้™ๆ€่ฐƒ็”จ.
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public static function __callStatic(string $level, array $args = []): void
    {
        // ่Žทๅ–ๆœ€่ฟ‘ไธคๅฑ‚็š„่ฐƒ็”จๆ ˆไฟกๆฏ
        [$headTrace, $lastTrace] = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
        // ้™ๆ€่ฐƒ็”จๅ‚ๆ•ฐๅค„็†
        [$message, $context, $traceString] = [
            $args[0] ?? '',
            $args[1] ?? [],
            $args[2] ?? '',
        ];
        // ่Š‚็‚นchannel
        $channel = "{$lastTrace['class']}@{$lastTrace['function']}";
        // ๅฝ“ๅ‰ๆ—ฅๆœŸ
        $nowDate = Carbon::now()->toDateTimeString();
        // string context
        $contextString = json_encode($context, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);

        // ๅผ‚ๆญฅ้˜Ÿๅˆ—ๅ†™ๅ…ฅๆ•ฐๆฎๅบ“(ๅฏไปฅ็”จๅ…ถไป–ๆ–นๅผๆ›ฟไปฃๆ—ฅๅฟ—ไธŠๆŠฅ)
        $jobParams = [
            'level' => Str::upper($level),
            'class' => $lastTrace['class'],
            'function' => $lastTrace['function'],
            'message' => $message,
            'context' => $contextString,
            'file' => $headTrace['file'],
            'line' => $headTrace['line'],
            'trace' => $traceString,
        ];
        Coroutine::create(function () use ($jobParams) {
            $job = new ReportLogJob(uniqid(), $jobParams);
            RedisQueueFactory::safePush($job, ConstCode::LOCK_QUEUE_NAME, 0);
        });

        // CLI่พ“ๅ‡บ
        $stdoutMessage = $traceString === '' ?
            "[{$nowDate}][{$channel}][{$message}]" :
            "[{$nowDate}][{$channel}][{$message}]\n{$traceString}";
        static::stdout()->{$level}($stdoutMessage);
        // DISK่พ“ๅ‡บ
        static::get($channel)->{$level}($message, $context);
    }

    /**
     * ่Žทๅ–Loggerๅฎžไพ‹.
     * @throws ContainerExceptionInterface|NotFoundExceptionInterface
     */
    public static function get(string $channel = ''): LoggerInterface
    {
        return ApplicationContext::getContainer()->get(LoggerFactory::class)->get($channel);
    }

    /**
     * CLI ๆ—ฅๅฟ—ๅฎžไพ‹.
     * @throws ContainerExceptionInterface|NotFoundExceptionInterface
     */
    public static function stdout(): StdoutLoggerInterface
    {
        return ApplicationContext::getContainer()->get(StdoutLoggerInterface::class);
    }
}
Edit this page
Update At:
Contributor: ็”ฐๆœๅธ†
Prev
Exception
Next
Command