Home » Php » linux – PHP log file color

linux – PHP log file color

Posted by: admin July 12, 2020 Leave a comment

Questions:

I’m writing a PHP log file class but I want to add color to the line that is written to the file.

The issue I’m having is the color changes the color of the terminal as well, what I want to achieve is to change color of line written to the log file only.

class logClass extends Singleton {

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

    public function logNotice($str) {
        $this->write($str, "3[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);
    }
}
How to&Answers:

You should add an end color mark sequence. Eg: sprintf("\033[33m%s\033[0m", $text)

Here is a list of color codes taken from https://github.com/kevinlebrun/colors.php

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

Example usage:

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