Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用ptb进行Python日志记录:同一行记录了两次,但只添加了一个处理程序 python:3.6.6 python电报机器人:10.0.2_Python_Python 3.x_Logging_Python Telegram Bot - Fatal编程技术网

使用ptb进行Python日志记录:同一行记录了两次,但只添加了一个处理程序 python:3.6.6 python电报机器人:10.0.2

使用ptb进行Python日志记录:同一行记录了两次,但只添加了一个处理程序 python:3.6.6 python电报机器人:10.0.2,python,python-3.x,logging,python-telegram-bot,Python,Python 3.x,Logging,Python Telegram Bot,我有这个问题:我已经定义了一个带有SMTPHandler、timedrotationfilehandler和StreamHandler的python记录器 StreamHandler工作得很好,但当我尝试从python telegram bot处理程序使用它时,该行在标准输出上以两种不同的格式打印了两次,我无法找到如何避免一种格式并保留另一种格式(定时格式) 我已经发现了原因。添加带有CallbackQueryHandler的ConversationHandler时,启动时会显示此消息 WARN

我有这个问题:我已经定义了一个带有SMTPHandler、timedrotationfilehandler和StreamHandler的python记录器

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

我已经发现了原因。添加带有CallbackQueryHandler的ConversationHandler时,启动时会显示此消息

WARNING:root:If 'per_message=False', 'CallbackQueryHandler' will not be tracked for every message.
然后每次都会出现未清除的日志行

下面的代码是log_config.py。我还添加了用于测试my_main_file.py和作为多行注释的当前输出的示例代码

config/log\u config.py

import os

import logging
from logging import Formatter

from datetime import datetime


VERSION_NUM = '1.2.0'
LOG_MSG_FORMAT = '%(asctime)s - ({0}) %(levelname)s - %(name)s - %(message)s'
LOGFILE_PATH = os.path.join(os.path.dirname(os.path.dirname(__file__)),
                            'log',
                            'alfred.log')
logging.getLogger('telegram').setLevel(logging.WARNING)
logging.getLogger('chardet.charsetprober').setLevel(logging.WARNING)


def my_timezone_time(*args):
    # I simplified this line, because it's irrelevant
    return datetime.now().timetuple()


handlers = []


#
# ... different handlers added
#


# last handler to add, this one works just as I want

ch = logging.StreamHandler()
formatter = Formatter(LOG_MSG_FORMAT.format(VERSION_NUM))
formatter.converter = my_timezone_time
ch.setFormatter(formatter)
ch.setLevel(logging.INFO)
handlers.append(ch)


def getLogger(name):
    """
    Returns a logger for the file. Works fine but when used,
       it always outputs the same line with the last handler 
       and also with an unknown handler not added by me 
       (must be some default instance)
    :param name: the file name
    :return: a logger
    """
    logger = logging.getLogger(name)
    logger.setLevel(logging.DEBUG)
    for h in handlers:
        logger.addHandler(h)

    return logger
#!/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!
"""
我的主文件.py

import os

import logging
from logging import Formatter

from datetime import datetime


VERSION_NUM = '1.2.0'
LOG_MSG_FORMAT = '%(asctime)s - ({0}) %(levelname)s - %(name)s - %(message)s'
LOGFILE_PATH = os.path.join(os.path.dirname(os.path.dirname(__file__)),
                            'log',
                            'alfred.log')
logging.getLogger('telegram').setLevel(logging.WARNING)
logging.getLogger('chardet.charsetprober').setLevel(logging.WARNING)


def my_timezone_time(*args):
    # I simplified this line, because it's irrelevant
    return datetime.now().timetuple()


handlers = []


#
# ... different handlers added
#


# last handler to add, this one works just as I want

ch = logging.StreamHandler()
formatter = Formatter(LOG_MSG_FORMAT.format(VERSION_NUM))
formatter.converter = my_timezone_time
ch.setFormatter(formatter)
ch.setLevel(logging.INFO)
handlers.append(ch)


def getLogger(name):
    """
    Returns a logger for the file. Works fine but when used,
       it always outputs the same line with the last handler 
       and also with an unknown handler not added by me 
       (must be some default instance)
    :param name: the file name
    :return: a logger
    """
    logger = logging.getLogger(name)
    logger.setLevel(logging.DEBUG)
    for h in handlers:
        logger.addHandler(h)

    return logger
#!/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!
"""

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

logging.warning
和其他模块级日志便利函数调用,如果根日志记录器上没有处理程序,则会向根日志记录器添加处理程序。该处理程序负责处理不需要的数据

INFO:__main__:HELP!
记录输出

使用
logging.warning
而不是
self.logger.warning
可能会被认为是python电报机器人的一个bug。我在他们的网站上看不到关于它的公开问题,所以你可能想提交一份bug报告

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

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

在剥离代码时,请确保剥离的表单在运行时仍会复制错误。对不起。你说得对。当使用来自另一个文件的函数时,它会这样做,但我试图简化所有内容以包括在这里,但没有测试它。我正在编辑。我修改了它。我做得再简单不过了。你用的是什么python电报机器人版本?10.0.2和python是3.6.6