Skip to content

Commit d5dc5a3

Browse files
committed
refactor: Override dbt logger output stream with StreamLogWriter
1 parent 6ccd803 commit d5dc5a3

File tree

1 file changed

+11
-16
lines changed
  • airflow_dbt_python/operators

1 file changed

+11
-16
lines changed

airflow_dbt_python/operators/dbt.py

Lines changed: 11 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
from contextlib import contextmanager
77
from dataclasses import asdict, is_dataclass
88
from pathlib import Path
9-
from tempfile import NamedTemporaryFile, TemporaryDirectory
9+
from tempfile import TemporaryDirectory
1010
from typing import Any, Iterator, Optional, Union
1111
from urllib.parse import urlparse
1212

@@ -241,23 +241,18 @@ def dbt_s3_hook(self):
241241
def override_dbt_logging(self, dbt_directory: str = None):
242242
"""Override dbt's logger.
243243
244-
dbt logger writes to STDOUT and I haven't found a way
245-
to bubble up to the Airflow command logger. As a workaround,
246-
I set the output stream to a temporary file that is later
247-
read and logged using the command's logger.
244+
We override the output stream of the dbt logger to use Airflow's StreamLogWriter
245+
so that we can ensure dbt logs properly to the Airflow task's log output.
248246
"""
249-
with NamedTemporaryFile(dir=dbt_directory, mode="w+") as f:
250-
with log_manager.applicationbound():
247+
from airflow.utils.log.logging_mixin import StreamLogWriter
251248

252-
log_manager.reset_handlers()
253-
log_manager.set_path(dbt_directory)
254-
log_manager.set_output_stream(f)
255-
256-
yield
257-
258-
with open(f.name) as read_file:
259-
for line in read_file:
260-
self.log.info(line.rstrip())
249+
with log_manager.applicationbound():
250+
log_manager.reset_handlers()
251+
log_manager.set_path(dbt_directory)
252+
log_manager.set_output_stream(
253+
StreamLogWriter(self.log, self.log.getEffectiveLevel())
254+
)
255+
yield
261256

262257
def run_dbt_command(self, args: list[Optional[str]]) -> tuple[RunResult, bool]:
263258
"""Run a dbt command as implemented by a subclass."""

0 commit comments

Comments
 (0)