In Python, we can put the command line
log to file instead of the console
using this command:
python script.py >> mylogfile.txt
How can I do it using PHP? I've tried
php script.php >> mylogfile.txt
but it doesn't work.
Just FYI, it might helps, I use Windows 10.
Finally found the answer. It's based on this article: https://www.sitepoint.com/php-command-line-1-2/
I first used php script.php > mylog.txt
which returns some of the log text to the console, so I thought it's not writing to the log, but it does. What I wanted is php script.php > mylog.txt 2>&1
which will put any log to the file.
The article says it doesn't work in Windows, but I use Windows 10 and it works.
The error messages are mixed with the normal output as before. But by piping the output from the script, I can split the errors from the normal output:
$ php outwitherrors.php 2> errors.log
This time, you’ll only see these messages:
Opening file foobar.log Job finished
But, if you look into the directory in which you ran the script, a new file called errors.log will have been created, containing the error message. The number 2 is the command line handle used to identify STDERR. Note that 1 is handle for STDOUT, while 0 is the handle for STDERR. Using the >
symbol from the command line, you can direct output to a particular location.
Although this may not seem very exciting, it’s a very handy tool for system administration. A simple application, running some script from cron, would be the following:
$ php outwitherrors.php >> transaction.log 2>> errors.log
Using ‘>>‘, I tell the terminal to append new messages to the existing log (rather than overwrite it). The normal operational messages are now logged to transaction.log, which I might peruse once a month, just to check that everything’s OK. Meanwhile, any errors that need a quicker response end up in errors.log, which some other cron job might email me on a daily basis (or more frequently) as required.
There’s one difference between the UNIX and Windows command lines, when it comes to piping output, of which you should be aware. On UNIX, you can merge the STDOUT and STDERR streams to a single destination, for example:
$ php outwitherrors.php > everything.log 2>&1
What this does is re-route the STDERR to STDOUT, meaning that both get written to the log file everything.log.