1

I'm creating some structured logging for my application and I wanna check the output of it. For the logging, I'm using Python default logger and pytests for the tests (unittest is not an option in this project). I wanna assert the output I get from the logging against a fixed text and in order to do it I need to have a fixed datetime. But doesn't matter what I do I can't override the Python Logger datetime. How can I mock the datetime I get from the python logger in order to have a proper test?

Update

It's not a formater that I need, I actually need the expected Datetime as result always when I run the tests. So how many times I call the logger, it will always respond with the same Datetime Value, for instance: 2001-01-01.

Rodrigo Farias Rezino
  • 2,687
  • 3
  • 33
  • 60

2 Answers2

1

Hope it helps.

def sim_time(self, record, datefmt=None):
    return datetime.datetime(2000,1,2,3,4,5,678).strftime('%Y-%m-%d %H:%M:%S,%f')[:-3]

import logging
logging.Formatter.formatTime = sim_time
biozid bostami
  • 664
  • 6
  • 13
0

Create a new formatter

# create formatter
formatter = logging.Formatter("%(asctime)s;%(levelname)s;%(message)s",
                              "%Y-%m-%d %H:%M:%S")

See How to Customize the time format for Python logging?

t3ng1l
  • 895
  • 9
  • 23