Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions changelog/7467.improvement.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
``--log-file`` CLI option and ``log_file`` ini marker now create subdirectories if needed.
6 changes: 6 additions & 0 deletions src/_pytest/logging.py
Original file line number Diff line number Diff line change
Expand Up @@ -531,11 +531,17 @@ def __init__(self, config: Config) -> None:
# File logging.
self.log_file_level = get_log_level_for_setting(config, "log_file_level")
log_file = get_option_ini(config, "log_file") or os.devnull
if log_file != os.devnull:
directory = os.path.dirname(os.path.abspath(log_file))
if not os.path.isdir(directory):
os.makedirs(directory)

self.log_file_handler = _FileHandler(log_file, mode="w", encoding="UTF-8")
log_file_format = get_option_ini(config, "log_file_format", "log_format")
log_file_date_format = get_option_ini(
config, "log_file_date_format", "log_date_format"
)

log_file_formatter = logging.Formatter(
log_file_format, datefmt=log_file_date_format
)
Expand Down
9 changes: 9 additions & 0 deletions testing/logging/test_reporting.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@

import pytest
from _pytest.capture import CaptureManager
from _pytest.config import ExitCode
from _pytest.pytester import Testdir
from _pytest.terminal import TerminalReporter

Expand Down Expand Up @@ -1152,3 +1153,11 @@ def test_bad_log(monkeypatch):
)
result = testdir.runpytest()
result.assert_outcomes(passed=1)


def test_log_file_cli_subdirectories_are_successfully_created(testdir):
path = testdir.makepyfile(""" def test_logger(): pass """)
expected = os.path.join(os.path.dirname(str(path)), "foo", "bar")
result = testdir.runpytest("--log-file=foo/bar/logf.log")
assert "logf.log" in os.listdir(expected)
assert result.ret == ExitCode.OK