首页 > 解决方案 > 强制松弛登录到队列中

问题描述

我有点进退两难,因为我需要想出一个好的记录器来记录应用程序中发生的事情,如果有Log::error调用,它还应该通过 slack 通知开发人员和系统管理员。它目前正在工作,但它增加了请求响应时间的开销。

以下是我的设置:

//config/logging.php
    'default' => env('LOG_CHANNEL', 'stack'),
    //truncated
    'channels' => [
        'stack' => [
            'driver' => 'stack',
            'channels' => ['daily', 'slack'],
        ],

        'daily' => [
            'driver' => 'daily',
            'path' => storage_path('logs/laravel.log'),
            'level' => 'debug',
            'days' => 0,
        ],

        'slack' => [
            'driver' => 'slack',
            'url' => env('LOG_SLACK_WEBHOOK_URL'),
            'username' => 'App',
            'emoji' => ':boom:',
            'level' => 'error',
        ]
    ]
    //truncated

//UserController
public function show(User $user)
{
    //just a sample code, the important part is where the Log facade is called
    try {
        //business logic
    } catch (Exception $e) {
        Log::error(get_class(), [
            'user_id' => $user->id,
            'message' => $e->getMessage()
        ]);
    }  

    return view('user.show', compact($user));
}

它已经在工作了,但可以肯定的是,即使上面代码所增加的时间可以忽略不计,我们仍然可以改进它以减少开销,但是真正的代码更复杂并且有很多迭代

如何更改修改“松弛”记录器的行为以在触发时将其推入队列?我更喜欢编码一次然后忘记它,而不是记住我必须将它推送到按需记录器,例如

Log::chanel(['daily', 'slack'])->...

或者

//this is good for more on particular event notification but not not error notification which can happen anywhere
Notification::route('slack', env('LOG_SLACK_WEBHOOK_URL'))->notify(new AlertDevInSlackNotification)`

笔记:

//bootstrap/app.php
$app->configureMonologUsing(function($monolog) use ($app) {
    //some code here. does not work, just getting page not working
});

标签: laravelmonolog

解决方案


你可以这样做。

1.创建工作ex:名称为LogSlackQueue.php

public class LogSlackQueue implements ShouldQueue {
     ...
     ...
     public function handle() {
          Log::channel(['daily', 'slack'])->info($your_input);
     }
}

2.然后用作

LogSlackQueue::dispatch($your_input)

如果您不想像上面那样做,则需要弄清楚以制作自定义提供程序


推荐阅读