*NIX Output Logging

I was asked today about how to log the output of a command on Linux. It turns out that there are a number of ways of capturing output in *NIX environments. The well known method is to make the shell take care of it, for example, if you use bash you could:


echo "test" &>log.txt

Unfortunately, this does have some limitations. It will capture standard output and standard error, but it won’t (directly) capture any input from the user and it won’t capture anything directly written to the pty by the program. One way to work around this would be to manipulate the pty manually, but that’s a pain. Most *NIX flavors ship with a tool called “script” which will launch a shell and keep track of the output for you. For example you might do the following:


$ script

Script started output file is typescript

$ echo "foo" > /dev/tty

^D

Script done, output file is typescript

After the shell exits, you should get a file called “typescript” which contains a plain text log of everything sent to the terminal. You can also have script record timing data so that the log can be played back (check out the manpage).

Most scripting languages (and, of course, “expect”) can do something similar if you want to filter the output on the fly.

 

One thing to be aware of with this method is that it will probably catch some control characters. If you look at your output in an editor these likely won’t be rendered by their meaning. If you just “cat” the file from a terminal they may very well be displayed. You can always filter any unwanted characters with sed (or similar)