日志系统#
备注
Astropy日志记录系统旨在为内部 astropy
用法。为了在其他包中使用,我们建议改为实现您自己的记录器。
概述#
Astropy日志系统的设计目的是让用户能够灵活地决定要显示哪些日志消息、捕获它们并将它们发送到文件中。
Astropy例程打印的所有消息都应该使用内置的日志记录工具(正常 print()
调用只能由显式请求打印输出的例程完成)。消息可以有以下几种级别之一:
调试:详细信息,通常只有在诊断问题时才感兴趣。
信息:传达有关当前任务的信息,并确认事情按预期工作的消息
警告:表示发生了意外情况,可能需要用户执行操作。
错误:表示更严重的问题,包括异常
默认情况下,将显示信息、警告和错误消息,并将其发送到位于 ~/.astropy/astropy.log
(如果文件是可写的)。
配置日志记录系统#
首先,导入记录器:
from astropy import log
消息的阈值级别(如上所述)可以通过以下方式设置:
log.setLevel('DEBUG')
颜色(默认情况下启用)可以通过以下方式禁用:
log.disable_color()
并启用:
log.enable_color()
来自的警告 warnings.warn
可以用以下方式记录:
log.enable_warnings_logging()
可使用以下命令禁用:
log.disable_warnings_logging()
异常可以包含在日志中:
log.enable_exception_logging()
可使用以下命令禁用:
log.disable_exception_logging()
也可以从文件中指定这些设置。看到了吗 Using the configuration file 更多信息。
上下文管理器#
在某些情况下,您可能需要捕获日志消息,例如,检查是否输出了特定消息,或者将特定代码段中的消息记录到文件中。这两种方法都可以使用上下文管理器。
要将日志消息添加到列表中,请先导入记录器(如果尚未导入):
from astropy import log
然后将要在其中记录消息的代码放入 with
声明:
with log.log_to_list() as log_list:
# your code here
在上面的例子中,一旦代码块被执行, log_list
将是一个Python列表,其中包含所有引发的Astropy日志消息。请注意,消息继续正常输出。
类似地,您可以使用以下命令将特定代码段的日志消息输出到文件中:
with log.log_to_file('myfile.log'):
# your code here
将所有消息添加到 myfile.log
除此之外,文件中还提到了 Using the configuration file )
而这些上下文管理器将包括记录器发出的所有消息(使用 log.setLevel
),可以使用 filter_level=
,并指定其中一个 'DEBUG'
, 'INFO'
, 'WARN'
, 'ERROR'
. 注意如果 filter_level
是一个较低的水平设置通过 setLevel
,只有级别设置为的邮件 setLevel
包括或更高的费用(即。 filter_level
只过滤记录器正常发出的消息的子集)。
类似地,可以通过指定 filter_origin=
后面是一个字符串。如果消息的上下文以消息的上下文开头,则该消息将包含在消息的上下文中。例如, filter_origin='astropy.wcs'
将只包括在 astropy.wcs
子包。
使用配置文件#
可以在中设置记录器的选项 [logger]
Astropy配置文件的部分:
[logger]
# Threshold for the logging messages. Logging messages that are less severe
# than this level will be ignored. The levels are 'DEBUG', 'INFO', 'WARNING',
# 'ERROR'
log_level = 'INFO'
# Whether to use color for the level names
use_color = True
# Whether to log warnings.warn calls
log_warnings = False
# Whether to log exceptions before raising them
log_exceptions = False
# Whether to always log messages to a log file
log_to_file = True
# The file to log messages to. If empty string is given, it defaults to a
# file `astropy.log` in the astropy config directory.
log_file_path = '~/.astropy/astropy.log'
# Threshold for logging messages to log_file_path
log_file_level = 'INFO'
# Format for log file entries
log_file_format = '%(asctime)s, %(origin)s, %(levelname)s, %(message)s'
# The encoding (e.g., UTF-8) to use for the log file. If empty string is
# given, it defaults to the platform-preferred encoding.
log_file_encoding = ""
参考/API#
astropy.logger模块#
此模块基于内置的日志记录模块定义日志记录类。
备注
此模块用于内部 astropy
用法。为了在其他包中使用,我们建议改为实现您自己的记录器。
Classes#
|
的配置参数 |
|
这个类用于设置Astropy日志记录。 |
此异常适用于astropy记录器中发生的各种错误,通常是在激活或停用记录器相关功能时。 |