alexlcdee/colorcli

带有彩色高亮级别的控制台日志记录器

dev-master 2017-04-26 11:30 UTC

This package is auto-updated.

Last update: 2024-09-23 18:08:53 UTC


README

PHP 库,用于渲染彩色 CLI 消息。

用法

安装

composer require alexlcdee/colorcli

日志记录器

日志记录器类是一个 PSR-3 兼容的日志记录器。提供彩色日志级别标签。

可以通过

setBGColor($level, BackgroundColors $bgcolor = null)

setFGColor($level, ForegroundColors $fgcolor = null)

默认情况下,日志记录器将错误类似消息传递到 STDERR,将信息类似消息传递到 STDOUT。此行为也可以通过以下方式自定义

setOutputStream($level, resource $stream)

日志记录器支持上下文参数和消息中的占位符。

$logger->debug('Debug output from {fileName}:{line}', [
    'fileName' => __FILE__, 
    'line' => __LINE__
]);

上下文键 'exception' 接受 Exception 实例,并在记录消息后立即渲染异常名称、文件名、行和堆栈跟踪。

// catch an exception and pass it to log as context param
try {
    // your code here
} catch (Exception $e) {
    $logger->alert("I've caught an exception", ['exception' => $e]);
}

包含换行的消息将用长度等于级别标签的空字符串填充。

用法

require_once dirname(__DIR__) . '/vendor/autoload.php';

$logger = new \ColorCLI\Logger();

$logger->emergency('System is unusable.');
$logger->alert('Action must be taken immediately.');
$logger->critical('Critical conditions.');
$logger->error('Runtime errors that do not require immediate action but should typically');
$logger->warning('Exceptional occurrences that are not errors.');
$logger->notice('Normal but significant events.');
$logger->info('Interesting events.');
$logger->debug('Detailed debug information.');

$logger->debug('Contextual debug output from {fileName}:{line}', [
    'fileName' => __FILE__,
    'line' => __LINE__
]);

$logger->info("Processing
multiline message");

try {
    (new Throwing())->throwException();
} catch (Exception $e) {
    $logger->alert('Caught an exception!', ['exception' => $e]);
}

上面的示例提供了以下输出: 输出示例

ColorHelper

提供静态方法来着色输入字符串

用法

// Print string with red font on yellow background
echo ColorHelper::colorString('I am a RED string on YELLOW background', ForegroundColors::RED(), BackgroundColors::YELLOW());
echo PHP_EOL;

上面的示例提供了以下输出: 输出示例

背景色和前景色

这些类仅仅是 MyCLabs\Enum\Enum 类,并提供支持的颜色列表。有关 MyCLabs\Enum 的更多信息,请参阅 MyCLabs\Enum

致谢

ColorHelper 的想法来自文章 PHP CLI Colors – PHP Class Command Line Colors (bash)