1

无法将标准输出重定向到 Celery 中的另一个记录器,我使用特殊的处理程序为 Celery 创建了特殊的记录器对象。我想捕获执行任务时发生的所有异常。我在 celery 中添加 setup_logging 信号的处理程序,以安装我自己的记录器:

import sys
import logging.config

from pika.adapters import BlockingConnection
from pika.connection import ConnectionParameters
from pika import BasicProperties

from celery.signals import setup_logging, after_setup_logger


class RabbitMqHandler(logging.Handler):
    '''
    Special logging handler which stores log messages in RabbitMq server
    It can used for async delivering message to clients
    '''

    HOST = 'localhost'
    QUEUE = 'hermes.standard'

    def emit(self, record):
        con = BlockingConnection(ConnectionParameters(self.HOST))
        # Open the channel
        channel = con.channel()

        # Declare the queue
        channel.queue_declare(queue=self.QUEUE, durable=True,
                              exclusive=False, auto_delete=False)

        channel.basic_publish(exchange='', routing_key=self.QUEUE, body=self.format(record)) #','.join(dir(record)))
        con.close()


LOGGING = {
    'version': 1,
    'disable_existing_loggers': True,
    'formatters': {
        'verbose': {
            'format': '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s'
        },
        'simple': {
            'format': '%(levelname)s %(message)s'
        },
        'timed': {
            'format': '[%(asctime)s: %(levelname)s] %(message)s'
        },
    },
    'handlers': {
        'null': {
            'level':'DEBUG',
            'class':'django.utils.log.NullHandler',
        },
        'console':{
            'level':'DEBUG',
            'class':'logging.StreamHandler',
            'formatter': 'timed'
        },
        'rabbit': {
            'level': 'INFO',
            'class': 'logconfig.RabbitMqHandler',
            'formatter': 'timed'
        },
        'celery': {
            'level': 'ERROR',
            'class': 'logging.FileHandler',
            'filename': '1.log',
            'formatter': 'timed',
            }
    },
    'loggers': {
        'celery': {
            'handlers': ['celery'],
            'level': 'INFO',
        },
        'hermes': {
            'handlers': ['console', 'rabbit'],
            'level': 'INFO',
        }
    }
}

from celery.log import LoggingProxy

@setup_logging.connect
def setup_logconfig(**kwargs):
    logging.config.dictConfig(LOGGING)
    #return logging.getLogger('hermes')

我自己的名为“hermes”的记录器工作正常,但所有异常都发生了捕获标准芹菜的记录器名称=芹菜。我试图用设置覆盖:

CELERY_REDIRECT_STDOUTS =假

但它也不起作用。所有例外都适用于标准 celery 记录器。

4

0 回答 0