Last active
April 28, 2025 07:13
-
-
Save NicolasPA/81071be2a08946db21523ea57748dd93 to your computer and use it in GitHub Desktop.
A fancy log format with ISO date, package and function name
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
import logging | |
from datetime import datetime | |
from typing import Union | |
def get_configured_logger(level: Union[int, str]) -> logging.Logger: | |
""" | |
Set a useful logging format and return a logger with a full reference to the current module. | |
>>> import logging | |
>>> logger = get_configured_logger(logging.INFO) | |
>>> logger.info("building table") | |
2021-07-16 10:55:17.417 INFO my_package.my_function: building table | |
:param level: as defined in logging library | |
""" | |
logging.basicConfig( | |
level=level, | |
format="%(asctime)s.%(msecs)03d %(levelname)-8s %(name)s.%(funcName)s: %(message)s", | |
datefmt="%Y-%m-%d %H:%M:%S", | |
handlers=[ | |
logging.FileHandler(f"logs/log_{datetime.now().strftime('%Y%m%d-%H%M%S.%f')[:-3]}.txt"), | |
logging.StreamHandler() | |
] | |
) | |
return logging.getLogger(__name__) | |
logger = get_configured_logger(logging.INFO) | |
def my_function(): | |
logger.info("My log line.") | |
my_function() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment