'how to redirct logs to files or suppress printing log to console screen when the log operationed in another code file

pythonHelper.py:

import logging
log = logging.getLogger(__name__)
class PythonHelper():
    def __init__(self):
        log.info("message1")
        pass
    def func(self):
        log.info("message2")
        pass
    def main(self):
        self.func()

runner.py:

from pythonHelper import PythonHelper
class Runner(PythonHelper):
    pass

if __name__ == "__main__":
    a = Runner()
    a.main()
    # do something on a:
    # which would print "message1" and "message2" 
    # to console screen and store them into files.

I cannot do any change in pythonHelper.py file. But I would like to suppress printing logs on console screen because printing is slow... How could I implement it? I only have a silly method using "command > output.txt" but I expect a method that change or add something in my runner code.



Solution 1:[1]

If I got your point you can add the file handler:

import logging
from pythonHelper import PythonHelper

logging.getLogger().setLevel(logging.DEBUG) # Set this level for demo only
fh = logging.FileHandler('output.log') # here the handler
logging.getLogger().addHandler(fh)   # added to the logging

class Runner(PythonHelper):
    def new_func(self):
        pass

if __name__ == "__main__":
    a = Runner()
    a.func()

you can read more here using-logging-in-multiple-modules

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Brown Bear