2

How to redefine stderr out and stdout out to separately logs files using logging module ? For example stderr.log and stdout.log files ?

Bdfy
  • 23,141
  • 55
  • 131
  • 179
  • do you want to redirect `sys.stdout`, `sys.stderr` to files or do you want message produced with an aid of `logging` module to go to files? – jfs Feb 03 '12 at 15:54

2 Answers2

8

You can simply replace sys.stdout and sys.stderr with custom file-like objects:

import sys

sys.stdout = open('stdout.log', 'a')
sys.stderr = open('stderr.log', 'a')

To undo:

sys.stdout = sys.__stdout__
sys.stderr = sys.__stderr__

For more information, read the sys module documentation.

Ferdinand Beyer
  • 64,979
  • 15
  • 154
  • 145
1
import sys


class OutDevice():
    def write(self, s):
        # do whatever
        pass

class ErrDevice():
    def write(self, s):
        # do whatever
        pass

sys.stdout = OutDevice()  
sys.stdout = ErrDevice()  

# to restore
sys.stdout = sys.__stdout__ 
sys.stderr = sys.__stderr__ 
Sid
  • 7,511
  • 2
  • 28
  • 41