首页 > 解决方案 > 是否可以将 python 项目的日志信息保存在局部变量中?

问题描述

我正在为一个项目使用日志记录。到目前为止,我将所有日志记录信息存储在由 RotatingFileHandler 创建的文件中。但是,我想知道是否可以将所有日志记录信息保存在我机器上类似字典的局部变量中?

我想这样做是因为该项目的要求之一是在执行过程中不要创建任何新文件。

标签: pythonjsonlogging

解决方案


该网站上的内容帮助我找到了解决方案:http ://alanwsmith.com/capturing-python-log-output-in-a-variable 。这是所用代码的摘录。

import logging
import io

### Create the logger
logger = logging.getLogger('basic_logger')
logger.setLevel(logging.DEBUG)

### Setup the console handler with a StringIO object
log_capture_string = io.StringIO()
ch = logging.StreamHandler(log_capture_string)
ch.setLevel(logging.DEBUG)

### Optionally add a formatter
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
ch.setFormatter(formatter)

### Add the console handler to the logger
logger.addHandler(ch)


### Send log messages. 
logger.debug('debug message')
logger.info('info message')
logger.warn('warn message')
logger.error('error message')
logger.critical('critical message')


### Pull the contents back into a string and close the stream
log_contents = log_capture_string.getvalue()
log_capture_string.close()

### Output as lower case to prove it worked. 
print(log_contents.lower())

您将log_capture_string作为参数添加到您的StreamHandler,然后从您的log_capture_stringStringIO获取您的内容


推荐阅读