简体   繁体   English

如何在ipython会话中完全重置Python stdlib日志记录模块?

[英]How to completely reset Python stdlib logging module in an ipython session?

I'd like to make repeated calls to Python scripts using %run in an ipython session, and for each of those scripts to log based on cmdline arguments passed via %run. 我想在ipython会话中使用%run重复调用Python脚本,并根据通过%run传递的cmdline参数对每个脚本进行日志记录。

For example while debugging cmd.py I might over time want to run: 例如,在调试cmd.py时,我可能会想要运行:

%run cmd.py
... logs with default behavior, e.g. to STDERR with root level WARN

%run cmd.py --log_level DEBUG --log_file /tmp/cmd.out
... logs with root level DEBUG to a file

%run cmd.py --log_level ERROR

Unfortunately this is difficult because the logging state created by logging.basicConfig persists after the first %run command (as is more generally true of all modules, and often desirable when using %run). 不幸的是,这很困难,因为logging.basicConfig创建的日志记录状态在第一个%run命令之后仍然存在(对于所有模块更常见,并且在使用%run时通常是可取的)。

I realize that in full generality a series of %run commands like above will not be the same as running each command in a new process. 我意识到完全通用性如上所述的一系列%run命令与在新进程中运行每个命令不同。 However, it would be very convenient if things like the log_level and log_file could be re-initialized. 但是,如果可以重新初始化log_level和log_file之类的东西,那将非常方便。

I've tried something like this in cmd.py: 我在cmd.py中尝试过类似的东西:

import logging_config  # parse logging config from sys.argv
reload(logging_config) # re-parse cmdline if using %run multiple times

and logging_config.py does (condensed): 和logging_config.py确实(浓缩):

if logging_initialized:
    logging.getLogger().setLevel(lvl)
else:
    logging.basicConfig(level=lvl)
    logging_initialized = True

It works for simple cases but not if cmd.py imports libraries that also use logging. 它适用于简单的情况,但如果cmd.py导入也使用日志记录的库则不行。 I've also experimented with logging.shutdown() (called at conclusion of each cmd.py) but that does not seem to help. 我也尝试过logging.shutdown()(在每个cmd.py结束时调用),但这似乎没有帮助。

Don't use basicConfig() for this style of usage - it's meant for simple one-off configuration and, as the documentation says, subsequent calls after the first have no effect (it only does anything if the root logger has no handlers). 不要将basicConfig()用于这种使用方式 - 它用于简单的一次性配置,并且正如文档所述,在第一次之后的后续调用没有任何效果(如果根记录器没有处理程序,它只会执行任何操作)。 This will be fine when your script is run from the shell prompt, but not from the interactive interpreter, IPython, IDLE, PythonWin, or other similar environment where the process you're interacting with doesn't exit. 当您的脚本从shell提示符运行时,这将是正常的,但不是来自交互式解释器,IPython,IDLE,PythonWin或其他与您交互的进程不会退出的类似环境。

Instead, use programmatic configuration, or fileConfig() or dictConfig() - these have modes where the completely replace the existing logging configuration with a new one. 相反,使用编程配置或fileConfig()dictConfig() - 这些模式可以完全用新的日志配置替换现有的日志记录配置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM