How to log events in functions?

Logging events in a system is an important task to get the most useful insights into what is happening in the application. We recommend following some conventions to achieve a consistent way of logging events.

Using the Firebase functions logger, pass to the first argument a string with the event description using capital letters and underscore between the words, and to the second argument, pass any data you want to log:

Logger.info('EVENT_DESCRIPTION', {
    message,
    userId,
});

How should you log events?

For example, you may want to log an event when a Stripe charge is made. You can then pass the customer ID and the amount of the charge:

const Logger = require('firebase-functions/lib/logger');

const confirmPayment = async ({ customerId, amount }) => {
    // payment logic
    await stripe.charge({
        customer: customerId,
        amount,
    });
    Logger.info('CUSTOMER_CHARGED', {
        customerId,
        amount,
    });
}

module.exports = confirmPayment;

How should I log errors?

Errors are logged the same as the above events, but the description starts with the ERROR_ prefix, and the data should have a message with an error string:

const Logger = require('firebase-functions/lib/logger');
const admin = require('./admin');

const getUserByEmail = (email) => {
    try {
        const user = await admin.auth().getUserByEmail(email);
        return user.toJSON();
    } catch (error) {
        Logger.error('ERROR_GET_USER_BY_EMAIL', {
            errorMessage: error.toString(),
        });
        return null;
    }
}

module.exports = getUserByEmail;

Last updated