Motivation
Handling datetime formatting in logs is crucial for debugging, monitoring, and analyzing application behavior. However, standard Python logging makes datetime handling unnecessarily complex with multiple confusing parameters and formatting options.
Traditional logging requires cumbersome datetime configuration:
import logging
from datetime import datetime
logging.basicConfig(
format="%(asctime)s %(levelname)s: %(message)s",
datefmt="%Y-%m-%d %H:%M:%S",
level=logging.INFO,
)
logging.info("This is a test")
Output:
2025-03-16 15:29:58 INFO: This is a test
This code requires understanding multiple parameters like datefmt
, asctime
, and msecs
, making it difficult to achieve desired datetime formats in logs.
Introduction to Loguru
Loguru is a Python library that simplifies logging with an intuitive interface. It can be installed using pip:
pip install loguru
As covered in Simplify Python Logging with Loguru and Configure Professional Logging in a Single Line, Loguru provides a more straightforward approach to logging. In this post, we’ll focus on its datetime handling capabilities.
Better Datetime Handling
Loguru simplifies datetime formatting in logs with a clean, intuitive syntax. Here’s how to use it:
Basic datetime formatting:
import sys
from loguru import logger
# Remove the default handler and add a custom format
logger.remove()
logger.add(sys.stdout, format="{time:YYYY-MM-DD HH:mm:ss} {level}: {message}")
logger.info("This is a test")
Output:
2025-03-16 15:29:06 INFO: This is a test
The datetime formatting supports:
- Date components:
YYYY
(year),MM
(month),DD
(day) - Time components:
HH
(hour),mm
(minute),ss
(second),SSS
(millisecond) - Custom separators and formats
Advanced Datetime Features
To convert timestamps to UTC, add !UTC
to your time format:
# Add handler with timezone support
logger.remove()
logger.add(sys.stdout, format="{time:dddd DD MMMM YYYY HH:mm:ss!UTC} | {message}")
logger.info("UTC timestamp")
Output:
Sunday 16 March 2025 08:24:05 | UTC timestamp
Conclusion
Loguru’s datetime handling feature significantly simplifies log timestamp formatting, making it more intuitive and powerful than standard Python logging. Its clean syntax and comprehensive formatting options make it an excellent choice for applications requiring precise and flexible datetime logging.