您的位置:首页 > 编程语言 > Python开发

获取python日志输出为字符串变量

2018-01-22 21:48 218 查看
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())
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python logging io