1
1

More than 1 year has passed since last update.

[AWS Lambda Powertools Python]ログに実行ファイル名を含める

Posted at

経緯

AWS Lambda Powertools Python [^1] のLogger機能はとても強力です。

ログを出力する目的は色々ありますが、デバッグ時のように処理を追いかける場面では「そのログがどこで出力されたのか」をまず知りたいのではないでしょうか。

デフォルト設定の出力では、 location 属性として出力されています。
下記の例だと、 get_users 関数内で、そのソースコードの40行目で出力したログであることがわかります。

{
    "level": "DEBUG",
    "location": "get_users:40",
    "message": "...

シンプルな構造であれば「ああ、get_users()はあそこだな」とわかるでしょうが、いくつものファイルで構成されている場合は「get_users()ってどこの?」となりませんか?

出力内容の変更

出力内容をカスタマイズ可能です。(ドキュメントにも記載されています)

location を指示することで書式がオーバーライドされます。

下記の例では先頭へfilename を記述することで、handler.pyget_users 関数、位置は40行目、ということがわかります。迷わずソースコードを開けます。

from aws_lambda_powertools import Logger

location_format = '%(filename)s:%(funcName)s:%(lineno)d'
logger = Logger(location=location_format)
{
    "level": "DEBUG",
    "location": "handler.py:get_users:40",
    "message": "...

参考

下記ソースコードあたりが該当します。

省略時の書式... _build_default_keys() を参照すると下記のようです

"%(funcName)s:%(lineno)d"

指定可能な属性値...RESERVED_LOG_ATTRS を参照します。

RESERVED_LOG_ATTRS = (
    "name",
    "msg",
    "args",
    "level",
    "levelname",
    "levelno",
    "pathname",
    "filename",
    "module",
    "exc_info",
    "exc_text",
    "stack_info",
    "lineno",
    "funcName",
    "created",
    "msecs",
    "relativeCreated",
    "thread",
    "threadName",
    "processName",
    "process",
    "asctime",
    "location",
    "timestamp",
)
1
1
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
1
1