エラーを自動的に報告する
次のように、Cloud Function から Stackdriver Error Reporting にエラーを送信できます。
Node.js
より詳細なエラー報告が必要な場合は、Stackdriver Error Reporting クライアント ライブラリを使用します。
報告されたエラーは、API Console の Stackdriver Error Reporting で確認できます。また、API Console で関数のリストから関数を選択すると、その関数から報告されたエラーを確認できます。
関数によって生成され、キャッチされていない例外は、Stackdriver Error Reporting に表示されます。キャッチされていない例外(非同期でスローされた例外など)は、将来の関数呼び出しでコールド スタートの原因となる可能性があります。これにより、関数のパフォーマンスが低下します。
Google 提供のライブラリを介して Google サービスを使用している場合は、次のように、提供されたエラーをログに記録できます。Node.js
エラーを手動で報告する
関数から Stackdriver Error Reporting にエラーを報告するには、Stackdriver Logging API を使用します。
依存関係をインポートする
functions
ディレクトリから、Node.js 用の Google Stackdriver Logging クライアント ライブラリをインストールします。
npm install --save @google-cloud/logging
Logging API にアクセスするために、Google Cloud クライアント ライブラリをインポートします。
const Logging = require('@google-cloud/logging');
// Instantiates a client
const logging = Logging();
Stackdriver に送信する
ログエントリを適切な形式にするには、MonitoredResource
オブジェクトと ErrorEvent
オブジェクトが必要です。
この例では、reportError
関数が Stackdriver Error Reporting にエラーを報告するのに必要な最低限のデータがわかります。
function reportError(err, context = {}) { // This is the name of the StackDriver log stream that will receive the log // entry. This name can be any valid log stream name, but must contain "err" // in order for the error to be picked up by StackDriver Error Reporting. const logName = 'errors'; const log = logging.log(logName); // https://cloud.google.com/logging/docs/api/ref_v2beta1/rest/v2beta1/MonitoredResource const metadata = { resource: { type: 'cloud_function', labels: {function_name: process.env.FUNCTION_NAME}, }, }; // https://cloud.google.com/error-reporting/reference/rest/v1beta1/ErrorEvent const errorEvent = { message: err.stack, serviceContext: { service: process.env.FUNCTION_NAME, resourceType: 'cloud_function', }, context: context, }; // Write the error log entry return new Promise((resolve, reject) => { log.write(log.entry(metadata, errorEvent), (error) => { if (error) { return reject(error); } return resolve(); }); }); }
reportError
関数を使用すると、エラーを手動で報告できます。
// Charge the Stripe customer whenever an amount is written to the Realtime database exports.createStripeCharge = functions.database.ref('/stripe_customers/{userId}/charges/{id}') .onCreate((snap, context) => { const val = snap.val(); // Look up the Stripe customer id written in createStripeCustomer return admin.database().ref(`/stripe_customers/${context.params.userId}/customer_id`) .once('value').then((snapshot) => { return snapshot.val(); }).then((customer) => { // Create a charge using the pushId as the idempotency key // protecting against double charges const amount = val.amount; const idempotencyKey = context.params.id; const charge = {amount, currency, customer}; if (val.source !== null) { charge.source = val.source; } return stripe.charges.create(charge, {idempotency_key: idempotencyKey}); }).then((response) => { // If the result is successful, write it back to the database return snap.ref.set(response); }).catch((error) => { // We want to capture errors and render them in a user-friendly way, while // still logging an exception with StackDriver return snap.ref.child('error').set(userFacingMessage(error)); }).then(() => { return reportError(error, {user: context.params.userId}); }); });
ErrorContext
パラメータを使用して、ユーザーの詳細を渡すことができます。これらの詳細は Stackdriver の UI に表示され、影響を受けるユーザーの数を計算するために使用されます。
ErrorContext
に HTTP リクエストに関する情報を渡すこともできます。
export.httpError = functions.https.onRequest((request, response) => {
const error = new Error('Test error');
const httpRequest = {
method: request.method,
url: request.originalUrl,
userAgent: request.get('user-agent'),
referrer: '',
remoteIp: request.ip
};
reportError(error, {httpRequest}).then(() => {
response.end();
});
});