获取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())
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入门(二)——IDE选择PyCharm,输入和输出,基础规范,数据类型和变量,常量,字符串和编码,格式化
- Python3基础 str + 字符串变量拼接后,用print输出
- python如何把输出的字符串赋值给变量
- python 调用系统命令,并将输出重定向,输出其结果至文件或者字符串变量
- Python学习笔记:02 基础:变量、整数、字符串、赋值、基本输出、注释、代码块
- Python入门(二)——IDE选择PyCharm,输入和输出,基础规范,数据类型和变量,常量,字符串和编码,格式化
- Python学习:使用boost c++嵌入python,获取异常信息输出到字符串
- Python学习(三) 输出任意格式的字符串以及字符串的切片
- 编写一函数 用户输入字符串 函数将获取第一个单词输出 并丢掉后面的字符(图)
- Python使用logging结合decorator模式实现优化日志输出的方法
- caffe中accuracy和loss用python从log日志里面获取
- python logging动态变更输出日志文件名
- python中使用shell命令的输出作为其变量的方法
- Python学习(变量与字符串)
- Python变量、字符串
- python 以十六进制输出字符串
- Python变量的三个特征获取方式
- Python:字符串中引用外部变量的3种方法
- objective-c之sel----字符串转化成sel数据(变量)----sel数据(变量)转化成字符串输出
- Python对象的文档字符串(DocString):__doc__的写法和输出方法