kuvalda-log/Loger.php

107 lines
3.7 KiB
PHP
Raw Permalink Normal View History

2024-11-20 15:58:07 +03:00
<?php
namespace dominion\log;
use Yii;
use yii\log\FileTarget;
class Loger extends FileTarget
{
public $logVars = [];
public $format = 'result';
public static function log($type, $result, $prefixFile = '', $log = false)
{
$config = Yii::$app->params['log'];
if ($type == 'error' || YII_DEBUG || $log)
{
$model = new Loger;
$model->maxFileSize = isset($config['maxFileSize']) ? $config['maxFileSize'] : 10;
$model->maxLogFiles = isset($config['maxLogFiles']) ? $config['maxLogFiles'] : 10000;
$model->enableRotation = isset($config['enableRotation']) ? (bool)$config['enableRotation'] : true;
$dir = Yii::getAlias($config['dir']);
$model->logFile = $dir . $prefixFile . (empty($prefixFile) ? $type : ucfirst($type) ) . '.log';
$model->messages = [$result];
$model->export();
}
if (isset($config['longRequestTime'], $result['time']) && $result['time'] > $config['longRequestTime'])
{
$model = new Loger;
$model->maxFileSize = isset($config['maxFileSize']) ? $config['maxFileSize'] : 10;
$model->maxLogFiles = isset($config['maxLogFiles']) ? $config['maxLogFiles'] : 10000;
$model->enableRotation = isset($config['enableRotation']) ? (bool)$config['enableRotation'] : true;
$dir = Yii::getAlias($config['dir']);
$model->logFile = $dir . 'longRequestTime.log';
$model->format = 'time';
$model->messages = [$result['time']];
$model->export();
}
}
public function formatMessage($result)
{
$output = '';
$url = '';
$post = '';
$jwt = 'console';
$HTTP_X_REAL_IP = '';
if(!is_a(Yii::$app->request, 'yii\console\Request'))
{
$url = Yii::$app->request->url;
$post = json_encode(Yii::$app->request->post(), JSON_UNESCAPED_UNICODE);
$jwt = str_replace('Bearer ', '', Yii::$app->request->getHeaders()->get('Authorization'));
$HTTP_X_REAL_IP = Yii::$app->request->getHeaders()->get('HTTP_X_REAL_IP');
}
switch ($this->format)
{
case 'time':
$output = sprintf(
"[%s]\t%s\t%s\t%s",
date('Y-m-d H:i:s'),
$url,
json_encode($result, JSON_UNESCAPED_UNICODE),
$post
);
break;
case 'json':
$error = $result[0];
if(is_a($error, 'Exception'))
{
$message = $error->getMessage() . ' in '.$error->getFile().':'.$error->getLine();
$output = json_encode([
'date' => date('Y-m-d H:i:s'),
'url' => $url,
'message' => $message ,
'trace' => $error->getTraceAsString(),
'graphql' => $post,
'jwt' => $jwt,
'HTTP_X_REAL_IP' => $HTTP_X_REAL_IP
], JSON_UNESCAPED_UNICODE);
}
else
{
// $output = print_r($result, true);
}
// var_dump($output);
break;
case 'result':
default :
$output = sprintf(
"[%s]\t%s\t%s\t%s",
date('Y-m-d H:i:s'),
$url,
$post,
json_encode($result, JSON_UNESCAPED_UNICODE)
);
break;
}
return $output;
}
}