Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to redirect stdout and stderr to logger in Python

I have a logger that has a RotatingFileHandler. I want to redirect all Stdout and Stderr to the logger. How to do so?

like image 691
orenma Avatar asked Oct 17 '13 11:10

orenma


1 Answers

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.

class LoggerWriter:     def __init__(self, level):         # self.level is really like using log.debug(message)         # at least in my case         self.level = level      def write(self, message):         # if statement reduces the amount of newlines that are         # printed to the logger         if message != '\n':             self.level(message)      def flush(self):         # create a flush method so things can be flushed when         # the system wants to. Not sure if simply 'printing'         # sys.stderr is the correct way to do it, but it seemed         # to work properly for me.         self.level(sys.stderr) 

and this would look something like:

log = logging.getLogger('foobar') sys.stdout = LoggerWriter(log.debug) sys.stderr = LoggerWriter(log.warning) 
like image 62
Cameron Gagnon Avatar answered Oct 13 '22 04:10

Cameron Gagnon