douwen7603 2016-11-10 17:30
浏览 68
已采纳

像在Python中一样将PHP命令行日志写入文件

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.

  • 写回答

1条回答 默认 最新

  • dongou4052 2016-11-10 18:13
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?