Search code examples
pythonloggingpytestconftest

Is there a way to customise the format for logging in pytest from conftest.py


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?


Solution

  • 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).