LoginSignup
0
3

More than 3 years have passed since last update.

[Python]AWS Lambdaから出力したログ(JSON)がCloudWatch Logで出力すると改行される

Posted at

現象

Pythonのログライブラリ logging を使ってJSONの文字列をCloudWatch Logに出力すると改行される
CloudWatch Log画面.png

コード

from logging import getLogger, INFO
from ask_sdk_model import Response

logger = getLogger(__name__)
logger.setLevel(INFO)

# Request and Response Loggers
class RequestLogger(AbstractRequestInterceptor):
    """Log the request envelope."""

    def process(self, handler_input):
        # type: (HandlerInput) -> None
        request = handler_input.request_envelope.request
        logger.info (request)

原因

AWS Lambda の Python 3.7 Runtime 環境では改行コードとしてCR(\n) を含む文字列が出力された場合、行を分割して CloudWatch Logs 上に出力される

回避策

出力したい内容をJSON 文字列に変換し、CRを削除して出力する

コード

#### [追加] jsonライブラリのインポート ###
import json
####
from logging import getLogger, INFO
from ask_sdk_model import Response

logger = getLogger(__name__)
logger.setLevel(INFO)

# Request and Response Loggers
class RequestLogger(AbstractRequestInterceptor):
    """Log the request envelope."""

    def process(self, handler_input):
        # type: (HandlerInput) -> None
        request = handler_input.request_envelope.request

        #### [追加]requestオブジェクトを文字列に変換し、CR(\n)を削除 ####
        request_str = json.dumps(request.__dict__, ensure_ascii=False, indent=2, default=str)
        logger.info (request_str.replace('\n', ''))
        ####

補足

上記、AWSサポートより、提示していただいた方法だが、注意点としてAWS Lambda としては上記のような改行コードの扱いについて一定の出力結果になることを明示的に保証していないとのことなので、将来的には変更される可能性があるとのこと

0
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
3