Created
December 28, 2021 14:41
-
-
Save gabicavalcante/592a4f60cf7749238671adf4f94a352b to your computer and use it in GitHub Desktop.
This file contains 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 | |
import time | |
from contextlib import contextmanager | |
logger = logging.getLogger(__name__) | |
@contextmanager | |
def log_file(logger_, log_message="Took %.4f secs", log_level=logging.INFO): | |
logging.basicConfig(filename='example.log', encoding='utf-8', level=logging.DEBUG) | |
start = time.perf_counter() | |
yield | |
elapsed = time.perf_counter() - start | |
logger_.log(log_level, log_message, elapsed) | |
def using_context(): | |
logger.debug('[1] This message should not go to the log file') | |
logger.info('[1] So should not this') | |
logger.warning('[1] And this, too') | |
logger.error('[1] And non-ASCII stuff, too, like Øresund and Malmö') | |
with log_file(logger_=logger, log_message="Daily downloaded took %.4f secs"): | |
logger.debug('[2] This message should go to the log file') | |
logger.info('[2] So should this') | |
logger.warning('[2] And this, too') | |
logger.error('[2] And non-ASCII stuff, too, like Øresund and Malmö') | |
def not_using_context(): | |
logger.debug('[1] This message should not go to the log file') | |
logger.info('[1] So should not this') | |
logger.warning('[1] And this, too') | |
logger.error('[1] And non-ASCII stuff, too, like Øresund and Malmö') | |
logging.basicConfig(filename='example.log', encoding='utf-8', level=logging.DEBUG) | |
logger.debug('[2] This message should go to the log file') | |
logger.info('[2] So should this') | |
logger.warning('[2] And this, too') | |
logger.error('[2] And non-ASCII stuff, too, like Øresund and Malmö') | |
not_using_context() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment