mirror of
https://github.com/zhamao-robot/zhamao-logger.git
synced 2026-07-21 15:45:37 +08:00
Compare commits
12 Commits
add-caller
...
fix/recurs
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c4367bef61 | ||
|
|
8a72831c5c | ||
|
|
ac5fa59428 | ||
|
|
26dc5fa8c3 | ||
|
|
e75fa01ca5 | ||
|
|
b28c0c26d5 | ||
|
|
2551b3e1db | ||
|
|
81ab0b98f6 | ||
|
|
1d7427abd8 | ||
|
|
1b7e343493 | ||
|
|
97ee152121 | ||
|
|
11156c65a2 |
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "zhamao/logger",
|
"name": "zhamao/logger",
|
||||||
"description": "Another Console Logger for CLI Applications",
|
"description": "Another Colorful Console Logger for CLI Applications",
|
||||||
"type": "library",
|
"type": "library",
|
||||||
"license": "Apache-2.0",
|
"license": "Apache-2.0",
|
||||||
"autoload": {
|
"autoload": {
|
||||||
@@ -16,7 +16,7 @@
|
|||||||
"authors": [
|
"authors": [
|
||||||
{
|
{
|
||||||
"name": "jerry",
|
"name": "jerry",
|
||||||
"email": "admin@zhamao.me"
|
"email": "github@cwcc.me"
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"name": "sunxyw",
|
"name": "sunxyw",
|
||||||
@@ -25,7 +25,7 @@
|
|||||||
],
|
],
|
||||||
"minimum-stability": "stable",
|
"minimum-stability": "stable",
|
||||||
"require": {
|
"require": {
|
||||||
"php": "^7.2 || ^7.3 || ^7.4 || ^8.0 || ^8.1",
|
"php": "^7.2 || ^7.3 || ^7.4 || ^8.0 || ^8.1 || ^8.2 || ^8.3 || ^8.4 || ^8.5",
|
||||||
"psr/log": "^1 || ^2 || ^3",
|
"psr/log": "^1 || ^2 || ^3",
|
||||||
"symfony/polyfill-mbstring": "^1.0"
|
"symfony/polyfill-mbstring": "^1.0"
|
||||||
},
|
},
|
||||||
@@ -37,9 +37,9 @@
|
|||||||
"ext-mbstring": "Use C/C++ extension instead of polyfill will be more efficient"
|
"ext-mbstring": "Use C/C++ extension instead of polyfill will be more efficient"
|
||||||
},
|
},
|
||||||
"require-dev": {
|
"require-dev": {
|
||||||
"friendsofphp/php-cs-fixer": "^3.2",
|
"friendsofphp/php-cs-fixer": "^3.64",
|
||||||
"phpstan/phpstan": "^1.1",
|
"phpstan/phpstan": "^1.12",
|
||||||
"phpunit/phpunit": "^8.5 || ^9.0",
|
"phpunit/phpunit": "^9.0",
|
||||||
"roave/security-advisories": "dev-latest",
|
"roave/security-advisories": "dev-latest",
|
||||||
"brainmaestro/composer-git-hooks": "^2.8"
|
"brainmaestro/composer-git-hooks": "^2.8"
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -10,14 +10,14 @@ use Psr\Log\LogLevel;
|
|||||||
|
|
||||||
class ConsoleLogger extends AbstractLogger
|
class ConsoleLogger extends AbstractLogger
|
||||||
{
|
{
|
||||||
public const VERSION = '1.1.0';
|
public const VERSION = '1.1.7';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 日志输出格式
|
* 日志输出格式
|
||||||
*
|
*
|
||||||
* @var string
|
* @var string
|
||||||
*/
|
*/
|
||||||
public static $format = '[%date%] [%level%] %caller% %body%';
|
public static $format = '[%date%] [%level%] %body%';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 日志输出日期格式
|
* 日志输出日期格式
|
||||||
@@ -86,6 +86,13 @@ class ConsoleLogger extends AbstractLogger
|
|||||||
*/
|
*/
|
||||||
protected $stream;
|
protected $stream;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 递归保护标志 — 防止日志写入失败时错误处理器再次调用日志导致死循环 CPU 100%
|
||||||
|
*
|
||||||
|
* @var bool
|
||||||
|
*/
|
||||||
|
protected static $in_log = false;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 是否带颜色
|
* 是否带颜色
|
||||||
*
|
*
|
||||||
@@ -93,13 +100,15 @@ class ConsoleLogger extends AbstractLogger
|
|||||||
*/
|
*/
|
||||||
protected $decorated;
|
protected $decorated;
|
||||||
|
|
||||||
|
protected $use_stderr = false;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 创建一个 ConsoleLogger 实例
|
* 创建一个 ConsoleLogger 实例
|
||||||
*
|
*
|
||||||
* @param string $level 日志等级
|
* @param string $level 日志等级
|
||||||
* @param null|resource $stream
|
* @param null|resource $stream
|
||||||
*/
|
*/
|
||||||
public function __construct(string $level = LogLevel::INFO, $stream = null, bool $decorated = true)
|
public function __construct(string $level = LogLevel::INFO, $stream = null, bool $decorated = true, bool $use_stderr = false)
|
||||||
{
|
{
|
||||||
$this->decorated = $decorated;
|
$this->decorated = $decorated;
|
||||||
self::$log_level = $this->castLogLevel($level);
|
self::$log_level = $this->castLogLevel($level);
|
||||||
@@ -113,12 +122,18 @@ class ConsoleLogger extends AbstractLogger
|
|||||||
if (($stat['mode'] & 0170000) === 0100000) { // whether is regular file
|
if (($stat['mode'] & 0170000) === 0100000) { // whether is regular file
|
||||||
$this->decorated = false;
|
$this->decorated = false;
|
||||||
} else {
|
} else {
|
||||||
$this->decorated =
|
$this->decorated
|
||||||
PHP_OS_FAMILY !== 'Windows' // linux or unix
|
= PHP_OS_FAMILY !== 'Windows' // linux or unix
|
||||||
&& function_exists('posix_isatty')
|
&& function_exists('posix_isatty')
|
||||||
&& posix_isatty($stream); // whether is interactive terminal
|
&& posix_isatty($stream); // whether is interactive terminal
|
||||||
}
|
}
|
||||||
$this->stream = $stream;
|
$this->stream = $stream;
|
||||||
|
$this->use_stderr = $use_stderr;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function setLevel(string $level): void
|
||||||
|
{
|
||||||
|
self::$log_level = $this->castLogLevel($level);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -139,27 +154,6 @@ class ConsoleLogger extends AbstractLogger
|
|||||||
return self::VERSION;
|
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;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 添加静态上下文
|
* 添加静态上下文
|
||||||
*/
|
*/
|
||||||
@@ -183,7 +177,7 @@ class ConsoleLogger extends AbstractLogger
|
|||||||
{
|
{
|
||||||
$log = 'Stack trace:' . PHP_EOL;
|
$log = 'Stack trace:' . PHP_EOL;
|
||||||
$trace = debug_backtrace();
|
$trace = debug_backtrace();
|
||||||
//array_shift($trace);
|
// array_shift($trace);
|
||||||
foreach ($trace as $i => $t) {
|
foreach ($trace as $i => $t) {
|
||||||
if (!isset($t['file'])) {
|
if (!isset($t['file'])) {
|
||||||
$t['file'] = 'unknown';
|
$t['file'] = 'unknown';
|
||||||
@@ -192,6 +186,7 @@ class ConsoleLogger extends AbstractLogger
|
|||||||
$t['line'] = 0;
|
$t['line'] = 0;
|
||||||
}
|
}
|
||||||
$log .= "#{$i} {$t['file']}({$t['line']}): ";
|
$log .= "#{$i} {$t['file']}({$t['line']}): ";
|
||||||
|
/* @phpstan-ignore-next-line */
|
||||||
if (isset($t['object']) && is_object($t['object'])) {
|
if (isset($t['object']) && is_object($t['object'])) {
|
||||||
$log .= get_class($t['object']) . '->';
|
$log .= get_class($t['object']) . '->';
|
||||||
}
|
}
|
||||||
@@ -224,60 +219,75 @@ class ConsoleLogger extends AbstractLogger
|
|||||||
return ConsoleColor::apply($styles, $string)->__toString();
|
return ConsoleColor::apply($styles, $string)->__toString();
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* {@inheritDoc}
|
|
||||||
*/
|
|
||||||
public function log($level, $message, array $context = []): void
|
public function log($level, $message, array $context = []): void
|
||||||
{
|
{
|
||||||
$level = $this->castLogLevel($level);
|
$level = $this->castLogLevel($level);
|
||||||
|
|
||||||
|
$log_replace = [
|
||||||
|
'%date%' => date(self::$date_format),
|
||||||
|
'%level_long%' => strtoupper(self::$levels[$level]),
|
||||||
|
'%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 = $this->interpolate($output, array_merge($this->static_context, $context));
|
||||||
|
|
||||||
|
foreach ($this->log_callbacks as $callback) {
|
||||||
|
if ($callback($level, $output, $message, $context, $this->shouldLog($level)) === false) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if (!$this->shouldLog($level)) {
|
if (!$this->shouldLog($level)) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
$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) {
|
|
||||||
if ($callback($level, $output, $message, $context) === false) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if ($this->decorated) {
|
if ($this->decorated) {
|
||||||
$output = $this->colorize($output, $level) . PHP_EOL;
|
$output = $this->colorize($output, $level) . PHP_EOL;
|
||||||
} else {
|
} else {
|
||||||
$output .= PHP_EOL;
|
$output = $output . PHP_EOL;
|
||||||
}
|
}
|
||||||
// use stream
|
// 递归保护:如果上一次日志写入触发了错误(如终端关闭后 STDOUT/STDERR 破损),
|
||||||
if ($this->stream) {
|
// 跳过本次输出,防止错误处理器递归调用导致 CPU 100% 空耗
|
||||||
fwrite($this->stream, $output);
|
if (self::$in_log) {
|
||||||
fflush($this->stream);
|
return;
|
||||||
} else {
|
|
||||||
// use plain text output
|
|
||||||
echo $output;
|
|
||||||
}
|
}
|
||||||
|
self::$in_log = true;
|
||||||
|
try {
|
||||||
|
// use stream
|
||||||
|
if ($this->stream) {
|
||||||
|
@fwrite($this->stream, $output);
|
||||||
|
@fflush($this->stream);
|
||||||
|
} else {
|
||||||
|
if ($level <= 4 && $this->use_stderr) {
|
||||||
|
@fwrite(STDERR, $output);
|
||||||
|
} else {
|
||||||
|
// use plain text output
|
||||||
|
@echo $output;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
self::$in_log = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public function setDecorated(bool $decorated): void
|
||||||
|
{
|
||||||
|
$this->decorated = $decorated;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 转换日志等级
|
* 转换日志等级
|
||||||
*/
|
*/
|
||||||
private function castLogLevel(string $level): int
|
protected function castLogLevel(string $level): int
|
||||||
{
|
{
|
||||||
if (in_array($level, self::$levels, true)) {
|
if (in_array($level, self::$levels, true)) {
|
||||||
return array_flip(self::$levels)[$level];
|
return array_flip(self::$levels)[$level];
|
||||||
}
|
}
|
||||||
|
|
||||||
throw new InvalidArgumentException('无效的日志等级');
|
throw new InvalidArgumentException('Invalid log level: ' . $level);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -285,7 +295,7 @@ class ConsoleLogger extends AbstractLogger
|
|||||||
*
|
*
|
||||||
* @param mixed $item 日志内容
|
* @param mixed $item 日志内容
|
||||||
*/
|
*/
|
||||||
private function stringify($item): string
|
protected function stringify($item): string
|
||||||
{
|
{
|
||||||
switch (true) {
|
switch (true) {
|
||||||
case is_callable($item):
|
case is_callable($item):
|
||||||
@@ -319,7 +329,7 @@ class ConsoleLogger extends AbstractLogger
|
|||||||
/**
|
/**
|
||||||
* 判断是否应该记录该等级日志
|
* 判断是否应该记录该等级日志
|
||||||
*/
|
*/
|
||||||
private function shouldLog(int $level): bool
|
protected function shouldLog(int $level): bool
|
||||||
{
|
{
|
||||||
return $level <= self::$log_level;
|
return $level <= self::$log_level;
|
||||||
}
|
}
|
||||||
@@ -330,7 +340,7 @@ class ConsoleLogger extends AbstractLogger
|
|||||||
* @param string $message 日志内容
|
* @param string $message 日志内容
|
||||||
* @param array $context 变量列表
|
* @param array $context 变量列表
|
||||||
*/
|
*/
|
||||||
private function interpolate(string $message, array $context = []): string
|
protected function interpolate(string $message, array $context = []): string
|
||||||
{
|
{
|
||||||
$replace = [];
|
$replace = [];
|
||||||
foreach ($context as $key => $value) {
|
foreach ($context as $key => $value) {
|
||||||
@@ -339,23 +349,4 @@ class ConsoleLogger extends AbstractLogger
|
|||||||
|
|
||||||
return strtr($message, $replace);
|
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);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -137,8 +137,8 @@ class TablePrinter
|
|||||||
$line_data[$current_line] = [
|
$line_data[$current_line] = [
|
||||||
'used' => $valid_width - $k_len - 2 - $partial_v_len,
|
'used' => $valid_width - $k_len - 2 - $partial_v_len,
|
||||||
'can_put_second' => false,
|
'can_put_second' => false,
|
||||||
'lines' => $k . ': ' .
|
'lines' => $k . ': '
|
||||||
ConsoleColor::apply([$this->value_color], $partial_v . str_pad('', $valid_width - $k_len - 2 - $partial_v_len, '.')),
|
. ConsoleColor::apply([$this->value_color], $partial_v . str_pad('', $valid_width - $k_len - 2 - $partial_v_len, '.')),
|
||||||
];
|
];
|
||||||
++$current_line;
|
++$current_line;
|
||||||
// 下一个参数
|
// 下一个参数
|
||||||
@@ -237,7 +237,12 @@ class TablePrinter
|
|||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
$size = exec('stty size 2>/dev/null');
|
$size = exec('stty size 2>/dev/null');
|
||||||
$size = (int) explode(' ', trim($size))[1];
|
// in case stty is not available
|
||||||
|
if (empty($size)) {
|
||||||
|
$size = 0;
|
||||||
|
} else {
|
||||||
|
$size = (int) explode(' ', trim($size))[1];
|
||||||
|
}
|
||||||
}
|
}
|
||||||
if (empty($size)) {
|
if (empty($size)) {
|
||||||
return $this->terminal_size = 79;
|
return $this->terminal_size = 79;
|
||||||
|
|||||||
Reference in New Issue
Block a user