aurzenligl / pytest-logger

Pytest plugin configuring handlers for loggers from Python logging module.
MIT License
35 stars 11 forks source link

No way to modify formatter #7

Closed farquet closed 7 years ago

farquet commented 7 years ago

Hi, Would that be possible to add a way to modify the logging handler/formatter from the LoggerConfig object ? From the code, I see no way of modifying the formatter without hacking the private self._loggers in LoggerConfig. Cool plugin by the way !

aurzenligl commented 7 years ago

Sure! Formatter is constructed in _make_handlers before each testcase. Information about format is hardcoded in three places:

a. FORMAT variable:

def _make_handlers(stdoutloggers, fileloggers, item):
    FORMAT = '%(asctime)s %(levelshortname)s %(name)s: %(message)s'
    fmt = Formatter(fmt=FORMAT)

b. asctime: Formatter override for formatTime

class Formatter(logging.Formatter):
# ...
    def formatTime(self, record, datefmt=None):
        ct = record.created - self._start
        dt = datetime.datetime.utcfromtimestamp(ct)
        return dt.strftime("%M:%S.%f")[:-3]  # omit useconds, leave mseconds

c. levelshortname: additional non-standard member of record:

class Formatter(logging.Formatter):
# ...
    def format(self, record):
        record.levelshortname = Formatter.short_level_names.get(record.levelno,
                                                                'l%s' % record.levelno)

If you'd like to modify only #a, you could:

Would you be willing to make a pull-request with the functionality you need?

farquet commented 7 years ago

Thanks for your detailed explanation. I could easily do the PR with those pointers.

Note that instead of passing a format string via a set_format method, I found more convenient/elegant to just pass the whole formatter (hence to a set_formatter method) as one might also want (or not) customize the date format or the short level names.

aurzenligl commented 6 years ago

I cannot see your comment anymore in issue #7. I suppose you may have removed it, noticing that set_formatter_class method allows to change formatting. Anyway - if something is unclear here, let me know.

K.

On 05/31/2018 12:36 AM, Pranesh3944 wrote:

Hi, I want to have the line line number, data and time in the log file created by the pytest logger. Also, I need the format with line number date and time in all the different loggers created in conftest.py. How, do we do that ? Curently the log lines are like this : 00:01.460 inf test_info.log: login is successful where test_info.log is the logger i created in conftest.py

— You are receiving this because you modified the open/close state. Reply to this email directly, view it on GitHub https://github.com/aurzenligl/pytest-logger/issues/7#issuecomment-393341714, or mute the thread https://github.com/notifications/unsubscribe-auth/AHcoVI_zKfSCwtTpEGbm4hSwdjUyVXjXks5t3x7fgaJpZM4QCxcf.