问题描述
如何以编程方式打开芹菜记录?
在终端上,这可以正常工作:
From the terminal, this works fine:
celery worker -l DEBUG
当我调用 get_task_logger(__ name __).debug('hello')
时,可以在终端中看到消息.(正在显示stdout和stderr)我什至可以 import logging
并调用 logger.info('hi')
来查看.(都是工作)
When I call get_task_logger(__name__).debug('hello')
, I can see the message come up in the terminal. (stdout and stderr are being displayed) I can even import logging
and call logger.info('hi')
and see that too. (both work)
但是,在开发任务时,我更喜欢使用测试模块并直接调用task函数,而不是解雇整个工作人员.但是我看不到日志消息.我知道Celery会将所有内容重定向到其内部设备,但是我也想在stdout上查看日志消息.
However, while developing a task, I prefer to use a test module and call the task function directly rather than firing up a whole worker. But I can't see the log messages. I understand that Celery is redirecting everything to its internal apparatus, but I want to see the log messages on the stdout too.
我如何告诉Celery将日志消息的副本发送回stdout?
我已经阅读了许多有关日志记录的在线文章,但是似乎已经淘汰了celery的许多与日志记录相关的配置var,并且从文档中我还不清楚今天支持的路径是什么.
I've read a bunch of online articles about logging but it seems that a number of logging-related configuration vars from celery have been deprecated and it's unclear to me from the docs what is the supported path today.
这里是一个示例模块,该模块创建一个celery对象并尝试记录输出.终端中什么也没显示.
示例 mymodule.py
from celery import Celery
import logging
from celery.utils.log import get_task_logger
app = Celery('test')
app.config_from_object('myfile', True)
get_task_logger(__name__).warn('hello world')
logging.getLogger(__name__).warn('hello world 2')
编辑我知道我可以添加一个处理程序,通过添加一个处理程序将一些输出重定向回终端
EDITI know that I can add a handler to redirect some of the output back to the terminal by adding a handler
log = get_task_logger(__name__)
h = logging.StreamHandler(sys.stdout)
log.addHandler(h)
但是有没有一种芹菜方式"来做到这一点?也许让我也有芹菜格式的文本行.
But is there a "Celery way" to do this? Maybe one that lets me also have the Celery formatted lines of text.
[2014-03-02 15:51:32,949: WARNING] hello world
推荐答案
我一直在寻找相同的问题...
I have been looking at the same issue...
根据 http://docs.celeryproject.org/en/latest/userguide/signals.html#after-setup-logger
在您的 celery.py
文件中使用:
from celery.signals import after_setup_logger
import logging
@after_setup_logger.connect()
def logger_setup_handler(logger, **kwargs ):
my_handler = MyLogHandler()
my_handler.setLevel(logging.DEBUG)
my_formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') #custom formatter
my_handler.setFormatter(my_formatter)
logger.addHandler(my_handler)
logging.info("My log handler connected -> Global Logging")
if __name__ == '__main__':
app.start()
然后,您可以根据需要定义 MyLogHandler()
.
then you can define MyLogHandler()
as you wish.
要将日志发送到STDOUT,您还应该可以使用(我尚未测试过):
To send the logs to STDOUT you should also be able to use (I have not tested it):
my_handler = logging.StreamHandler(sys.stdout)
这篇关于如何以编程方式告诉Celery将所有日志消息发送到stdout或stderr?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!