1

I want to create a Python logging object in my main program and have logging in both my main program and in the modules it uses at the same logging level. The basic example given in logging documentation is essentially as follows:

main.py:

import logging
import mylib

def main():
    logging.basicConfig(level = logging.INFO)
    logging.info('Started')
    mylib.do_something()
    logging.info('Finished')

if __name__ == '__main__':
    main()

mylib.py:

import logging

def do_something():
    logging.info('Doing something')

This works fine. I am not sure, however, of how to get a Python logging object doing something similar. The following, for example, does not work:

main.py:

import logging
import mylib

def main():
    verbose = True
    global log
    log = logging.getLogger(__name__)
    if verbose:
        log.setLevel(logging.INFO)
    else:
        log.setLevel(logging.DEBUG)
    log.info('Started')
    mylib.do_something()
    log.info('Finished')

if __name__ == '__main__':
    main()

mylib.py:

import logging

def do_something():
    log.info('Doing something')

It does not work because the global log object is not recognised in the mylib.py module. How should I be doing this? My two main goals are

  • to have the logging level that is set in my main program propagate through to any modules used and
  • to be able to use log for logging, not "logging" (i.e. log.info("alert") as opposed to logging.info("alert")).
1

2 Answers 2

3

Your application should configure the logging once (with basicConfig or see logging.config) and then in each file you can have:

import logging

log = logging.getLogger(__name__)

# further down:

log.info("alert")

So you use a logger everywhere and you don't directly access the logging module in your codebase. This allows you to configure all your loggers in your logging configuration (which, as said earlier, is configured once and loaded at the beginning of your application).

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks very much for your help and for the detail on the logging configuration.
why do want to have an object from which we log? It seems like (a bit) more work to setup log = logging.getLogger(__name__) for each file? Why cant we just use logging.info() etc for each module (assuming we have setup the logging using basicconfig)
1

You can use a different logger in each module as follows:

import logging
LOG = logging.getLogger(__name__)

# Stuff
LOG.info("A log message")

1 Comment

Thanks for your help. You've got a solution similar to that of Simeon Visser, who's added a little explanatory detail.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.