Search code examples
pythonstdoutstderr

Python stderr for imported class


I am trying to pipe the error messages to a file in my python script. I have it working fine for the most part. The problem comes when I import another file, and there is an error in that file. Here is an example (logger.py):

import time
import sys
import test

class Logger(object):
    def __init__(self,outputType):
        self.outputType=outputType;
        self.log = open("serverLog.log", "w")
    def write(self, message):
        self.log = open("serverLog.log", "a")
        self.log.write(message)  
        self.log.close()

sys.stdout = Logger("stdout")
sys.stderr = Logger("stderr")

j=0
while 3<4:
    print "Sdf"
    j=j+1
    if j>4:
        print k
    time.sleep(1)

The above file works fine for logging the output and errors (when test.py is not imported).

Here is the second file that I am importing (test.py) with an intentional error:

import time
time.sleep(1)
print x

When I run logger.py, all of the output and errors go to serverLog.log, except for the error cause by the import of test.py.

I am wondering if it is possible to pipe the error messages from test.py to serverLog.log without adding anything to test.py.


Solution

  • You should define any modules after: sys.stdout = Logger("stdout") sys.stderr = Logger("stderr")

    And result will be: cat serverLog.log

    Traceback (most recent call last):
      File "/root/untitled/x.py", line 16, in <module>
        import test1
      File "/root/untitled/test1.py", line 3, in <module>
        print x
    NameError: name 'x' is not defined
    

    My code:

    import time
    import sys
    
    class Logger(object):
        def __init__(self,outputType):
            self.outputType=outputType;
            self.log = open("serverLog.log", "w")
        def write(self, message):
            self.log = open("serverLog.log", "a")
            self.log.write(message)
            self.log.close()
    
    sys.stdout = Logger("stdout")
    sys.stderr = Logger("stderr")
    
    import test1
    
    j=0
    while 3<4:
        print "Sdf"
        j=j+1
        if j>4:
            print k
        time.sleep(1)