2 Commits

Author SHA1 Message Date
sunxyw
0ee6e43f06 change method sign to static 2022-12-21 21:09:53 +08:00
sunxyw
9da98fde5a add caller to log format 2022-12-21 20:58:26 +08:00
2 changed files with 54 additions and 16 deletions

View File

@@ -10,14 +10,14 @@ use Psr\Log\LogLevel;
class ConsoleLogger extends AbstractLogger
{
public const VERSION = '1.1.2';
public const VERSION = '1.1.0';
/**
* 日志输出格式
*
* @var string
*/
public static $format = '[%date%] [%level%] %body%';
public static $format = '[%date%] [%level%] %caller% %body%';
/**
* 日志输出日期格式
@@ -139,6 +139,27 @@ class ConsoleLogger extends AbstractLogger
return self::VERSION;
}
/**
* 插入字段到指定字段之前,或之后
* @param string $field 字段名
* @param string $alter 要插入的字段
* @param string $position 插入位置before 或 after
*/
public static function alterFormat(string $field, string $alter, string $position = 'before'): void
{
$format = self::$format;
$pos = strpos($format, $field);
if ($pos === false) {
return;
}
if ($position === 'before') {
$format = substr_replace($format, $alter, $pos, 0);
} else {
$format = substr_replace($format, $alter, $pos + strlen($field), 0);
}
self::$format = $format;
}
/**
* 添加静态上下文
*/
@@ -213,14 +234,17 @@ class ConsoleLogger extends AbstractLogger
if (!$this->shouldLog($level)) {
return;
}
$log_replace = [
'%date%' => date(self::$date_format),
'%level%' => strtoupper(substr(self::$levels[$level], 0, 4)),
'%body%' => $message,
'%level_short%' => strtoupper(substr(self::$levels[$level], 0, 1)),
];
$output = str_replace(array_keys($log_replace), array_values($log_replace), self::$format);
$output = str_replace(
['%date%', '%level%', '%body%', '%caller%'],
[
date(self::$date_format),
strtoupper(substr(self::$levels[$level], 0, 4)),
$message,
$this->getCaller(),
],
self::$format
);
$output = $this->interpolate($output, array_merge($this->static_context, $context));
foreach ($this->log_callbacks as $callback) {
@@ -232,7 +256,7 @@ class ConsoleLogger extends AbstractLogger
if ($this->decorated) {
$output = $this->colorize($output, $level) . PHP_EOL;
} else {
$output = $output . PHP_EOL;
$output .= PHP_EOL;
}
// use stream
if ($this->stream) {
@@ -315,4 +339,23 @@ class ConsoleLogger extends AbstractLogger
return strtr($message, $replace);
}
/**
* 获取调用者信息
*/
private function getCaller(): string
{
$trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
$caller = $trace[1] ?? [];
$file = $caller['file'] ?? '';
if ($file) {
// 截取路径,获取 src 之后至多两级目录
$path = substr($file, strpos($file, 'src') + 4);
$path = explode(DIRECTORY_SEPARATOR, $path);
$path = array_slice($path, 0, 2);
} else {
$path = ['unknown'];
}
return implode(' > ', $path);
}
}

View File

@@ -237,12 +237,7 @@ class TablePrinter
}
} else {
$size = exec('stty size 2>/dev/null');
// in case stty is not available
if (empty($size)) {
$size = 0;
} else {
$size = (int) explode(' ', trim($size))[1];
}
$size = (int) explode(' ', trim($size))[1];
}
if (empty($size)) {
return $this->terminal_size = 79;