gpt4 book ai didi

PHP 日志文件颜色

转载 作者:IT王子 更新时间:2023-10-29 00:23:58 25 4
gpt4 key购买 nike

我正在编写一个 PHP 日志文件类,但我想为写入文件的行添加颜色。

我遇到的问题是颜色也会改变终端的颜色,我想要实现的是只改变写入日志文件的行的颜色。

class logClass extends Singleton {

private function checkDate() {
return date("onSj");
}

public function logNotice($str) {
$this->write($str, "\033[33m");
}

public function write($string, $color) {
$fileName = $this->checkDate();
$handle = fopen('error.log', 'a');
fwrite($handle, "$color" . date("Y-m-d H:i:s") . $string . "\n");
fclose($handle);
}
}

最佳答案

您应该添加一个结束颜色标记序列。例如:sprintf("\033[33m%s\033[0m", $text)

这是从 https://github.com/kevinlebrun/colors.php 中提取的颜色代码列表

$colorFormats = array(
// styles
// italic and blink may not work depending of your terminal
'bold' => "\033[1m%s\033[0m",
'dark' => "\033[2m%s\033[0m",
'italic' => "\033[3m%s\033[0m",
'underline' => "\033[4m%s\033[0m",
'blink' => "\033[5m%s\033[0m",
'reverse' => "\033[7m%s\033[0m",
'concealed' => "\033[8m%s\033[0m",
// foreground colors
'black' => "\033[30m%s\033[0m",
'red' => "\033[31m%s\033[0m",
'green' => "\033[32m%s\033[0m",
'yellow' => "\033[33m%s\033[0m",
'blue' => "\033[34m%s\033[0m",
'magenta' => "\033[35m%s\033[0m",
'cyan' => "\033[36m%s\033[0m",
'white' => "\033[37m%s\033[0m",
// background colors
'bg_black' => "\033[40m%s\033[0m",
'bg_red' => "\033[41m%s\033[0m",
'bg_green' => "\033[42m%s\033[0m",
'bg_yellow' => "\033[43m%s\033[0m",
'bg_blue' => "\033[44m%s\033[0m",
'bg_magenta' => "\033[45m%s\033[0m",
'bg_cyan' => "\033[46m%s\033[0m",
'bg_white' => "\033[47m%s\033[0m",
);

示例用法:

sprintf($colorFormats['green'], $someText)

关于PHP 日志文件颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13101302/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com