如何解决第二次使用python 2.7
我知道标题似乎令人困惑。 我将尝试更好地解释myslef。 Python 2.7,我正在编写一个模块来设置我可能使用的任何其他脚本的日志记录。 从任何其他脚本中,我将导入此模块,以便配置日志记录。
我想要一种非常特定的日志输出格式,只能通过创建自定义格式器来获取。到目前为止没有问题,我得到了期望的输出。 这是我的日志记录模块:
import logging
import sys
class CustomLogFormatter(logging.Formatter):
def format(self,record):
source = "%s.%s:%s" % (record.module,record.funcName,record.lineno)
custom_levelname_display = "[%s]" % (record.levelname)
msg = "%s %-50s %10s: %s" % (self.formatTime(record),source,custom_levelname_display,record.msg)
record.msg = msg
return super(CustomLogFormatter,self).format(record)
def configure_root_logger(log_filename):
# Configure the root logger
root_logger = logging.getLogger()
root_logger.setLevel(logging.INFO)
# Create handlers
console_handler = logging.StreamHandler(sys.stdout)
console_handler.setLevel(logging.INFO)
file_handler = logging.FileHandler(log_filename)
file_handler.setLevel(logging.INFO)
# Create formatters and add them to handlers
file_formatter = CustomLogFormatter()
file_handler.setFormatter(file_formatter)
console_formatter = CustomLogFormatter()
# KNOWN ISSUE
# If I assign more than once an instance of the custom formatter object like in the line above,in the log file everything but the message parameter is repeated twice in every row.
# If you create a second custom formatter object but you don't assign/use it,the log file is as intended. No idea why,and I can't seem to find anything on the web related to this
# I'm assigning handlers only to root logger as advised by the documentation
# working way,but with wrong console output and correct file output (the line below,commented):
#console_formatter = logging.Formatter('%(module)s.%(funcName)-20s - [%(levelname)s]: %(message)s')
console_handler.setFormatter(console_formatter)
# Add handlers to the root logger
root_logger.addHandler(console_handler)
root_logger.addHandler(file_handler)
return root_logger
所以基本上,如果我两次分配一个CustomLogFormatter对象,并且我都使用它们,则在文件日志中的输出是
time source custom_levelname_display time source custom_levelname_display message
在控制台上,它是正确的:
time source custom_levelname_display message
相反,如果我仅将自定义格式化程序分配给日志文件的处理程序,而我只是使用此控制台格式化程序:
console_formatter = logging.Formatter('%(module)s.%(funcName)-20s - [%(levelname)s]: %(message)s')
日志文件中的输出符合预期,(当然控制台输出不是)。
我花了很多时间,不知道如果我使用两次(单独的!)自定义格式化程序,记录的那部分是如何重复的
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。