I have a logger that has a RotatingFileHandler
.
I want to redirect all Stdout
and Stderr
to the logger.
How to do so?
相关问题
- how to define constructor for Python's new Nam
- streaming md5sum of contents of a large remote tar
- How to get the background from multiple images by
- Django __str__ returned non-string (type NoneType)
- Evil ctypes hack in python
If it's an all-Python system (i.e. no C libraries writing to fds directly, as Ignacio Vazquez-Abrams asked about) then you might be able to use an approach as suggested here:
and then set
sys.stdout
andsys.stderr
toLoggerWriter
instances.All of the prior answers seem to have problems adding extra newlines where they aren't needed. The solution that works best for me is from http://www.electricmonk.nl/log/2011/08/14/redirect-stdout-and-stderr-to-a-logger-in-python/, where he demonstrates how send both stdout and stderr to the logger:
The output looks like:
Note that self.linebuf = '' is where the flush is being handled, rather than implementing a flush function.
As an evolution to Cameron Gagnon's response, I've improved the
LoggerWriter
class to:now uncontrolled exceptions look nicer:
Not enough rep to comment, but I wanted to add the version of this that worked for me in case others are in a similar situation.
and this would look something like:
With flush added to Vinay Sajip's answer:
You can use redirect_stdout context manager:
or like this