@m1keil's answer will work for simple cases, but gets cumbersome if you want, for example, to have multiple handlers which format the time in different ways, or if you don't need/want to specify the time every time you make a logging call, etc. Here is a solution which is slightly more complicated, but is the "more correct way", and integrates better with the logging system's normal timestamp handling:
First, you need to create a log filter (filters have the ability to modify log records that pass through loggers they're attached to):
class TimestampFilter (logging.Filter):
"""
This is a logging filter which will check for a `timestamp` attribute on a
given LogRecord, and if present it will override the LogRecord creation time
to be that of the timestamp (specified as a time.time()-style value).
This allows one to override the date/time output for log entries by specifying
`timestamp` in the `extra` option to the logging call.
"""
def filter(self, record):
if hasattr(record, 'timestamp'):
record.created = record.timestamp
return True
Then, simply create an instance of the filter and add it to an appropriate logger instance:
logger = logging.getLogger(__name__)
filter = TimestampFilter()
logger.addFilter(filter)
Then when you want to override the date/time of a log entry, when making the logging call, supply a timestamp in extra
:
my_timestamp = time.time() + 86400 # Let's pretend it's tomorrow already
logger.warn("I am a warning from the future!", extra={'timestamp': my_timestamp})