使用 Python 在文件中打印日志
原文:https://www.studytonight.com/python/python-logging-in-file
如果您想在文件中打印 python 日志,而不是在控制台上打印,那么我们可以通过提供filename和filemode作为参数来使用basicConfig()方法。
消息的格式可以使用basicConfig()方法中的format参数来指定。
让我们举一个基本的例子,将日志打印到一个文件中,而不是在控制台上。下面给出了代码片段:
import logging # first of all import the module
logging.basicConfig(filename='std.log', filemode='w', format='%(name)s - %(levelname)s - %(message)s')
logging.warning('This message will get logged on to a file')
根错误-此消息将被记录到一个文件中
上面的输出显示了消息看起来是怎样的,但是请记住,它将被写入名为 std.log 的文件,而不是控制台。
在上面的代码中,filemode被设置为w,这意味着每次调用basicConfig()时,日志文件都是以写模式打开的,每次运行程序后,它都会重写文件。
文件模式的默认配置是a,即追加,这意味着日志将被追加到日志文件中,并将日志添加到现有日志中。
Python 日志记录-将日志存储在文件中
下面给出了一些基本步骤:
首先,只需写
import logging,简单导入logging模块。第二步是创建和配置记录器。要配置记录器将日志存储在文件中,必须传递要记录事件的文件的名称。
在第三步中,还可以设置记录器的格式。请注意,默认情况下,文件在追加模式下工作,但如果需要,我们可以将其更改为写入模式。
您还可以设置记录器的级别。
现在让我们继续看代码:
#importing the module
import logging
#now we will Create and configure logger
logging.basicConfig(filename="std.log",
format='%(asctime)s %(message)s',
filemode='w')
#Let us Create an object
logger=logging.getLogger()
#Now we are going to Set the threshold of logger to DEBUG
logger.setLevel(logging.DEBUG)
#some messages to test
logger.debug("This is just a harmless debug message")
logger.info("This is just an information for you")
logger.warning("OOPS!!!Its a Warning")
logger.error("Have you try to divide a number by zero")
logger.critical("The Internet is not working....")
上面的代码会写一些消息到名为 std.log 的文件中。如果我们打开文件,那么消息将如下所示:
2020-06-19 12:48:00,449 -这只是无害的调试消息 2020-06-19 12:48:00,449 -这只是给你的一个信息 2020-06-19 12:48:00,449 - OOPS!!!这是一个警告 2020-06-19 12:48:00,449 -你试过用零除一个数字吗 2020-06-19 12:48:00,449 -互联网不工作了...
您可以更改日志的格式、日志级别或LogRecord的任何其他属性,以及设置文件名以将日志和模式一起存储在文件中。