Spinor8
Spinor8

Reputation: 1607

Logging in a Python project with multiple points of entry

In a multi-module Python environment, the docs recommend that one run the following snippet in the first point of entry into the Python project to define project-wide logging.

# ABC.py
import logging

logging.basicConfig(filename='master.log', level=logging.INFO)
logging.info('Start Logging.')

If some other file is another potential first point of entry into the project, do I add the same snippet to the top of that file as well? What I am trying to achieve is to specify logging in a single central location regardless of which file is the first point of entry.

Upvotes: 4

Views: 2270

Answers (2)

Łukasz Rogalski
Łukasz Rogalski

Reputation: 23203

Common approach would be to use module-level loggers.

In your "main" configure logging:

import logging

logging.basicConfig(filename='master.log', level=logging.INFO)
main()

In every module use module-level loggers. Each log created that way will use common config:

import logging
# my.module.name is arbitrary string and logger identifier, usually it's each module name
logger = logging.getLogger("my.module.name")
logger.info("info msg")

Upvotes: 1

tobias_k
tobias_k

Reputation: 82899

You could create a dedicated python script file just for setting up the logging. Basically, that file would contain exactly what your ABC.py file contains now.

Then just import this file in every script that's a potential "entry point". Even if the file is imported twice, the code in the file will be run exactly once.

Upvotes: 5

Related Questions