我基于 Tornado 构建了一个应用程序。
<块引用>龙卷风版本:6.0.4
Python 版本:3.8.5
我的日志代码是:
tornado.options.parse_command_line()
gen_logger = logging.getLogger("tornado.general")
gen_logger.propagate = False
log_path = os.path.dirname(os.path.abspath(__name__))
log_path = os.path.join(log_path, "log")
if not os.path.exists(log_path):
os.mkdir(log_path)
log_file_gen_info = os.path.join(log_path, "log_general_info.log")
# set Formatter for root
formatter = logging.Formatter(
"%(asctime)s.%(msecs)03d|%(levelname)s|%(filename)s|%(funcName)s()|Line:%(lineno)d|%(message)s",
datefmt="%Y-%m-%d %H:%M:%S",
)
handler_file_gen_info = ConcurrentRotatingFileHandler(
log_file_gen_info,
mode="a",
maxBytes=30 * 1024 * 1024,
backupCount=30,
encoding="utf-8",
)
handler_file_gen_info.setFormatter(formatter)
handler_file_gen_info.setLevel(logging.INFO)
gen_logger.addHandler(handler_file_gen_info)
当我需要将一些日志信息写入日志文件时,我使用如下代码:
logger = logging.getLogger("tornado.general")
logger.info("my log information.")
此日志信息可以正确保存到我的日志文件中。但是我也可以找到一些不是我自己写的日志信息。
2021-05-04 18:36:55.407|INFO|backTransmission.py|on_send_success()|Line:168|Sent kafka message successfully.
2021-05-04 18:37:18.461|INFO|http1connection.py|_read_message()|Line:289|Malformed HTTP message from 10.129.98.81: Malformed HTTP version in HTTP Request-Line: 'HTTP/2.0'
2021-05-04 18:37:55.756|INFO|http1connection.py|_read_message()|Line:289|Malformed HTTP message from 10.129.106.104: Malformed HTTP version in HTTP Request-Line: 'HTTP/2.0'
2021-05-04 18:38:00.664|INFO|http1connection.py|_read_message()|Line:289|Malformed HTTP message from 10.144.2.199: Malformed HTTP version in HTTP Request-Line: 'HTTP/2.0'
2021-05-04 18:38:00.725|INFO|http1connection.py|_read_message()|Line:289|Malformed HTTP message from 10.144.2.199: Malformed HTTP version in HTTP Request-Line: 'HTTP/2.0'
2021-05-04 18:39:14.598|INFO|http1connection.py|_read_message()|Line:289|Malformed HTTP message from 10.129.98.81: Malformed HTTP version in HTTP Request-Line: 'HTTP/2.0'
第一行来自我的日志代码,以下不是我的日志代码。但我不希望将以下几行写入我的日志文件,因为这些日志记录太多了。如何避免它们?我试图通过从谷歌搜索解决方案来修复它,但失败了。欢迎向我提出任何建议。谢谢。
答案 0 :(得分:1)
在您的情况下,一种方法可能是通过实现自定义 Filter
对象,只允许比 INFO
级别更高的消息用于其他记录器(以消除噪音)。
class TornadoFilter(logging.Filter):
ALL_LEVELS = "tornado.general"
def filter(self, record):
if record.name == TornadoFilter.ALL_LEVELS:
return True
else:
if record.levelno > logging.INFO:
return True
return False
# logging setup ...
fltr = TornadoFIlter()
handler_file_gen_info.addFilter(fltr)
相反,您可以只使用 default Filter
并使用您希望只允许来自该 logger
的消息传播和记录的名称对其进行初始化.
fltr = logging.Filter("tornado.general")
handler_file_gen_info.addFilter(fltr)
答案 1 :(得分:1)
tornado.general
是 Tornado 用于其自身消息的记录器。您应该为您的应用程序创建自己的记录器,logger = logging.getLogger("myapp")
然后您可以根据自己的喜好配置此记录器,将其消息发送到您的日志文件并将龙卷风的消息发送到另一个文件(或者根本不发送,尽管我建议保存至少来自 Tornado 某处记录器的 ERROR 级消息)