LoginSignup
0
0

More than 1 year has passed since last update.

Lambda/SAM ログ出力方法 メモ

Posted at
  • Lambdaでのログ出力をsam cliを使って試したのでメモとして残しておく。

事前準備

  • sam プロジェクト作成

    sam init
    

    ※ランタイムはPython3.8を選択。

コード

  • template.yml

    ログレベルを環境変数として設定する

...
	Environment:
        Variables:
          LOG_LEVEL: !Ref LogLevel
...
Parameters:
  LogLevel:
    Type: String
    Default: INFO
  • app.py

    import json
    import logging
    import os
    import requests
    
    def lambda_handler(event, context):
        logger = logging.getLogger()
    
        # ログレベル設定※環境変数から取得
        LOG_LEVEL = os.environ.get('LOG_LEVEL')
        level = logging.getLevelName(LOG_LEVEL)
        logger.setLevel(level)
        # ログフォーマッター
        formatter = logging.Formatter(
            '[%(levelname)s]\t%(asctime)s.%(msecs)dZ\t%(aws_request_id)s\t%(clientip)s\t%(message)s\n',
        '%Y-%m-%dT%H:%M:%S'
        )
        handler = logging.StreamHandler()
        handler.setFormatter(formatter)
        logger.addHandler(handler)
        try:
            ip = requests.get("http://checkip.amazonaws.com/")
            logger.debug('debug test')
            logger.info('info test',extra={'clientip': ip.text.replace("\n", "")})
        except requests.RequestException as e:
            print(e)
            raise e
    
        return {
            "statusCode": 200,
            "body": json.dumps({
                "message": "hello world",
                "location": ip.text.replace("\n", "")
            }),
        }
    
    

動作確認

  • ビルド

    sam build --use-container
    
  • 起動

    sam local start-api
    
  • 呼び出し

    GET /hello HTTP/1.1
    Host: localhost:3000
    Content-Type: application/json
    
  • レスポンス

    {
        "message": "hello world",
        "location": "xxx.xxx.xxx.xxx"
    }
    
  • ログ出力

    [INFO]  2022-03-04T11:41:50.627Z       {AWS_REQUEST_ID}    xxx.xxx.xxx.xxx   info test
    

    ※環境変数が読み込まれデバッグログは出力されない。

参考情報

0
0
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
0