LoginSignup
4
2

More than 5 years have passed since last update.

Cloud FunctionsのlogをstackdriverにjsonPayloadで送りたい

Last updated at Posted at 2019-01-23

Cloud Functionsは実行ログをstackdriverに自動的に集めてくれるので大変に便利だが、
console.log を利用するとjs objectを渡してもstackdriverのrecordの本文がtextPayload になってしまう。
これをなんとかしてjsonPayloadとしてログ送信したい。

tl;dr

@google-cloud/logging で自前でlogger instanceを作って送信する。

そもそもなんでそんなことしたいのか

できる限り楽して、URL query paramをBQに保存したかったから。

stackdriver > BQ にexportしたときにjson payloadの場合は勝手にcolumn作ってくれて便利

console.logを使った場合

まずは一番シンプルなcloud functions

/**
 * Responds to any HTTP request.
 *
 * @param {!express:Request} req HTTP request context.
 * @param {!express:Response} res HTTP response context.
 */
exports.helloWorld = (req, res) => {

  //この書き方だとstackdriverのrecordがtextPayloadになる
  console.log(req.query);
  res.status(200).send(message);
};

上記のfunctionsを以下のようなqueryで実行

https://${TRIGGER_URL}/functions-1?hoge=fuga&foo=bar

stackdriverのrecordは以下のようにtextPayloadの文字列として保存される

textPayload:  "{ hoge: 'fuga', foo: 'bar', mes: 'mesbody' }"  

自前loggerを使う場合

以下のようにlogger instanceを自前で作ってやるとjsonPayloadで入る。よかったよかった

const {Logging} = require('@google-cloud/logging');
const logging = new Logging(process.env.GCLOUD_PROJECT);
const log = logging.log('jsonpayload-log');

const LogMetadata = {
  resource: {
    type: 'cloud_function',
    labels: {
      function_name: process.env.FUNCTION_NAME ,
      project: process.env.GCLOUD_PROJECT,
      region: process.env.FUNCTION_REGION
    },
  },
};

/**
 * Responds to any HTTP request.
 *
 * @param {!express:Request} req HTTP request context.
 * @param {!express:Response} res HTTP response context.
 */
exports.helloWorld = (req, res) => {
  const entry = log.entry(LogMetadata, req.query);
  log.write(entry);
};

4
2
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
4
2