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

需求

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

实践

引用拓展包

$ composer require ruflin/elastica: ^5.0

ruflin/elastica 拓展包说明

Elastica ElasticSearch elasticsearch-php PHP
5.x 5.x ^5.0 >=5.6
3.2.3 (unmaintained) 2.4.0 no >=5.4
2.x (unmaintained) 1.7.2 no >=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



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 中显示
laravel接合monolog实现日志记录到Elasticsearch实践_第1张图片

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

你可能感兴趣的:(laravel接合monolog实现日志记录到Elasticsearch实践)