laravel接合monolog实现日志记录到Elasticsearch实践

需求

记录所有前台用户请求返回数据到ES

实践

引用拓展包

$ composer require ruflin/elastica: ^5.0

ruflin/elastica 拓展包说明

ElasticaElasticSearchelasticsearch-phpPHP
5.x5.x^5.0>=5.6
3.2.3 (unmaintained)2.4.0no>=5.4
2.x (unmaintained)1.7.2no>=5.3.3

由于项目中已经继承了BaseController ,其中有所有接口通过showReturnCodeAndSaveLog返回(也可以通过中间件的方式去实现)


/**
     * 返回函数
     * 
     * @param        $code
     * @param string $msg
     * @param array  $data
     *
     * @return array
     */
    protected function showReturnCodeAndSaveLog($code, $msg = '', $data = [])
    {
        //添加日志内容
        $this->addLog($msg, $data);
        //返回信息
        return self::showReturnCode($code, $msg, $data);
    }

添加析构函数

/**
     * 保存日志动作
     */
    protected function saveLogAction()
    {
        if (!empty($this->log)) {
            //获取文件前缀&&es的type
            $file_title = $this->getLogTitle();
            //添加es日志记录队列
            $job     = (new JobEsMonolog($this->request->method(), $this->log, $file_title))->onQueue(config('queue_list.lcsc'));
            dispatch($job);
            //添加文本日志
            if ($file_title) {
                $log = newLogRecord($file_title . '-' . date('Ymd'), env('APP_NAME'));
                foreach ($this->log as $info) {
                    $log->info($this->request->method(), $info);
                }
            } else {
                info($this->request->method(), $this->log);
            }

        }
    }


	public function __destruct()
    {
        if (!empty($this->log) && $this->saveLog == true) {
            //保存日志
            $this->saveLogAction();
        }
    }

添加job

$ php artisan make:job JobEsMonolog

JobEsMonolog.php

<?php

namespace App\Jobs;

use Elastica\Client;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Monolog\Formatter\ElasticaFormatter;
use Monolog\Handler\ElasticSearchHandler;
use Monolog\Logger;

class JobEsMonolog implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    //日志message
    private $msg;
    //日志内容
    private $data;
    //es type
    private $type;
    //错误级别
    private $level;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($msg,$data,$type = 'orders',$level = Logger::INFO)
    {
        $this->msg   = $msg;
        $this->data  = $data;
        $this->type  = $type;
        $this->level = $level;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        //es host配置
        $es_host = env('ES_HOSTS','192.168.12.35:9202');
        $es_host_array = explode(':',$es_host);
        $config = [
            'host'=>$es_host_array[0],
            'port'=>$es_host_array[1],
        ];
        $client  = new Client($config);
        $options = [
            'index' => 'monolog_' . date('Y_m_d'),
            'type'  => $this->type,
        ];
        $handler = new ElasticSearchHandler($client, $options);
        //es formatter
        $formatter = new ElasticaFormatter($options['index'],$options['type']);
        $handler->setFormatter($formatter);
        $log = new Logger('monolog');
        $log->pushHandler($handler);

        //目前暂时引用两种
        switch ($this->level) {
            case Logger::INFO :
                $log->info($this->msg,$this->data);
                break;
            case Logger::DEBUG :
                $log->debug($this->msg,$this->data);
                break;
            default :
                $log->warning('未添加错误类型',$this->data);
                break;
        }
    }
}

kibana 中显示
在这里插入图片描述

其实对于大家来说就只有JobEsMonolog代码比较有参考价值;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值