LoginSignup
6
5

More than 3 years have passed since last update.

Google Cloud Functionsのログ出力(とハマったこと)

Last updated at Posted at 2020-07-08

やりたいこと

やったこと

  • google-cloud-loggingを使う
    • requirements.txtに google-cloud-logging==1.14.0 を追記
# Imports the Google Cloud client library
import logging
from google.cloud import logging as glogging

client = glogging.Client(project=os.environ['PROJECT_ID'])
handler = client.get_default_handler()
cloud_logger = logging.getLogger('cloudLogger')
cloud_logger.setLevel(logging.INFO)
cloud_logger.addHandler(handler)

def test_method(request):

  print('== start ==')

  try:
    cloud_logger.info('Info Message')
    cloud_logger.warn('Warn Message')
    raise Exception
  except Exception:
    cloud_logger.error('Error Message')
    raise Exception

  print('== finish ==')

実行、しかしログが出ない

  • なんにも出ない。

1_test.png

2_log.png

原因(想像)

  • print にしても結果は変わらず・・・
  • どうやらGoogle Cloud Functionsはcrash(=異常終了)するとそこまでのログを出力してくれない
    • ドキュメントのどこかに記述があるのだろうか・・・・
  • なのでExceptionが出たらcatchして最終的に sys.exit() するように変更
import sys
# 中略
  try:
    cloud_logger.info('Info Message')
    cloud_logger.warn('Warn Message')
    raise Exception
  except Exception:
    cloud_logger.error('Error Message')
    sys.exit()

  print('== finish ==')

再実行、そしてエラー

3_log.png

  • Failed to submit 3 logs.
  • google.api_core.exceptions.PermissionDenied: 403 The caller does not have permission

とな

Google Cloud Functionsのサービスアカウント

  • ドキュメントを見るとGoogle Cloud Functionsのデフォルトサービスアカウントは PROJECT_ID@appspot.gserviceaccount.com (App Engine default service account)になると記載がある。どうやらプロジェクト編集者のロールを持っているらしい。
  • 自分の環境を見ると・・・・ない!
    • なぜか無くなっていた模様

解決策

  • 専用のSAを作成してGoogle Cloud Functionsへ紐付け。
  • ちゃんとログが出るようになりました
    • エラーレベルがinfoとerrorしかないのはなぜだろう・・・ 4_log.png

振り返り

  • ドキュメントはちゃんと読もう
    • 書いてなかったかもしれないけど
  • 横着してデフォルトのSAを使わず、ちゃんと必要な権限をもったSAを作成して利用しよう
  • Cloud Functionsは落とさない。正常終了させる
  • 稼働状況をモニタリングするならerror件数ではなくログのerrorメッセージ数を見る(しかないのだろうか・・・?)
6
5
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
6
5