Created
May 5, 2025 15:18
-
-
Save hartwork/8b5963b5e9a698a3d6d352c657418af3 to your computer and use it in GitHub Desktop.
Demo Python logging with time zone information for field `asctime`
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#! /usr/bin/env python3 | |
# Copyright (c) Sebastian Pipping <[email protected]> | |
# | |
# Licensed under Zero-Clause BSD | |
# SPDX-License-Identifier: 0BSD | |
import datetime | |
import logging | |
class CustomFormatter(logging.Formatter): | |
def formatTime(self, record, datefmt=None): | |
local_time_zone = datetime.datetime.now().astimezone().tzinfo | |
dt = datetime.datetime.fromtimestamp(record.created, tz=local_time_zone) | |
return dt.isoformat(sep=" ", timespec="milliseconds") | |
format_ = "[%(asctime)s][%(levelname)s] %(message)s" | |
logging.basicConfig(format=format_) | |
logging.warning("First warning, no time zone") | |
# Now install customer formatter class | |
formatter = CustomFormatter(fmt=format_) | |
for handler in logging.root.handlers: | |
handler.setFormatter(formatter) | |
logging.warning("Second warning, with time zone") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Output: