python - 在 apscheduler 中捕获日志

标签 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 中的消息?

最佳答案

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

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

关于python - 在 apscheduler 中捕获日志,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15392058/

相关文章:

python - 字符串与下一个非数字字符之间的字符串

python - tktable 中的单元格为空白而不显示内容

python - apscheduler 间隔任务未运行

python - 随着 NoSQL 的兴起,现在没有任何模型的 webapp 是否更常见?

python - 分析 Tornado/Asyncio 时哪些函数是免费的?

php - 如何注销特定用户 session (php 和 mysql)

c# - 日志文件的分析、预处理或后处理

react-native - React Native 中客户端日志记录和错误处理的最佳实践

flask - 如何在现有 Flask 应用中使用 Flask-APScheduler

APScheduler - 作业未执行