Home » Php » newline in error_log in php

newline in error_log in php

Posted by: admin April 23, 2020 Leave a comment

Questions:

How to insert a newline while using error_log() in php

I tried to use <br> and \n but those didn’t work.

How to&Answers:

Use double quotes when putting the error message:

error_log("This is a two lined message. \nThis is line two.");

should work.

error_log('This is a one lined message. \nThis is the same line still.');

will not work: notice the single quotes.

Answer:

As mentioned before, you can use either PHP_EOL or use double quotes in order to output a newline to your log file.

Anyway, when using linux console in order to debug the application, the tail command will show the new line as \\\\n.

Simple solution is to use sed in order to replace \\\\n with \\n:

tail -f file | sed 's/\n/\n/g'

See this answer:
https://serverfault.com/a/126409

Answer:

PHP_EOL manage newlines on multiple platforms:

error_log("Error message".PHP_EOL, 3, 'error.log');

Answer:

I occasionally run into this problem, but certain PHP interpreters don’t always play fair with \n on their own. My ugly solution requires adding the raw ASCII code for newline, \10, seems to do the trick. So try \n\10:

error_log("\n\n".$this->db->last_query()."\n\n");

It’s miserable looking code, so you might want to wrap this into your own function… but it makes the error log look a lot better if you want something to stand out.

I also have no clue why this works better… don’t care enough to find out, but if someone knows why, it’d be cool to hear.

Answer:

When debugging, if you want to make your Error Log line stand out while you’re watching the log ‘tail -f’, I use a little function like this to make the line stand out and easily readable.

Just throw in some white space, and a common term like ‘CUSTOM_LOG’ for later grepping purposes.

highlight_error_log('Msg here');

function highlight_error_log($str){
    error_log('CUSTOM_LOG:            ' . $str . '            ');
}

Answer:

If your error log path is undefined in both your php.ini file and your function call, then \n and \r\n won’t work, even when double quoted (they’ll show up as literal characters instead).

You can fix that by either specifying a location in php.ini:

error_log = /var/log/php-errors.log

or in each PHP function call like this:

error_log("error message", 3, $logFileLocation);

Answer:

This is the correct answer PHP_EOL manage newlines on multiple platforms :

error_log("Error message".PHP_EOL, 3, 'error.log');

https://blog.zohear.com/