将日志注册到 GomaGaming 后端服务


README

描述

  • GomaGaming Logs 跟踪异常、请求和响应以及自定义日志,并将它们与相关元数据(路径、参数、头信息等)一起发送到特定队列中,以便进行适当的处理。

Laravel 版本兼容性

  • Laravel >= 8.x.x 在 PHP >= 7.3

Lumen 版本兼容性

  • Lumen >= 8.x.x 在 PHP >= 7.3

安装

    composer require gomagaming/logs

Lumen 专用

将 GomaGamingLogsServiceProvider 添加到 bootstrap/app.php

    $app->register(GomaGaming\Logs\GomaGamingLogsServiceProvider::class);

配置文件

默认情况下,所有日志都会发送到名为 'logs' 的队列中,但可以在配置文件 gomagaminglogs.php 中进行更改

Lumen 专用

    cp vendor/gomagaming/logs/config/gomagaminglogs.php config/gomagaminglogs.php

使用方法

通过以下修改 App/Exceptions/Handler.php 来启用捕获未处理的异常

Laravel

    use GomaGaming\Logs\GomaGamingLogs;

    public function register()
    {
        $this->reportable(function (Throwable $e) {

            if ($this->shouldReport($e)) {
                GomaGamingLogs::error($e->getMessage());
            }

        });
    }

Lumen

    use GomaGaming\Logs\GomaGamingLogs;

    public function report(Throwable $exception)
    {
        if ($this->shouldReport($exception)) {
            GomaGamingLogs::error($exception->getMessage());
        }

        parent::report($exception);
    }

要捕获有关所有传入请求或所有响应的信息,请将以下中间件添加为全局或应用于一组

在 Laravel 中添加到 app/Http/Kernel.php

    protected $middleware = [
        (...)
        \GomaGaming\Logs\Http\Middleware\LogRequests::class,
        \GomaGaming\Logs\Http\Middleware\LogResponses::class,
    ];

在 Lumen 中添加到 bootstarp/app.php

    $app->middleware([
        \GomaGaming\Logs\Http\Middleware\LogRequests::class,
        \GomaGaming\Logs\Http\Middleware\LogResponses::class
    ]);

也可以报告自定义错误或信息

    use GomaGaming\Logs\GomaGamingLogs;

    GomaGamingLogs::info("This is an information about my service.");
    GomaGamingLogs::error("This is an error ocurring in my service");

对于不希望向用户提供异常信息的 API,我们可以将 App/Exceptions/Handler.php 中的 render 方法更改为始终返回 http 状态码 500 并带有自定义消息,例如

    public function render($request, Throwable $exception)
    {
        (...)

        //might want to check if request is asking for json response

        return response()->json(['status' => 'error', 'msg' => 'Internal Server Error'], 500);
    }

待办事项

测试