4

如何从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

4

1 回答 1

3

这可以使用线程安全队列来完成

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
于 2013-03-22T13:59:16.327 回答