Python Logging: Overriding Log Time

After Python documentation , I try to redefine logging.Formatter.converter to control logging time.
As you can see below - milliseconds were not exceeded (these are current milliseconds).

How did it happen? How can I control milliseconds?

 >>> import logging, datetime >>> formatter = logging.Formatter('%(asctime)s:%(message)s') >>> handler = logging.StreamHandler() >>> handler.setFormatter(formatter) >>> def sim_time(t): ... return datetime.datetime(2000,1,2,3,4,5,678).timetuple() ... >>> formatter.converter = sim_time >>> log = logging.getLogger('test') >>> log.addHandler(handler) >>> log.info('hi') 2000-01-02 03:04:05,898:hi >>> log.info('hi') 2000-01-02 03:04:05,914:hi >>> log.info('hi') 2000-01-02 03:04:05,434:hi 
+2
source share
3 answers

override logging.Formatter.formatTime() instead:

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

If you need this for all the loggers in this process, you can override the class function, but do it right after the first import logging statement that your code encounters:

 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 
+2
source

timetuple() does not use milliseconds, so the ms information contained in the datetime object is lost after calling the method:

 >>> d datetime.datetime(2000, 1, 2, 3, 4, 5, 678) >>> d.timetuple() time.struct_time(tm_year=2000, tm_mon=1, tm_mday=2, tm_hour=3, tm_min=4, tm_sec=5, tm_wday=6, tm_yday=2, tm_isdst=-1) 

Note that this is not a limitation of this particular method, but rather a time.struct_time type .

Bottom line: if you need to override the timestamp, do not go through the time.struct_time object. You could, for example, pass a timestamp already formatted as a string, rather than a fake time. Of course, depending on your needs, there may be better methods.

+1
source

Here is the best example that allows you to replace the time that was generated, since the accepted answer did not actually do this.

 def inSimulatedTime(self,secs=None): global myTimeKeeper try: ts=myTimeKeeper.getCurrentTimeLocal() # returns a datetime.datetime object return ts.timetuple() except Exception as e: #sometimes my timekeeper hasn't been initialized yet. return time.localtime(secs) 

To enable it:

 logging.Formatter.converter=inSimulatedTime 
0
source

Source: https://habr.com/ru/post/1396269/


All Articles