admin管理员组文章数量:1399906
I'm trying to call a Management Command with call_command
within a Celery task. The management command writes logs in different ways: through print statements, self.stdout.write
, or using the logger defined at the script's module level.
I want to capture all these log messages in the Celery logger to make them visible in Datadog. Is this possible?
I tried the worker_redirect_stdouts_level
option, but it impacts the global Celery logging configuration.
I'm trying to call a Management Command with call_command
within a Celery task. The management command writes logs in different ways: through print statements, self.stdout.write
, or using the logger defined at the script's module level.
I want to capture all these log messages in the Celery logger to make them visible in Datadog. Is this possible?
I tried the worker_redirect_stdouts_level
option, but it impacts the global Celery logging configuration.
1 Answer
Reset to default 0You can use call_command()
with StringIO
to capture stdout within a Celery task and redirect it to the Celery logger
from celery import shared_task
from django.core.management import call_command
import io
import logging
logger = logging.getLogger(__name__)
@shared_task
def task_that_runs_your_management_command():
output = io.StringIO() # To capture stdout
try:
call_command("your_command", stdout=output, stderr=output)
except Exception as e:
logger.exception("Error while executing management command")
# Log the captured output
command_output = output.getvalue()
if command_output:
logger.info("Management Command Output:\n%s", command_output)
本文标签: pythonCalling a Django Management Command from a Celery Task and Redirecting LogsStack Overflow
版权声明:本文标题:python - Calling a Django Management Command from a Celery Task and Redirecting Logs - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744168837a2593678.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论