Skip to content

Commit 7f467eb

Browse files
symonknicoddemus
andauthored
Create subdirectories if they do not exist when specified for log file (#7468)
Co-authored-by: Bruno Oliveira <[email protected]>
1 parent 7b65b23 commit 7f467eb

File tree

3 files changed

+16
-0
lines changed

3 files changed

+16
-0
lines changed

changelog/7467.improvement.rst

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
``--log-file`` CLI option and ``log_file`` ini marker now create subdirectories if needed.

src/_pytest/logging.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -531,11 +531,17 @@ def __init__(self, config: Config) -> None:
531531
# File logging.
532532
self.log_file_level = get_log_level_for_setting(config, "log_file_level")
533533
log_file = get_option_ini(config, "log_file") or os.devnull
534+
if log_file != os.devnull:
535+
directory = os.path.dirname(os.path.abspath(log_file))
536+
if not os.path.isdir(directory):
537+
os.makedirs(directory)
538+
534539
self.log_file_handler = _FileHandler(log_file, mode="w", encoding="UTF-8")
535540
log_file_format = get_option_ini(config, "log_file_format", "log_format")
536541
log_file_date_format = get_option_ini(
537542
config, "log_file_date_format", "log_date_format"
538543
)
544+
539545
log_file_formatter = logging.Formatter(
540546
log_file_format, datefmt=log_file_date_format
541547
)

testing/logging/test_reporting.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55

66
import pytest
77
from _pytest.capture import CaptureManager
8+
from _pytest.config import ExitCode
89
from _pytest.pytester import Testdir
910
from _pytest.terminal import TerminalReporter
1011

@@ -1152,3 +1153,11 @@ def test_bad_log(monkeypatch):
11521153
)
11531154
result = testdir.runpytest()
11541155
result.assert_outcomes(passed=1)
1156+
1157+
1158+
def test_log_file_cli_subdirectories_are_successfully_created(testdir):
1159+
path = testdir.makepyfile(""" def test_logger(): pass """)
1160+
expected = os.path.join(os.path.dirname(str(path)), "foo", "bar")
1161+
result = testdir.runpytest("--log-file=foo/bar/logf.log")
1162+
assert "logf.log" in os.listdir(expected)
1163+
assert result.ret == ExitCode.OK

0 commit comments

Comments
 (0)