change log to json

This commit is contained in:
dongwei 2019-03-15 16:57:43 +08:00
parent 47556ce2fe
commit 211ff1de4a
2 changed files with 53 additions and 9 deletions

View File

@ -2,9 +2,9 @@
namespace Arch\Listeners;
use Arch\Logging\LogstashFormatter;
use Illuminate\Database\Events\QueryExecuted;
use Monolog\Formatter\LineFormatter;
use Monolog\Handler\RotatingFileHandler;
use Monolog\Handler\StreamHandler;
use Monolog\Logger;
class QueryListener
@ -20,9 +20,8 @@ class QueryListener
public function __construct()
{
$this->logger = new Logger(env('APP_NAME', 'APP_NAME'));
$handler = new RotatingFileHandler(storage_path('/logs/sql.log'), 15);
$formatter = new LineFormatter(null, null, false, true);
$handler->setFormatter($formatter);
$handler = new StreamHandler(storage_path('/logs/sql.log'));
$handler->setFormatter(new LogstashFormatter());
$this->logger->pushHandler($handler);
}
@ -36,10 +35,7 @@ class QueryListener
{
if (env('APP_DEBUG')) {
$sql = str_replace("?", "'%s'", $event->sql);
$log = vsprintf($sql, $event->bindings);
$requestId = app('request')->header('x-request-id','nginx_config_error');
$text = "$requestId\t$log\t";
$this->logger->debug($text, ['conn' => $event->connectionName, 'time' => $event->time.'ms']);
$this->logger->debug(vsprintf($sql, $event->bindings), ['conn' => $event->connectionName, 'time' => $event->time.'ms']);
}
}

View File

@ -0,0 +1,48 @@
<?php
/**
* Created by PhpStorm.
* User: dongwei
* Date: 2019/1/10
* Time: 3:18 PM
*/
namespace Arch\Logging;
use Monolog\Formatter\NormalizerFormatter;
class LogstashFormatter extends NormalizerFormatter
{
protected $hostname;
public function __construct()
{
// logstash requires a ISO 8601 format date with optional millisecond precision.
parent::__construct('Y-m-d\TH:i:s.uP');
$this->hostname = gethostname();
}
public function format(array $record)
{
$record = parent::format($record);
$message = array(
'@timestamp' => $record['datetime'],
'host' => $this->hostname,
'app' => env('APP_NAME'),
);
$request_id = app('request')->header('X-Request-Id');
if ($request_id) {
$message['request_id'] = $request_id;
}
if (isset($record['message'])) {
$message['sql'] = $record['message'];
}
if (!empty($record['context'])) {
$message['conn'] =$record['context']['conn'];
$message['time'] =$record['context']['time'];
}
return $this->toJson($message) . "\n";
}
}