如何在Python中为导入的模块定义其他记录器? [英] How do I define a different logger for an imported module in Python?
问题描述
我在Python脚本中使用高级Python计划程序.主程序通过使用我想要的日志文件名调用logging.basicConfig来定义日志.该日志也设置为"DEBUG"作为日志记录级别,因为这是我目前对脚本的需求.
I'm using Advanced Python Scheduler in a Python script. The main program defines a log by calling logging.basicConfig with the file name of the log that I want. This log is also set to "DEBUG" as the logging level, since that's what I need at present for my script.
不幸的是,由于logging.basicConfig是以这种方式设置的,因此apscheduler会将其日志条目写入同一日志文件.其中有很多,尤其是因为我有一个预定的任务每分钟运行一次.
Unfortunately, because logging.basicConfig has been set up in this manner, apscheduler writes its log entries to the same log file. There are an awful lot of these, especially since I have one scheduled task that runs every minute.
在将日志文件用于自己的脚本时,是否可以将apscheduler的日志输出重定向到另一个日志文件(无需更改apscheduler的代码)?IE.有没有办法在我的脚本中更改每个模块输出的文件名?
Is there any way to redirect apscheduler's log output to another log file (without changing apscheduler's code) while using my log file for my own script? I.e. is there a way to change the file name for each module's output within my script?
我尝试阅读模块页面和HOWTO日志记录,但找不到答案.
I tried reading the module page and the HOWTO for logging, but could not find an answer to this.
推荐答案
将 apscheduler
的记录器级别设置为所需的值(例如, WARNING
,以避免看到DEBUG和INFO来自 apscheduler
的消息,如下所示:
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)
您仍然会收到有关 WARNING
和更高严重性的消息.要将邮件从 apscheduler
定向到一个单独的文件中,请使用
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)
确保上述代码仅被调用一次(否则,您将添加多个 FileHandler
实例-可能不是您想要的).
Ensure the above code is only called once (otherwise you will add multiple FileHandler
instances - probably not what you want).
这篇关于如何在Python中为导入的模块定义其他记录器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!