Google Colab 中的日志记录模块出现问题
Problem with Logging Module in Google Colab
我有一个 python 脚本,它使用日志模块进行错误处理。尽管此 python 脚本在导入到 google colab 时有效,但它不会在日志文件中记录错误。
作为实验,我在 google colab 中尝试了以下脚本,只是为了看看它是否完全写入日志
import logging
logging.basicConfig(filename="log_file_test.log",
filemode='a',
format='%(asctime)s,%(msecs)d %(name)s %(levelname)s %(message)s',
datefmt='%H:%M:%S',
level=logging.DEBUG)
logging.info("This is a test log ..")
令我沮丧的是,它 甚至没有创建 名为 log_file_test.log 的日志文件。我在本地 尝试了 运行 相同的脚本,它 确实生成了 一个文件 log_file_test.log 与以下文本
13:20:53,441 root INFO This is a test log ..
我在这里缺少什么?
目前,我正在用打印语句替换错误日志,但我认为必须有解决方法。
也许您以某种方式重新配置了您的环境? (尝试运行时菜单 -> 重置所有运行时...)您的代码片段完全按照为我编写的方式运行 --
logging.basicConfig
可以 运行 一次*
任何对 basicConfig
的后续调用都将被忽略。
*
除非你在 Python 3.8 并使用标志 force=True
logging.basicConfig(filename='app.log',
level=logging.DEBUG,
force=True, # Resets any previous configuration
)
解决方法 (2)
(1)
您可以使用此命令轻松重置 Colab 工作区
exit
等待它返回并再次尝试您的命令。
(2)
但是,如果您打算多次重置 and/or 正在学习使用 logging
,也许最好使用 %%python
magic 到 运行子进程中的整个单元格。见下图。
What is it that I am missing here?
更深入地了解 logging
的工作原理。这有点棘手,但是有很多很好的网站可以解释陷阱。
我有一个 python 脚本,它使用日志模块进行错误处理。尽管此 python 脚本在导入到 google colab 时有效,但它不会在日志文件中记录错误。
作为实验,我在 google colab 中尝试了以下脚本,只是为了看看它是否完全写入日志
import logging
logging.basicConfig(filename="log_file_test.log",
filemode='a',
format='%(asctime)s,%(msecs)d %(name)s %(levelname)s %(message)s',
datefmt='%H:%M:%S',
level=logging.DEBUG)
logging.info("This is a test log ..")
令我沮丧的是,它 甚至没有创建 名为 log_file_test.log 的日志文件。我在本地 尝试了 运行 相同的脚本,它 确实生成了 一个文件 log_file_test.log 与以下文本
13:20:53,441 root INFO This is a test log ..
我在这里缺少什么? 目前,我正在用打印语句替换错误日志,但我认为必须有解决方法。
也许您以某种方式重新配置了您的环境? (尝试运行时菜单 -> 重置所有运行时...)您的代码片段完全按照为我编写的方式运行 --
logging.basicConfig
可以 运行 一次*
任何对 basicConfig
的后续调用都将被忽略。
*
除非你在 Python 3.8 并使用标志 force=True
logging.basicConfig(filename='app.log',
level=logging.DEBUG,
force=True, # Resets any previous configuration
)
解决方法 (2)
(1)
您可以使用此命令轻松重置 Colab 工作区
exit
等待它返回并再次尝试您的命令。
(2)
但是,如果您打算多次重置 and/or 正在学习使用 logging
,也许最好使用 %%python
magic 到 运行子进程中的整个单元格。见下图。
What is it that I am missing here?
更深入地了解 logging
的工作原理。这有点棘手,但是有很多很好的网站可以解释陷阱。