Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I define a different logger for an imported module in Python?

Tags:

python

logging

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.

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.

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?

I tried reading the module page and the HOWTO for logging, but could not find an answer to this.

like image 524
ShankarG Avatar asked Aug 03 '13 12:08

ShankarG


1 Answers

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)

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)

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

like image 135
Vinay Sajip Avatar answered Sep 29 '22 10:09

Vinay Sajip