Sunday, 16 January 2022

How to get message from logging function?

I have a logger function from logging package that after I call it, I can send the message through logging level.

I would like to send this message also to another function, which is a Telegram function called SendTelegramMsg().

How can I get the message after I call the funcion setup_logger send a message through logger.info("Start") for example, and then send this exatcly same message to SendTelegramMsg() function which is inside setup_logger function?

My currently setup_logger function:

# Define the logging level and the file name
def setup_logger(telegram_integration=False):
    """To setup as many loggers as you want"""

    filename = os.path.join(os.path.sep, pathlib.Path(__file__).parent.resolve(), 'logs', str(dt.date.today()) + '.log')
    formatter = logging.Formatter('%(levelname)s: %(asctime)s: %(message)s', datefmt='%m/%d/%Y %H:%M:%S')
    level = logging.DEBUG

    handler = logging.FileHandler(filename, 'a')    
    handler.setFormatter(formatter)

    consolehandler = logging.StreamHandler()
    consolehandler.setFormatter(formatter)

    logger = logging.getLogger('logs')
    if logger.hasHandlers():
        # Logger is already configured, remove all handlers
        logger.handlers = []
    else:
        logger.setLevel(level)
        logger.addHandler(handler)        
        logger.addHandler(consolehandler)

    #if telegram_integration == True:
        #SendTelegramMsg(message goes here)

    return logger

After I call the function setup_logger():

logger = setup_logger()
logger.info("Start")

The output:

INFO: 01/06/2022 11:07:12: Start

How am I able to get this message and send to SendTelegramMsg() if I enable the integration to True?



from How to get message from logging function?

No comments:

Post a Comment