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
?
3
Answers
Picking up the idea suggested by @gold_cy: You implement a custom
logging.Handler
. Some hints for that:__init__
so that you have it available lateremit
must be implemented by you. Here you’ll want to callformat
which gives you a formatted version of the log record. You can then use that message to send it via the botStreamHandler
andFileHandler
is helpful as wellImplement a custom logging.Handler:
Add the handler:
Usage, no change: