diff --git a/src/Listeners/QueryListener.php b/src/Listeners/QueryListener.php index b6d0f26..64ce7c4 100644 --- a/src/Listeners/QueryListener.php +++ b/src/Listeners/QueryListener.php @@ -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']); } } diff --git a/src/Logging/LogstashFormatter.php b/src/Logging/LogstashFormatter.php new file mode 100644 index 0000000..c311ef4 --- /dev/null +++ b/src/Logging/LogstashFormatter.php @@ -0,0 +1,48 @@ +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"; + } +}