Redirecting stderr and stdout to syslog

Lincoln Yeoh lyeoh at pop.jaring.my
Wed Aug 6 03:44:04 CEST 2008


At 03:29 AM 8/6/2008, Matthew Woodcraft wrote:
>In article <mailman.1134.1217944475.922.python-list at python.org>,
>
> > How do I redirect ALL stderr stuff to syslog, even stderr from
> > external programs that don't explicitly change their own stderr?
>
>Sending messages to syslog involves more than writing to a file
>descriptor, so there's no way to make this happen without having some
>process read the external programs' output and send it to syslog (which
>is basically the 'logger' method that you said you didn't like).

I actually don't mind resorting to logger,  I just don't want to wrap 
the python program in a shell script.

Anyway the following appears to work, not sure if there are any 
gotchas (I'm new to this).

(a,b)=popen2.popen2('/bin/logger -t "test[%u]: STDERR"' % os.getpid())
os.dup2(b.fileno(),sys.stderr.fileno())
(a,b1)=popen2.popen2('/bin/logger -t "test[%u]: STDOUT"' % os.getpid())
os.dup2(b1.fileno(),sys.stdout.fileno())

It seems subprocess is to be preferred over popen2. subprocess is 
more verbose for this.

With perl I normally do (close your eyes if you are allergic to perl :) ):

open(STDERR,"|/bin/logger -t \"${PROGNAME}[$$]: STDERR\"") or die 
"Error: Unable to redirect STDERR to logger!";
open(STDOUT,"|/bin/logger -t \"${PROGNAME}[$$]: STDOUT\"") or die 
"Error: Unable to redirect STDOUT to logger!";

>You'd do that with something like this (untested):
>
>     STDERR = 2
>     se = os.open("breakage.log", os.O_WRONLY|os.O_APPEND)
>     os.dup2(se, STDERR)
>     os.close(se)
>
>You can also use this breakage log for errors from your own program, if
>there are any cases where you think things might be too messed up for
>you to want to rely on your normal logging routines.

I've seen that but rejected it because it will not provide 
timestamps, and the logs end up in different places - some to syslog 
and some to this file.

Having the logs go to the same place also gives a hint on the order 
of events - it's not 100% in order of course, but usually good 
enough, and much better than not even knowing what hour each line occurred.

Regards,
Link.




More information about the Python-list mailing list