Created
November 8, 2019 18:48
-
-
Save wanghq/7af145e92884f78fdb50e0de93c05d06 to your computer and use it in GitHub Desktop.
演示如何使用logger输出结构化的日志,并且保留RequestId
This file contains 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
# -*- coding: utf-8 -*- | |
import json | |
import os | |
import logging | |
import re | |
# 演示如何使用logger输出结构化的日志,并且保留RequestId | |
# Sample output | |
# FunctionCompute python3 runtime inited. | |
# FC Invoke Start RequestId: a567f45b-cf83-4436-96a5-bafad61e1c28 | |
# {"time":"2019-11-08 18:35:12,170.170Z", "requestId": "a567f45b-cf83-4436-96a5-bafad61e1c28", "level": "INFO", "detail": "{"message": "message 1", "foo": "bar", "bar": "baz", "num": 123, "fnum": 123.456}"} | |
# nullFC Invoke End RequestId: a567f45b-cf83-4436-96a5-bafad61e1c28 | |
class StructuredMessage(object): | |
def __init__(self, message, **kwargs): | |
self.message = message | |
self.kwargs = kwargs | |
def __str__(self): | |
kv = {} | |
kv['message'] = self.message | |
kv.update(self.kwargs) | |
return json.dumps(kv) | |
_ = StructuredMessage # optional, to improve readability | |
logger = logging.getLogger() | |
lh = logger.handlers.pop() | |
lh.setFormatter(logging.Formatter( | |
'{"time":"%(asctime)s.%(msecs)03dZ", "requestId": "%(fc_request_id)s", "level": "%(levelname)s", "detail": %(message)s}', '%Y-%m-%dT%H:%M:%S')) | |
logger.addHandler(lh) | |
def handler(event, context): | |
logging.info(_('message 1', foo='bar', bar='baz', num=123, fnum=123.456)) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment