捕获apscheduler中的日志

时间:2013-03-13 17:16:03

标签: python logging apscheduler

如何从apscheduler中捕获作业中的日志?

假设,我有以下工作

@sched.interval_schedule(hours=3)
def some_job():
    log.info('I was here.')
    log.info('And here.')

和听众

sched.add_listener(job_listener,
                       events.EVENT_JOB_EXECUTED |
                       events.EVENT_JOB_MISSED |
                       events.EVENT_JOB_ERROR)

def job_listener(event):
    # how do I get the logged messages here?

如何访问job_listener中的邮件?

1 个答案:

答案 0 :(得分:4)

这可以使用线程安全队列

来完成
import logging

import Queue
from apscheduler import events
from apscheduler.scheduler import Scheduler
import time


#logging.basicConfig(level=logging.INFO,format='%(asctime)s : %(name)s : %(levelname)s : %(module)s.%(funcName)s(%(lineno)d) : %(thread)d %(threadName)s: %(message)s')

#enable logger to see exceptions caught by apscheduler
logging.basicConfig()



q = Queue.Queue()

sched = Scheduler()


@sched.interval_schedule(seconds=1)
def some_job():
    msg = "Decorated job : %s" % time.time()
    print msg
    logging.info(msg)
    q.put(msg)
    q.put("message 2")


def job_listener(event):
    #print str(event)
    while not q.empty():
        get_ = "msg from job '%s': '%s'" % (event.job, q.get())
        print get_
        logging.info(get_)


sched.add_listener(job_listener,
                   events.EVENT_JOB_EXECUTED |
                   events.EVENT_JOB_MISSED |
                   events.EVENT_JOB_ERROR)

config = {'apscheduler.jobstores.file.class': 'apscheduler.jobstores.shelve_store:ShelveJobStore',
          'apscheduler.jobstores.file.path': '/temp/dbfile'}

sched.configure(config)


sched.start()

q.join()
while True:
    pass

输出:

Decorated job : 1363960621.39
msg from job 'some_job ...: 'Decorated job : 1363960621.39'
msg from job 'some_job ...': 'message 2'
Decorated job : 1363960622.4
msg from job 'some_job ...: 'Decorated job : 1363960622.4'
msg from job 'some_job ...: 'message 2'
Decorated job : 1363960623.39