Last active
February 8, 2018 10:05
-
-
Save gciotta/a3941179b9283e09ae7b1db61a58c876 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# | |
# This formatter creates log entries in this format: | |
# {"message": "my message", "severity": "INFO", "timestamp": {"seconds": 1518105845000, "nanos": 252}} | |
# | |
class StackdriverJSONFormatter(jsonlogger.JsonFormatter): | |
FORMAT_STRING = "{message}" | |
@staticmethod | |
def get_timestamp_dict(when=None): | |
"""Converts a datetime.datetime to integer milliseconds since the epoch. | |
Requires special handling to preserve microseconds. | |
Args: | |
when: | |
A datetime.datetime instance. If None, the timestamp for 'now' | |
will be used. | |
Returns: | |
Integer time since the epoch in milliseconds. If the supplied 'when' is | |
None, the return value will be None. | |
""" | |
if when is None: | |
when = datetime.datetime.utcnow() | |
ms_since_epoch = float(time.mktime(when.utctimetuple()) * 1000.0) | |
return { | |
'seconds': int(ms_since_epoch), | |
'nanos': int(when.microsecond / 1000.0), | |
} | |
def add_fields(self, log_record, record, message_dict): | |
super().add_fields(log_record, record, message_dict) | |
log_record['severity'] = record.levelname | |
log_record['timestamp'] = self.get_timestamp_dict() | |
log_record['message'] = self.FORMAT_STRING.format( | |
message=record.message, | |
filename=record.filename, | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment