只需使用Python的logging http://docs.python.org/2/library/logging.html module.
您可以按照您想要的方式调整输出;看一眼更改显示消息的格式 http://docs.python.org/2/howto/logging.html#changing-the-format-of-displayed-messages:
要更改用于显示消息的格式,您需要指定要使用的格式:
import logging
logging.basicConfig(format='%(levelname)s:%(message)s', level=logging.DEBUG)
logging.debug('This message should appear on the console')
logging.info('So should this')
logging.warning('And this, too')
and 格式化程序 http://docs.python.org/2/howto/logging.html#formatters:
格式化程序对象配置日志消息的最终顺序、结构和内容。
您将在此处找到可以使用的属性列表:日志记录属性 http://docs.python.org/2/library/logging.html#logrecord-attributes.
如果你想生成一个有效的 csv 文件,请使用 python 的csv module https://docs.python.org/3/library/csv.html, too.
这是一个简单的例子:
import logging
import csv
import io
class CsvFormatter(logging.Formatter):
def __init__(self):
super().__init__()
self.output = io.StringIO()
self.writer = csv.writer(self.output, quoting=csv.QUOTE_ALL)
def format(self, record):
self.writer.writerow([record.levelname, record.msg])
data = self.output.getvalue()
self.output.truncate(0)
self.output.seek(0)
return data.strip()
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)
logging.root.handlers[0].setFormatter(CsvFormatter())
logger.debug('This message should appear on the console')
logger.info('So should "this", and it\'s using quoting...')
logger.warning('And this, too')
Output:
“DEBUG”,“此消息应出现在控制台上”
“INFO”,“““this””也应该如此,并且它使用引用......”
“警告”,“还有这个”