21
18

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

AWS Lambda の CloudWatch Logs かんたんログ出力 (Python3.6)

Last updated at Posted at 2018-08-12

AWS Lambdaで、自作のログを手間を掛けずに超簡単に出力したいならば、
難しいライブラリ等を使わなくても、print を使えば出来ます。

ログ出力サンプルコード

Lambda
from datetime import datetime 

# ログ出力関数
def logging(errorLv, lambdaName, errorMsg):
    loggingDateStr=(datetime.now()).strftime('%Y/%m/%d %H:%M:%S')
    print(loggingDateStr + " " + lambdaName + " [" + errorLv + "] " + errorMsg)
    return

# lambda_handler
def lambda_handler(event, context):
    logging("info", context.function_name, "実行開始")
    logging("error", context.function_name, "エラーログテスト")

ログ出力サンプル

ログはCloudWatch Logsに出力されます。

sample
2018/08/11 23:02:26 loggingTest [info] 実行開始
2018/08/11 23:02:26 loggingTest [error] エラーログテスト

サンプルコードのポイント

  • Pythonの print でCloudWatch Logsにログを書き込めますので、利用します。
  • print の引数の文字列でログのフォーマットを組み立てます。
  • lambda_handlerの context.function_name で関数名を取れるので、実行元の情報をログ出力する場合に利用します。

最後に

これだけで、簡単にログを出力できます。
ログのフォーマットをお好みで変更してください。
フォーマットの変更は print の引数の文字列を変えるだけですから、楽勝です。

21
18
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
21
18

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?