The -8s in the formatter is a field formatting specification that means:
- = left-align the text
8 = use at least 8 characters of width
s = format as a string
It ensures that log levels like "INFO" (4 chars) and "WARNING" (7 chars) will always occupy the same width, making your logs more visually aligned:
code
2023-06-04 12:34:56 | INFO | my_app | Program started
2023-06-04 12:34:57 | WARNING | my_app | Configuration file missing
2023-06-04 12:34:58 | ERROR | my_app | Database connection failed
Without the formatting, the vertical alignment would be inconsistent after each log level.
Adding UTC Timestamps and UTF-8 Encoding
python
import logging
import sys
from datetime import datetime, timezone
class UTCFormatter(logging.Formatter):
"""Formatter that ensures timestamps are in UTC"""
def formatTime(self, record, datefmt=None):
# Convert timestamp to UTC before formatting
dt = datetime.fromtimestamp(record.created, tz=timezone.utc)
if datefmt:
return dt.strftime(datefmt)
return dt.isoformat()
# Create logger
logger = logging.getLogger("my_app")
logger.setLevel(logging.DEBUG)
# Create formatter with UTC timestamps
formatter = UTCFormatter(
fmt="%(asctime)s | %(levelname)-8s | %(name)s | %(message)s",
datefmt="%Y-%m-%d %H:%M:%S %Z" # %Z will show 'UTC'
)
# Console handler
console_handler = logging.StreamHandler(sys.stdout)
console_handler.setFormatter(formatter)
logger.addHandler(console_handler)
# File handler with UTF-8 encoding
file_handler = logging.FileHandler("app.log", encoding="utf-8")
file_handler.setFormatter(formatter)
logger.addHandler(file_handler)
# Test with some UTF-8 characters
logger.info("Program started 😊 - Some UTF-8 text: 你好, здравствуйте")
Key points:
-
UTC Timestamps:
- We created a custom formatter that explicitly uses
timezone.utc
- Added
%Z to the datetime format to show the timezone
-
UTF-8 Encoding:
- When creating the
FileHandler, we specified encoding="utf-8"
- This ensures UTF-8 characters (like emojis and non-Latin alphabets) are stored correctly
The resulting log will show timestamps in UTC and properly handle UTF-8 characters in both console output and the log file.