{
    "href": "/post/2017/04/04/command-line-output-consider-logging-over-streams/",
    "relId": "2017/04/04/command-line-output-consider-logging-over-streams",
    "title": "Command-Line Output: Consider Logging Over Streams",
    "author": "pmjones",
    "markup": "html",
    "tags": [
        {
            "href": "/tag/php/",
            "relId": "php",
            "title": "PHP",
            "author": null,
            "created": null,
            "updated": [],
            "markup": "markdown"
        },
        {
            "href": "/tag/producer/",
            "relId": "producer",
            "title": "Producer",
            "author": null,
            "created": null,
            "updated": [],
            "markup": "markdown"
        },
        {
            "href": "/tag/programming/",
            "relId": "programming",
            "title": "Programming",
            "author": null,
            "created": null,
            "updated": [],
            "markup": "markdown"
        }
    ],
    "created": "2017-04-04 14:39:55 UTC",
    "updated": [
        "2017-04-04 14:39:55 UTC"
    ],
    "html": "<p>When writing command-line applications for PHP, consider using a logger for screen output. This is something I've done with great success in several projects. <a href=\"http://getproducer.org\">Producer</a>, for example, uses a very light <a href=\"https://github.com/producerphp/producer.producer/blob/2.x/src/Stdlog.php\">standard I/O logger</a> class that writes output to <code>STDOUT</code> and <code>STDERR</code> resource/stream handles. Every command that generates output uses that standard I/O logger (cf. <a href=\"https://github.com/producerphp/producer.producer/blob/2.x/src/Command/Issues.php\">the <code>issues</code> command</a>).</p>\n<p>This has a couple of advantages:</p>\n<ul>\n<li>\n<p>Your command-line code gets stdout/stderr output separation practically for free, using a common <a href=\"http://www.php-fig.org/psr/psr-3/\">PSR-3</a> interface.</p>\n</li>\n<li>\n<p>If you incorporate that command-line tool into another class, you can easily inject a different PSR-3 logger so that output is captured elsewhere, instead of writing to stdout/stderr. Among other things, that makes it relatively easy to <a href=\"https://github.com/producerphp/producer.producer/blob/2.x/tests/StdlogTest.php\">test the output</a> of your command-line code without having to use output buffering.</p>\n</li>\n</ul>\n<p>I think this approach works best for non-interactive commands. If you have to read keyboard input from the user as part of the command, using a logger for output might not make a lot of sense. But if all of the command inputs are handled as options or flags, using a logger for output can be great.</p>\n<p class=\"reddit-links\">Read the Reddit discussion about this post <a href=\"https://www.reddit.com/r/PHP/comments/63ei45/commandline_output_consider_logging_over_streams/\">here</a>.</p>\n"
}
