Python 记录到标准输出和日志文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40858658/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 00:06:15  来源:igfitidea点击:

Python logging to stdout and log file

pythonlogging

提问by Zen

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?

我在 python 中相当新,并开始进入日志模块。我希望将消息记录到日志文件中并输出到控制台。下面的代码将消息打印到控制台,但如何将所有消息记录到文件中?

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

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

Thanks for the help in advance.

我在这里先向您的帮助表示感谢。

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')

采纳答案by Brendan Abel

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

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

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

回答by victor

Expanding on @Brendan's answer.

扩展@Brendan 的回答。

Your logger currently outputs to the console using a StreamHandler.

您的记录器当前使用StreamHandler.

By adding a FileHandler, you can log to a file.

通过添加FileHandler,您可以登录到文件。

Each handler instance can be customized to have its own format and logging level.

每个处理程序实例都可以自定义为具有自己的格式和日志记录级别。

If you want to log using the same format, you will have to set the format on the new FileHandler as well.

如果您想使用相同的格式进行日志记录,您还必须在新的 FileHandler 上设置格式。

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

Read more: Python logging cookbook

阅读更多:Python 日志记录手册

回答by Lexxer

After having used Waterboy's code for simultaneous logging to console and to file (see this thread) over and over in multiple Python packages, I finally cast it into a tiny standalone Python package, which you can find here:

在使用 Waterboy 的代码在多个 Python 包中一遍又一遍地同时记录到控制台和文件(请参阅此线程)后,我终于将其转换为一个小型的独立 Python 包,您可以在此处找到它:

https://github.com/acschaefer/duallog

https://github.com/acschaefer/duallog

The code is well documented and easy to use. Simply download the .pyfile and include it in your project, or install the whole package via python setup.py install.

该代码有据可查且易于使用。只需下载该.py文件并将其包含在您的项目中,或者通过python setup.py install.

Using this package, your code would look like this:

使用这个包,你的代码看起来像这样:

# Set up logging to console and file.
import duallog
duallog.setup(logdir='my_logs')

# Generate log messages.
import logging    
logging.debug('debug message')
logging.info('info message')
logging.warn('warn message')
logging.error('error message')
logging.critical('critical message')