[英]How to use logging library? (Implement logging in Python)
I would like to apply logging
library in a class to get reports from the different steps in my code and use info
, debug
or error
functions and keep it in a logging file.我想在一个类中应用
logging
库以从我的代码中的不同步骤获取报告,并使用info
、 debug
或error
函数并将其保存在日志文件中。 In addition I want to use multiprocessing
in my code as well.此外,我还想在我的代码中使用
multiprocessing
。 But I could not quite figure out how it works and should be set up, plus I have used it in a code and defined it as following但我不太清楚它是如何工作的,应该如何设置,另外我已经在代码中使用它并将其定义如下
import logging
logging.basicConfig(filename='logfile.log',level=logging.DEBUG)
it halted the code and prevents to terminate the process.它停止了代码并阻止终止进程。 I am wondering how it should be used in a class and stopped and closed the log file?!!
我想知道它应该如何在课堂上使用并停止并关闭日志文件?!! Any help would be appreciated...
任何帮助,将不胜感激...
You may go through Good logging practice in python for getting more idea of logging module and get more detailed info from Python document .您可以通过 Python 中的Good logging practice获得更多关于 logging 模块的想法并从Python 文档中获取更详细的信息。
Below is a basic example on how to use logging module, in which I am knowingly raising an exception:下面是一个关于如何使用日志记录模块的基本示例,我在其中故意提出了一个异常:
import logging
log = logging.getLogger("mylog")
log.setLevel(logging.DEBUG)
formatter = logging.Formatter(
"%(asctime)s %(threadName)-11s %(levelname)-10s %(message)s")
# Alternative formatting available on python 3.2+:
# formatter = logging.Formatter(
# "{asctime} {threadName:>11} {levelname} {message}", style='{')
# Log to file
filehandler = logging.FileHandler("debug.txt", "w")
filehandler.setLevel(logging.DEBUG)
filehandler.setFormatter(formatter)
log.addHandler(filehandler)
# Log to stdout too
streamhandler = logging.StreamHandler()
streamhandler.setLevel(logging.INFO)
streamhandler.setFormatter(formatter)
log.addHandler(streamhandler)
# Test it
log.debug("Some message")
log.error("An error!")
try:
something()
except:
log.exception("An exception occured!")
In your debug.txt
, you will get output as:在您的
debug.txt
中,您将获得如下输出:
2011-01-18 12:07:24,943 MainThread DEBUG Some message
2011-01-18 12:07:24,943 MainThread ERROR An error!
2011-01-18 12:07:24,943 MainThread ERROR An exception occured!
Traceback (most recent call last):
File "./logtest.py", line 17, in
something()
NameError: name 'something' is not defined
log = Logger( name ).logger日志 = 记录器(名称).logger
log.info('hello') log.info('你好')
The output of the logger will even contain the namefile (script.py). <br> I hope it helps! <br> The <a href="https://github.com/vignif/LogMe">code is available</a>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.