如何在Python中为导入的模块定义不同的记录器?

Sha*_*arG 5 python logging

我在Python脚本中使用Advanced Python Scheduler.主程序通过使用我想要的日志的文件名调用logging.basicConfig来定义日志.此日志也设置为"DEBUG"作为日志记录级别,因为这是我目前需要的脚本.

不幸的是,因为logging.basicConfig已经以这种方式设置,所以apscheduler将其日志条目写入同一个日志文件.其中有很多这些,特别是因为我有一个每分钟运行一次的计划任务.

有没有办法将我的日志文件用于我自己的脚本时,将apscheduler的日志输出重定向到另一个日志文件(不更改apscheduler的代码)?即有没有办法在我的脚本中更改每个模块输出的文件名?

我尝试阅读模块页面和HOWTO进行日志记录,但无法找到答案.

Vin*_*jip 5

Set the logger level for apscheduler to your desired value (e.g. WARNING to avoid seeing DEBUG and INFO messages from apscheduler like this:

logging.getLogger('apscheduler').setLevel(logging.WARNING)
Run Code Online (Sandbox Code Playgroud)

You will still get messages for WARNING and higher severities. To direct messages from apscheduler into a separate file, use

aplogger = logging.getLogger('apscheduler')
aplogger.propagate = False
aplogger.setLevel(logging.WARNING)    # or whatever
aphandler = logging.FileHandler(...)  # as per what you want
aplogger.addHandler(aphandler)
Run Code Online (Sandbox Code Playgroud)

Ensure the above code is only called once (otherwise you will add multiple FileHandler instances - probably not what you want).