2012-10-27 79 views
7

我正在寫一個PHP日誌文件類,但我想爲寫入該文件的行添加顏色。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); 
    } 
} 
+2

你應該添加結束色標序列。例如:'sprintf(「\ 033 [33m%s \ 033 [0m」,$ text)' –

+0

謝謝:) alotttttt – meWantToLearn

+0

@ catalin.costache將其作爲答案plz,因此我可以標記它 – meWantToLearn

回答

12

您應該添加一個結束顏色標記序列。例如: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)

+0

嘿@ catalin.costache我有一個[類似的問題](http://stackoverflow.com/questions/23429683/changing-color -and-輸出的-毫安 - PHP-錯誤登錄在最終端)。想想你可以檢查出來嗎? –