Friday, November 12, 2021

A Trivial Use Case of Python Logging Package



import logging
import pandas as pd
from time import time 

# create logger

logger = logging.getLogger('mylogger')
logger.setLevel(logging.DEBUG)

# create formatter
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')

# create file handler which logs even debug messages
log_file_name = pd.Timestamp('today').strftime('%Y-%m-%d') + "_" + str(round(time())) + ".log"

fh = logging.FileHandler(log_file_name)
fh.setLevel(logging.DEBUG)
fh.setFormatter(formatter) # Add formatter to the handlers
logger.addHandler(fh) # add the handlers to the logger

logger.info("Info logged.")
logger.debug("Debugging log.") 

Output:

File: 2021-11-11_1636609628.log
2021-11-11 11:17:08,174 - mylogger - INFO - Info logged.

File: 2021-11-12_1636688151.log
2021-11-12 09:05:50,813 - mylogger - INFO - Info logged.
2021-11-12 09:05:50,813 - mylogger - DEBUG - Debugging log.

No comments:

Post a Comment