Skip to content

Commit 3bfea1e

Browse files
docs(celery): keep the configured logging in workers with a setup_logging receiver (#46056)
Co-authored-by: Evan Rusackas <evan@preset.io>
1 parent efc57b6 commit 3bfea1e

3 files changed

Lines changed: 204 additions & 0 deletions

File tree

‎docs/admin_docs/configuration/async-queries-celery.mdx‎

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -102,6 +102,42 @@ terminal status arrives by polling or websocket. Embedded guest viewers receive
102102
the same redacted message as synchronous chart requests. If no detail is
103103
available, the chart displays a generic failure message.
104104

105+
## Worker logging
106+
107+
The worker entrypoint, `superset.tasks.celery_app`, calls `create_app()`, so Celery workers and
108+
`celery beat` apply the same `LOGGING_CONFIGURATOR` as the web server. Celery then runs its own
109+
logging setup when the process starts: by default it replaces the handlers of the root logger
110+
with its own text handler (`worker_hijack_root_logger`), and even with that setting disabled in
111+
`CELERY_CONFIG` it still adds a text handler to the `celery.task` logger, through which every
112+
logger created with `celery.utils.log.get_task_logger` writes, and resets the root log level to
113+
the worker's `--loglevel`. If your configurator sets up structured logging, for example JSON
114+
records for a log aggregator, the worker output ends up as a mix of both formats.
115+
116+
Celery skips its logging setup entirely as soon as its `setup_logging` signal has a receiver.
117+
Connect the receiver shipped with Superset from your `superset_config.py`:
118+
119+
```python
120+
from celery.signals import setup_logging
121+
122+
from superset.utils.logging_configurator import keep_configured_logging
123+
124+
setup_logging.connect(keep_configured_logging)
125+
```
126+
127+
`superset_config.py` is imported while `create_app()` builds the application, which happens
128+
before the `worker` or `beat` command sends the signal, so the receiver is in place in time. A
129+
custom `LOGGING_CONFIGURATOR` can connect it from its `configure_logging()` instead.
130+
131+
With the receiver connected, Celery ignores the `--loglevel` and `--logfile` options of
132+
`celery worker` and `celery beat` as well as the `worker_redirect_stdouts` setting: log levels and
133+
destinations come from your logging configuration alone (`LOG_LEVEL`, `ENABLE_TIME_ROTATE` and
134+
the related settings, or your own configurator), and plain `print()` output is written to the
135+
process' standard output instead of the log. Records from Celery task loggers are formatted by
136+
your handlers as well, so the task name and id that Celery's own task formatter adds are only
137+
included when your formatter provides them (for example `celery.app.log.TaskFormatter`). Newer
138+
Celery versions add a `worker_skip_logging_setup` setting with the same effect; once your Celery
139+
has it, set it in `CELERY_CONFIG` instead of connecting the receiver.
140+
105141
## Celery Flower
106142

107143
Flower is a web based tool for monitoring the Celery cluster which you can install from pip:

‎superset/utils/logging_configurator.py‎

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
import abc
1818
import logging
1919
from logging.handlers import TimedRotatingFileHandler
20+
from typing import Any
2021

2122
import flask.app
2223
import flask.config
@@ -63,3 +64,44 @@ def configure_logging(
6364
logging.getLogger().addHandler(handler)
6465

6566
logger.debug("logging was configured successfully")
67+
68+
69+
def keep_configured_logging(**kwargs: Any) -> None: # pylint: disable=unused-argument
70+
"""
71+
Receiver for Celery's ``setup_logging`` signal.
72+
73+
Celery configures logging when a worker or beat process starts, after the
74+
application, and with it ``LOGGING_CONFIGURATOR``, has been imported. By
75+
default it replaces the handlers of the root logger with its own text handler
76+
(``worker_hijack_root_logger``). Even with that setting off it still sets the
77+
root level to the worker's ``--loglevel`` (``WARNING`` when the option is
78+
omitted), adds a text handler to the ``celery.task`` logger and stops that
79+
logger from propagating, so records from ``celery.utils.log.get_task_logger``
80+
bypass the configured handlers, and adds a text handler to the
81+
``multiprocessing`` logger.
82+
83+
Celery skips that setup entirely as soon as this signal has a receiver, so
84+
connecting this function keeps the configured logging as is::
85+
86+
from celery.signals import setup_logging
87+
88+
from superset.utils.logging_configurator import keep_configured_logging
89+
90+
setup_logging.connect(keep_configured_logging)
91+
92+
Do this in ``superset_config.py``, or in a custom ``LoggingConfigurator``'s
93+
``configure_logging()``; both run inside ``create_app()``, before the
94+
``worker`` or ``beat`` command sends the signal. In exchange the ``--loglevel``
95+
and ``--logfile`` options and the ``worker_redirect_stdouts`` setting are not
96+
applied: levels and destinations come from the logging configuration alone,
97+
and records from task loggers carry Celery's task name and id only when the
98+
configured formatter adds them. The ``loglevel`` and ``logfile`` Celery passes
99+
here are ignored on purpose: the command-line default (``WARNING``) cannot be
100+
told apart from an explicit ``-l WARNING``.
101+
102+
The receiver has to stay trivial: Celery sends the signal again in every
103+
prefork child when ``--logfile`` contains ``%i``, and an exception raised by
104+
a receiver is logged and swallowed while logging still counts as handled.
105+
106+
:see: https://docs.celeryq.dev/en/stable/userguide/signals.html#setup-logging
107+
"""
Lines changed: 126 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,126 @@
1+
# Licensed to the Apache Software Foundation (ASF) under one
2+
# or more contributor license agreements. See the NOTICE file
3+
# distributed with this work for additional information
4+
# regarding copyright ownership. The ASF licenses this file
5+
# to you under the Apache License, Version 2.0 (the
6+
# "License"); you may not use this file except in compliance
7+
# with the License. You may obtain a copy of the License at
8+
#
9+
# http://www.apache.org/licenses/LICENSE-2.0
10+
#
11+
# Unless required by applicable law or agreed to in writing,
12+
# software distributed under the License is distributed on an
13+
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14+
# KIND, either express or implied. See the License for the
15+
# specific language governing permissions and limitations
16+
# under the License.
17+
"""Tests for the Celery part of ``superset.utils.logging_configurator``."""
18+
19+
import logging
20+
import os
21+
import sys
22+
import warnings
23+
from collections.abc import Iterator
24+
from pathlib import Path
25+
from unittest import mock
26+
27+
import pytest
28+
from celery import Celery
29+
from celery.app.log import Logging
30+
from celery.signals import setup_logging
31+
32+
from superset.utils.logging_configurator import keep_configured_logging
33+
34+
# Loggers that Celery's logging setup touches
35+
LOGGERS = ("", "celery", "celery.task", "multiprocessing")
36+
37+
38+
def _logger_state(name: str) -> tuple[list[logging.Handler], int, bool]:
39+
logger = logging.getLogger(name)
40+
return list(logger.handlers), logger.level, bool(logger.propagate)
41+
42+
43+
@pytest.fixture
44+
def celery_instance(monkeypatch: pytest.MonkeyPatch) -> Iterator[Celery]:
45+
"""
46+
A Celery app whose logging setup can run in this process, plus a reset of
47+
everything that setup touches once the test is over.
48+
"""
49+
# Celery configures logging once per process and remembers that in a class
50+
# attribute; start from a clean slate and leave no receivers behind.
51+
monkeypatch.setattr(Logging, "_setup", False)
52+
monkeypatch.setattr(setup_logging, "receivers", [])
53+
monkeypatch.setattr(sys, "stdout", sys.stdout)
54+
monkeypatch.setattr(sys, "stderr", sys.stderr)
55+
before = {name: _logger_state(name) for name in LOGGERS}
56+
# A known root level, so the tests can tell whether Celery changed it
57+
logging.getLogger().setLevel(logging.INFO)
58+
59+
app = Celery("superset_logging_test", set_as_current=False)
60+
# The setting people reach for first. It does not keep Celery from adding
61+
# its task-logger handler or from changing the root level.
62+
app.conf.worker_hijack_root_logger = False
63+
64+
# ``Logging.setup()`` also exports CELERY_LOG_* / _MP_FORK_* variables for
65+
# prefork children and adds warning filters; undo both.
66+
with mock.patch.dict(os.environ), warnings.catch_warnings():
67+
yield app
68+
69+
for name, (handlers, level, propagate) in before.items():
70+
logger = logging.getLogger(name)
71+
# Drop what Celery added and keep what was there, including the capture
72+
# handlers pytest attaches to the root logger around every test phase.
73+
for handler in list(logger.handlers):
74+
if handler not in handlers:
75+
logger.removeHandler(handler)
76+
logger.setLevel(level)
77+
logger.propagate = propagate
78+
79+
80+
def test_celery_reconfigures_logging_by_default(celery_instance: Celery) -> None:
81+
"""
82+
Without a receiver Celery still adds a handler to the task logger and
83+
overrides the root level, even with ``worker_hijack_root_logger`` off.
84+
"""
85+
task_logger = logging.getLogger("celery.task")
86+
task_handlers = list(task_logger.handlers)
87+
88+
handled = celery_instance.log.setup(loglevel=logging.ERROR, logfile=None)
89+
90+
assert not handled
91+
assert logging.getLogger().level == logging.ERROR
92+
assert len(task_logger.handlers) == len(task_handlers) + 1
93+
assert not task_logger.propagate
94+
95+
96+
def test_receiver_keeps_configured_logging(
97+
celery_instance: Celery,
98+
tmp_path: Path,
99+
) -> None:
100+
"""
101+
With the receiver connected, Celery leaves every logger as the application
102+
configured it, opens no log file and skips the stdout/stderr redirection.
103+
"""
104+
setup_logging.connect(keep_configured_logging)
105+
setup_logging.connect(keep_configured_logging) # a second connect is a no-op
106+
assert len(setup_logging.receivers) == 1
107+
108+
before = {name: _logger_state(name) for name in LOGGERS}
109+
stdout, stderr = sys.stdout, sys.stderr
110+
logfile = tmp_path / "worker.log"
111+
112+
# What ``celery worker -l ERROR --logfile ...`` and ``celery beat`` run on
113+
# start-up; a prefork child runs it again when the file name contains ``%i``
114+
for _ in range(2):
115+
celery_instance.log.already_setup = False
116+
handled = celery_instance.log.setup(
117+
loglevel=logging.ERROR, logfile=str(logfile), redirect_stdouts=True
118+
)
119+
# Celery hands back (receiver, return value) pairs; an exception raised
120+
# by the receiver would show up here instead of None
121+
assert handled == [(keep_configured_logging, None)]
122+
123+
assert {name: _logger_state(name) for name in LOGGERS} == before
124+
assert not logfile.exists()
125+
assert sys.stdout is stdout
126+
assert sys.stderr is stderr

0 commit comments

Comments
 (0)