at the main script, insert the code below to setup a logger named debug.

# inside ``. and example main script file

debuglogger = logging.getLogger("debug")

debuglogger_fh = logging.FileHandler("debug.log",mode='w')

FORMAT = '%(asctime)-15s %(funcName)-20s > %(message)s'
formatter = logging.Formatter()


debuglogger_sh = logging.StreamHandler(sys.stdout)



# do some main stuff

In the above code, I have set the debug logger to print its text to both sys.stdout(providing the same effect as a normal print) and to a file debug.log. Note that when writing to this external file, I have set the writing mode to w indicating that whenever this logger is setup, it will overwrite if a file named debug.log already exists. If I used the a option as the mode, then it will append to the already existing file with the same name.

Once our debug logger is setup in the main script, then you can fetch this logger from anywhere in your python files(not only the main script file) and push a log message to it.

For example, lets say that in the main script file I have imported a python module(which is identical to a python file) named some_external. If I wanted to print some debug messages in this module, instead of using print, I can do the following:

# this is ``
import logging

debuglogger = logging.getLogger("debug")

def some_func1():
    # do something
    # and I want to print some debug messages


Notice that in this, the code only fetches a logger named debug and doesn’t configure this logger. That is because the configuration(adding handlers, adding formatters, etc.) is meant and will be done in the main sript file. And this totally make sense because file isn’t meant to play a role as a main execution script but rather just a side-module that stores numerous functions. That is why should only utilize a reference to some logger and do not need to care anything about the specific configurations of the logger.


Leave a Reply

Your email address will not be published.