0

Am new to pytest and am trying to setup logging

I have the following code in my conftest.py file

def pytest_logger_config(logger_config):
    logger_config.add_loggers([log_fname], stdout_level=logging.INFO)
    logger_config.set_log_option_default(log_fname)

Another file logger.py

Log = logging.getLogger(log_fname)

on writing Log.info("message")

I see the log written as
00:16.748 inf logfile_00_00_13_10_2020.log: message

Not sure how or where this format is defined.

Can we customise it to a format like

log_file_format = %(levelname)s: %(asctime)s (%(filename)s:%(lineno)s %(message)s)

INFO: 2020-10-13 00:00:45 (.py:<line_no>) message

Where should be the right place to define this?

user1007839
  • 23
  • 2
  • 9

1 Answers1

0

In the pytest.ini file:

[pytest]
log_format =  %(levelname)s: %(asctime)s (%(filename)s:%(lineno)s %(message)s)
log_date_format = %Y-%m-%d %H:%M:%S

You also don't need to add your own log configuration directly into test code, just enable pytest's live logging features (documented here).

wim
  • 338,267
  • 99
  • 616
  • 750
  • Thanks wim, I had tried this as well but the output file for this prints ANSI **[32mINFO [0m ** is there a way to disable that? – user1007839 Oct 12 '20 at 20:11
  • 1
    Use a terminal emulator that supports ANSI colors, or disable them `export PYTEST_ADDOPTS="--color=no"` – wim Oct 12 '20 at 21:12
  • Working fine on the console. Seeing these when content is written to a file, for allure report. – user1007839 Oct 12 '20 at 21:20
  • 1
    That much is out of scope of Python itself, and the behavior depends how you are writing to file, whether going through any shell pipes, etc .. – wim Oct 12 '20 at 21:30