Blogged by Ujihisa. Standard methods of programming and thoughts including Clojure, Vim, LLVM, Haskell, Ruby and Mathematics written by a Japanese programmer. github/ujihisa

Sunday, February 14, 2010

How To Save Both Standard And Error Logs By Some Processes On A Same Log File

Problem

Assuming that you need to save both standard and error logs by two processes on a same file.

$ command1
mesg...
error...
mesg...
....

$ command2
mesg...
mesg...
mesg...
error..
....

How to do that? The following code looks good, but it doesn't work as you want.

$ (command1 >& log.txt) &
$ (command2 >& log.txt) &

You can find only the logs of command2.

How about trying this?

$ (command1 2>&1 >> log.txt) &
$ (command2 2>&1 >> log.txt) &

It is better, but it doesn't work as you want as well. The result is not chronically ordered because of buffering.

Solution

Do the following code:

$ (command1 2>&1 | cat >> log.txt) &
$ (command2 2>&1 | cat >> log.txt) &

It's tricky. The part of | cat >> means not to buffer the outputs.

2 comments:

  1. Interesting. But when I try to capture STDOUT and STDERR I define the output to STDOUT first, then point STDERR to that same stream. I.E.:

    ( command1 >>log.txt 2>&1 ) &
    ( command2 >>log.txt 2>&1 ) &

    this seems to work for me. Does it for you?

    Cheers
    Eric

    ReplyDelete

Followers