[Twisted-Python] Logging to both console and file (using twisted logging API)?

David Bolen db3l.net at gmail.com
Fri Oct 30 14:25:06 MDT 2009


naman jain <namanvit at gmail.com> writes:

> I wanted to log in a file and keep the console also going with it.

I can read this as either:

  * Keep file logs and stdout/console completely separate, or
  * File gets explicit logs and copies of stdout, but stdout also goes to
    console as well.

The latter is something I'd more commonly do, but the former is what
you explain further below with your rules.

> I am using
> log.startLogging(open(logname, 'w'))
>
> whatever documentation I could find about this API, it suggested me to pass
> setStdout=False(in order to keep stdout away from putting into log)
> somewhere in the startlogging function.
>
> Something like this I tried:
> log.startLogging(sys.stdout,setStdout=False)

Why did you switch to sys.stdout here?  While this will prevent
sys.stdout and sys.stderr from being redirected, it will use
sys.stdout for any log.msg() calls, so nothing would end up in your
log file.

> Doesnt help in solving the problem of getting both things:
>
> Requirement:
> log.msg("messageforlog")    -> goes to log
> print "message for console" -> goes to console
>
> Could anyone give some ideas on this?

I think you had the right idea with setStdout, but changed more than
just that when you tested it.  If you use a call like
log.startLogging(open(logname, 'w'), setStdout=False) I believe you'll
get what you want.  Only calls to log.msg() will go to the file, and
stdout/stderr will be left unchanged.

-- David





More information about the Twisted-Python mailing list