使用ptb的Python日志记录:同一行记录了两次,但只添加了一个处理程序

2024-04-28 13:46:01 发布

您现在位置:Python中文网/ 问答频道 /正文

  • python:3.6.6
  • python电报机器人:10.0.2

我有一个问题:我定义了一个带有SMTPHandler、timedrotingfilehandler和StreamHandler的python记录器。在

StreamHandler工作正常,但当我试图从python telegram bot处理程序中使用它时,该行在标准输出上以两种不同的格式打印两次,我无法找到如何避免其中一种格式并保留另一种格式(定时的)。在

我已经找到原因了。当添加带有CallbackQueryHandler的ConversationHandler时,在启动时显示此消息。在

WARNING:root:If 'per_message=False', 'CallbackQueryHandler' will not be tracked for every message.

然后每次都会出现未拆开的原木线。在

代码以日志形式显示在下面_配置.py. 我还添加了测试mymain的示例代码_文件.py和当前输出作为多行注释。在

配置/日志_配置.py

^{pr2}$

我的主_文件.py

#!/usr/bin/python3
from telegram.ext import (Updater, CommandHandler, ConversationHandler,
                          run_async, CallbackQueryHandler)
from config.log_config import getLogger

# Enable logging
logger = getLogger(__name__)

updater = Updater('......')  # Replace with your bot token

# ************************** HANDLERS
# Define a few command handlers. These usually take the two arguments bot and
# update. Error handlers also receive the raised TelegramError object in error.


@run_async
def show_help(bot, update):
    logger.info('HELP!')


def error_handler(bot, update, error):
    logger.warning('La actualización "%s" causó el error "%s"', update, error)


def dumb_handler(bot, update, user_data):
    return ConversationHandler.END


def main():
    """Start the bot."""
    # Create the EventHandler and pass it your bot's token.
    global updater

    # Get the dispatcher to register handlers
    dp = updater.dispatcher

    # on different commands - answer in Telegram
    dp.add_handler(CommandHandler('help', show_help))

    # Add conversation handler with the states
    # The telegram conversation handler needs a handler_list with functions
    # so it can execute desired code in each state/step

    conv_handler = ConversationHandler(
        entry_points=[CommandHandler('irrelevant', dumb_handler,
                                     pass_user_data=True)
                      ],
        states={
            0: [CallbackQueryHandler(dumb_handler, pass_user_data=True)],
        },
        fallbacks=[],
    )
    dp.add_handler(conv_handler)

    # log all errors
    dp.add_error_handler(error_handler)

    updater.start_polling()
    updater.idle()


if __name__ == '__main__':
    main()

"""
OUTPUT when used /help from the bot chat
(First is my wished output, second is the line I want to avoid)
------

2018-11-08 16:41:51,115 - (1.2.0) INFO - __main__ - HELP!
INFO:__main__:HELP!
"""

Tags: thepymaindef格式bothelpupdate
1条回答
网友
1楼 · 发布于 2024-04-28 13:46:01

telegram.ext.ConversationHandler包括几个日志调用,它们使用logging.warning而不是它们可能应该使用的self.logger记录器,例如this call

for handler in all_handlers:
    if isinstance(handler, CallbackQueryHandler):
        logging.warning("If 'per_message=False', 'CallbackQueryHandler' will not be "
                        "tracked for every message.")

logging.warning和其他模块级日志记录便利函数调用^{},如果根日志记录器上不存在处理程序,它会向根日志记录器添加一个处理程序。这个处理程序负责处理不需要的

^{pr2}$

记录输出。在

使用logging.warning而不是{}应该被认为是python电报bot错误。我在他们的issue tracker上看不到它的开放问题,所以您可能需要提交一个bug报告。在

同时,或者如果python telegram bot开发人员认为行为正常,您可以向根日志记录器添加一个空处理程序,以防止basicConfig添加自己的处理程序。必须在创建ConversationHandler之前完成此操作,才能抢占basicConfig

logging.getLogger().addHandler(logging.NullHandler())

相关问题 更多 >