Command-Line Output: Consider Logging Over Streams

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. Producer, for example, uses a very light standard I/O logger class that writes output to STDOUT and STDERR resource/stream handles. Every command that generates output uses that standard I/O logger (cf. the issues command).

This has a couple of advantages:

  • Your command-line code gets stdout/stderr output separation practically for free, using a common PSR-3 interface.

  • 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 test the output of your command-line code without having to use output buffering.

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.

Are you stuck with a legacy PHP application? You might like my book because it gives you a step-by-step guide to improving your codebase, all while keeping it running the whole time.
Share This!Share on Google+Share on FacebookTweet about this on TwitterShare on RedditShare on LinkedIn

One thought on “Command-Line Output: Consider Logging Over Streams

  1. Uhm. Except I usually don’t want everything a logger writes in the output to the user (for example date or context) which means I have to customize the loggers format for the occasion.
    Then having the code look like it 8s logging there is bad for the maintainability of the code, as the idea won’t be obvious to other devs. And last but not least even more confusion when having output and logging, which is the most common case

Leave a Reply

Your email address will not be published. Required fields are marked *