Skip to content

Commit 8bc84dd

Browse files
authored
Updates logging in https callable functions. (#745)
1 parent a07d6ef commit 8bc84dd

File tree

5 files changed

+25
-21
lines changed

5 files changed

+25
-21
lines changed

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ const notifyUsers = require('./notify-users');
2929
exports.newPost = functions.database
3030
.ref('/posts/{postId}')
3131
.onCreate((snapshot, context) => {
32-
console.log('Received new post with ID:', context.params.postId);
32+
functions.logger.info('Received new post with ID:', context.params.postId);
3333
return notifyUsers(snapshot.val());
3434
});
3535
```

src/cloud-functions.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@
2323
import { Request, Response } from 'express';
2424
import * as _ from 'lodash';
2525
import { DeploymentOptions, Schedule } from './function-configuration';
26+
import { warn } from './logger';
2627
export { Request, Response };
2728

2829
/** @hidden */
@@ -379,7 +380,7 @@ export function makeCloudFunction<EventData>({
379380
promise = handler(dataOrChange, context);
380381
}
381382
if (typeof promise === 'undefined') {
382-
console.warn('Function returned undefined, expected Promise or value');
383+
warn('Function returned undefined, expected Promise or value');
383384
}
384385
return Promise.resolve(promise)
385386
.then((result) => {

src/providers/crashlytics.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -77,7 +77,7 @@ export class IssueBuilder {
7777
* const slackMessage = ` There's a new issue (${issueId}) ` +
7878
* `in your app - ${issueTitle}`;
7979
* return notifySlack(slackMessage).then(() => {
80-
* console.log(`Posted new issue ${issueId} successfully to Slack`);
80+
* functions.logger.info(`Posted new issue ${issueId} successfully to Slack`);
8181
* });
8282
* });
8383
* ```

src/providers/https.ts

Lines changed: 18 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -24,9 +24,11 @@ import * as cors from 'cors';
2424
import * as express from 'express';
2525
import * as firebase from 'firebase-admin';
2626
import * as _ from 'lodash';
27+
2728
import { apps } from '../apps';
2829
import { HttpsFunction, optionsToTrigger, Runnable } from '../cloud-functions';
2930
import { DeploymentOptions } from '../function-configuration';
31+
import { warn, error } from '../logger';
3032

3133
/** @hidden */
3234
export interface Request extends express.Request {
@@ -285,13 +287,13 @@ interface HttpResponseBody {
285287
function isValidRequest(req: Request): req is HttpRequest {
286288
// The body must not be empty.
287289
if (!req.body) {
288-
console.warn('Request is missing body.');
290+
warn('Request is missing body.');
289291
return false;
290292
}
291293

292294
// Make sure it's a POST.
293295
if (req.method !== 'POST') {
294-
console.warn('Request has invalid method.', req.method);
296+
warn('Request has invalid method.', req.method);
295297
return false;
296298
}
297299

@@ -303,13 +305,13 @@ function isValidRequest(req: Request): req is HttpRequest {
303305
contentType = contentType.substr(0, semiColon).trim();
304306
}
305307
if (contentType !== 'application/json') {
306-
console.warn('Request has incorrect Content-Type.', contentType);
308+
warn('Request has incorrect Content-Type.', contentType);
307309
return false;
308310
}
309311

310312
// The body must have data.
311313
if (_.isUndefined(req.body.data)) {
312-
console.warn('Request body is missing data.', req.body);
314+
warn('Request body is missing data.', req.body);
313315
return false;
314316
}
315317

@@ -318,7 +320,7 @@ function isValidRequest(req: Request): req is HttpRequest {
318320
// Verify that the body does not have any extra fields.
319321
const extras = _.omit(req.body, 'data');
320322
if (!_.isEmpty(extras)) {
321-
console.warn('Request body has extra fields.', extras);
323+
warn('Request body has extra fields.', extras);
322324
return false;
323325
}
324326
return true;
@@ -363,7 +365,7 @@ export function encode(data: any): any {
363365
return _.mapValues(data, encode);
364366
}
365367
// If we got this far, the data is not encodable.
366-
console.error('Data cannot be encoded in JSON.', data);
368+
error('Data cannot be encoded in JSON.', data);
367369
throw new Error('Data cannot be encoded in JSON: ' + data);
368370
}
369371

@@ -386,13 +388,13 @@ export function decode(data: any): any {
386388
// worth all the extra code to detect that case.
387389
const value = parseFloat(data.value);
388390
if (_.isNaN(value)) {
389-
console.error('Data cannot be decoded from JSON.', data);
391+
error('Data cannot be decoded from JSON.', data);
390392
throw new Error('Data cannot be decoded from JSON: ' + data);
391393
}
392394
return value;
393395
}
394396
default: {
395-
console.error('Data cannot be decoded from JSON.', data);
397+
error('Data cannot be decoded from JSON.', data);
396398
throw new Error('Data cannot be decoded from JSON: ' + data);
397399
}
398400
}
@@ -420,7 +422,7 @@ export function _onCallWithOptions(
420422
const func = async (req: Request, res: express.Response) => {
421423
try {
422424
if (!isValidRequest(req)) {
423-
console.error('Invalid request', req);
425+
error('Invalid request, unable to process.');
424426
throw new HttpsError('invalid-argument', 'Bad Request');
425427
}
426428

@@ -441,7 +443,7 @@ export function _onCallWithOptions(
441443
uid: authToken.uid,
442444
token: authToken,
443445
};
444-
} catch (e) {
446+
} catch (err) {
445447
throw new HttpsError('unauthenticated', 'Unauthenticated');
446448
}
447449
}
@@ -464,15 +466,15 @@ export function _onCallWithOptions(
464466
// If there was some result, encode it in the body.
465467
const responseBody: HttpResponseBody = { result };
466468
res.status(200).send(responseBody);
467-
} catch (error) {
468-
if (!(error instanceof HttpsError)) {
469+
} catch (err) {
470+
if (!(err instanceof HttpsError)) {
469471
// This doesn't count as an 'explicit' error.
470-
console.error('Unhandled error', error);
471-
error = new HttpsError('internal', 'INTERNAL');
472+
error('Unhandled error', error);
473+
err = new HttpsError('internal', 'INTERNAL');
472474
}
473475

474-
const { status } = error.httpErrorCode;
475-
const body = { error: error.toJSON() };
476+
const { status } = err.httpErrorCode;
477+
const body = { error: err.toJSON() };
476478

477479
res.status(status).send(body);
478480
}

src/setup.ts

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@
2222

2323
/** @hidden */
2424
import { firebaseConfig } from './config';
25+
import { warn } from './logger';
2526

2627
// Set up for config and vars
2728
export function setup() {
@@ -45,7 +46,7 @@ export function setup() {
4546
// If FIREBASE_CONFIG is still not found, try using GCLOUD_PROJECT to estimate
4647
if (!process.env.FIREBASE_CONFIG) {
4748
if (process.env.GCLOUD_PROJECT) {
48-
console.warn(
49+
warn(
4950
'Warning, estimating Firebase Config based on GCLOUD_PROJECT. Initializing firebase-admin may fail'
5051
);
5152
process.env.FIREBASE_CONFIG = JSON.stringify({
@@ -58,7 +59,7 @@ export function setup() {
5859
projectId: process.env.GCLOUD_PROJECT,
5960
});
6061
} else {
61-
console.warn(
62+
warn(
6263
'Warning, FIREBASE_CONFIG and GCLOUD_PROJECT environment variables are missing. Initializing firebase-admin will fail'
6364
);
6465
}

0 commit comments

Comments
 (0)