[Python] Is there a way to fully customize log file format?

Discussão em 'Python' iniciado por Stack, Junho 19, 2025.

  1. Stack

    Stack Membro Participativo

    I would like to keep pytest log format as simple as possible, such as

    16:00:20 test_numbers.py::test_if_even PASSED
    16:00:21 test_if_less_then_17 ::test_if_even FAILED AssertionError:
    def test_is_not_devisible_by_5(generate_number):
    num = generate_number
    > assert num % 3 != 0, "The number is devisible by 3"
    E AssertionError: The number is devisible by 3
    E assert (15 % 3) != 0


    I configured pytest.ini

    [pytest]
    log_file_level = DEBUG
    log_file_format="%(asctime)s %(levelname)s: %(message)s"


    and launch pytest with

    pytest . --log-file $(date '+%F_%H_%M_%S').log


    Now I get:


    1. with log_file_level = ERROR option -- only messages for failed tests

      16:35:52 ERROR: test status is FAILED (test_numbers.py::test_is_not_devisible_by_5): AssertionError

    2. with log_file_level = INFO option -- unwanted "End..." and "Start..." strings

      "16:27:31 INFO: ------------------Start: test_numbers.py::test_if_less_then_10------------------"
      "16:27:31 ERROR: test status is FAILED (test_numbers.py::test_if_less_then_10): AssertionError"
      "16:27:31 INFO: -------------------End: test_numbers.py::test_if_less_then_10-------------------"

    3. with log_file_level = DEBUG option -- even more redundant information

      )
      "16:30:01 INFO: ----------------------Start: test_numbers.py::test_if_even----------------------"
      "16:30:01 ERROR: test status is FAILED (test_numbers.py::test_if_even): AssertionError"
      "16:30:01 DEBUG: test_numbers.py::test_if_even -> generate_number = 15

      def test_if_even(generate_number):
      num = generate_number
      > assert num % 2 == 0, "The number is not even"
      E AssertionError: The number is not even
      E assert (15 % 2) == 0

      test_numbers.py:14: AssertionError"
      "16:30:01 INFO: -----------------------End: test_numbers.py::test_if_even-----------------------"

    Is there a way to get desired format?

    Continue reading...

Compartilhe esta Página