Python记录到stdout和日志文件 [英] Python logging to stdout and log file

查看:55
本文介绍了Python记录到stdout和日志文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是python的新手,开始进入日志记录模块.我想将消息记录到日志文件中并输出到控制台.下面的代码将消息输出到控制台,但是如何获取所有消息并记录到文件中?

I am fairly new in python and starting to get into the logging module. I would like to have the message logged into a log file and outputting to the console. The code below prints out the message to console but how can I get all the message to be log in a file?

Logger对象没有用于记录到文件的函数调用(basicConfig(filename =)).如何添加此功能?

Logger object does not have a function call (basicConfig(filename=)) for logging to a file. How can I add this functionality?

非常感谢您的帮助.

import logging

# create logger
logger = logging.getLogger(_name_)
logger.setLevel(logging.DEBUG)

# create console handler and set level to debug
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)

# create formatter
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')

# add formatter to ch
ch.setFormatter(formatter)

# add ch to logger
logger.addHandler(ch)

# 'application' code
logger.debug('debug message')
logger.info('info message')
logger.warn('warn message')
logger.error('error message')
logger.critical('critical message')

推荐答案

您只需要添加另一个处理程序,例如 logging.FileHandler

You just need to add another handler, like a logging.FileHandler

fh = logging.FileHandler(r'/path/to/log.txt')
logger.addHandler(fh)

这篇关于Python记录到stdout和日志文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆