【问题标题】:Is it possible to save logging information from python project in a local variable?是否可以将 python 项目的日志信息保存在局部变量中?
【发布时间】:2020-07-18 15:48:19
【问题描述】:

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

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

【问题讨论】:

标签: python json logging


【解决方案1】:

这个网站上的内容帮助我找到了解决方案: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_string StringIO 获取您的内容

【讨论】:

    猜你喜欢
    • 2011-08-17
    • 1970-01-01
    • 2020-12-28
    • 2023-04-08
    • 2018-07-27
    • 1970-01-01
    • 2011-01-25
    • 1970-01-01
    • 2014-08-04
    相关资源
    最近更新 更多