Python Forum
Application logging best practices
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Application logging best practices
#1
I'm newbie in Python development.
I was reading several logging tutorials. For example, in "Medium" you have this guide:
A Step-by-Step Guide to Configuring Python Logging with YAML Files
It suggests to load configuration file in order to log a message, this way:
import logging.config import yaml # Load the config file with open('logging_config.yaml', 'rt') as f: config = yaml.safe_load(f.read()) # Configure the logging module with the config file logging.config.dictConfig(config) # Get a logger object logger = logging.getLogger('development') # Log some messages logger.debug('This is a debug message')
But, when I have an application with several modules, I have to repeat this code in every module that need to log.
Are there any way to avoid this boilerplate?
Is there a solution in the standard library for this issue?

Thank you, in advance.
--
Adrián E. Córdoba
Reply
#2
Use logurur it has no or minimal boilerplate setup.
Example.
import time from loguru import logger logger.add("loop.log", rotation="1 week") start = logger.info('Start of loop') targets = ["a", "b", "c"] for target in targets: time.sleep(5) logger.debug(f"Log file: {target}") end = logger.info('End of loop')
Output:
2025-11-02 09:50:58.219 | INFO | __main__:<module>:5 - Start of loop 2025-11-02 09:51:03.221 | DEBUG | __main__:<module>:9 - Log file: a 2025-11-02 09:51:08.222 | DEBUG | __main__:<module>:9 - Log file: b 2025-11-02 09:51:13.223 | DEBUG | __main__:<module>:9 - Log file: c 2025-11-02 09:51:13.224 | INFO | __main__:<module>:10 - End of loop
For a application if build like a package can have the minimal setup in __init__.py at top level.
app/__init__.py:
from loguru import logger import sys # Only info to file logger.remove() logger.add("logs/app.log", rotation="10 MB")

Then your modules just log;
app/module_a.py:
from loguru import logger def run(): logger.debug("A says hi") 

app/module_b.py:
from loguru import logger def run(): logger.info("B reporting")
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Applications config files / Best practices aecordoba 2 4,857 Oct-23-2024, 12:56 PM
Last Post: aecordoba
  Good practices with Python if Pedroski55 1 2,120 Nov-07-2021, 07:48 AM
Last Post: Gribouillis
  How to send data from a python application to an external application aditya_rajiv 1 3,517 Jul-26-2021, 06:00 AM
Last Post: ndc85430

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020
This forum uses Lukasz Tkacz MyBB addons.
Forum use Krzysztof "Supryk" Supryczynski addons.