第二次使用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 (将#修改为@)

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...