首先在config/logging中配置日志的channel和驱动和handler.'YS_YJCX'=>['driver'=>'monolog','level'=>&...
首先在config/logging中配置日志的channel和驱动和handler.
'YS_YJCX' => [
'driver' => 'monolog',
'level' => 'debug',
'handler' => \App\Log\YsLogHandler::class,
'handler_with' => [
'url' => 'http://192.168.0.212:8081/log/save',
'project'=>'分销TMC系统',
'module' => '运价查询',
],
],
对应的YsLogHandler代码
<?php
namespace App\Log;
use Illuminate\Support\Facades\Log;
use Monolog\Logger;
use Monolog\Handler\AbstractProcessingHandler;
class YsLogHandler extends AbstractProcessingHandler
{
private $url;
private $module;
private $project;
public function __construct($url,$project,$module = '运价查询', $level = Logger::DEBUG, $bubble = true)
{
$this->url = $url;
$this->module = $module;
$this->project = $project;
parent::__construct($level, $bubble);
}
protected function write(array $record)
{
$level = '';
switch ($record['level']) {
case 100:
#DEBUG
$level = 'Info';
break;
case 200:
#INFO
$level = 'Info';
break;
case 250:
#NOTICE
$level = 'Info';
break;
case 300:
#WARNING
$level = 'Warn';
break;
case 400:
#ERROR
$level = 'Error';
break;
case 550:
#ALERT
$level = 'Fatal';
break;
}
$logContent = ['channel' => $record['channel'],
'level' => $level,
'message' => $record['formatted'],
'time' => date('Y-m-d\TH:i:s\.000\+08:00', $record['datetime']->format('U')),
'project' => $this->project,
'module' => $this->module,
'user' => '7924',
];
$result = json_decode($this->Post($this->url, json_encode($logContent)), true);
if ($result['status'] !== 'success') {
Log::error('日志中心写入失败:', $record);
}
}
protected function Post($url, $parameter, $timeout = 60)
{
$header = array(
'Content-Type:' . 'application/json',
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
if (!empty($header)) {
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_HEADER, 0);
}
if ($parameter) {
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $parameter);
}
$data = curl_exec($ch);
if ($data === FALSE) {
Logger::ERROR(curl_error($ch));
}
curl_close($ch);
return $data;
}
}
全文详见:http://xpxw.com/?id=129