Setting Log Message Status in Google Cloud Logs From Nodejs


If you're using Cloud Run or Cloud Functions on GCP you have probably use Cloud Logging to see error message or other output from your applications. Ifwant to have more control over how your log messages are flagged in you Nodejs applications, try the npm package @google-cloud/logging.

First install the npm package and create a file you can require where needed to handle the logging.

npm install @google-cloud/logging
const { Logging } = require('@google-cloud/logging');
let log;

async function initLog(
    projectId = 'myprojectid-11122233', // Your GCP project ID
    logName = 'your-applications-log-name' // Your app log name
  ) {
    // Creates a client
    const logging = new Logging({projectId});
  
    // Selects the log to write to
    log = logging.log(logName);
  
  }

  initLog();

  module.exports = { log };
logging/gcplogs.js

To use the file just require it where you need it in your Nodejs app.

const { log } = require('./helpers/gcplogs.js');

Then you can log message with different flags. Here are some examples.

Warning

Usage:

// Warning 
log.warning(log.entry("This is a test of gcp logs package - log.warning"))
Warning Message

Output:

Error

Usage:

// Error
log.error(log.entry("This is a test of gcp logs package - log.error"))

Output:

Alert

Usage:

// Alert 
log.alert(log.entry("This is a test of gcp logs package - log.alert"))

Output:

Info

Usage:

// Info
log.info(log.entry("This is a test of gcp logs package - log.info"))

Output:

Standard

// Standard
log.write(log.entry("This is a test of gcp logs package - log.write"))

Output:

If you want to dig into it more you can check it out here.

@google-cloud/logging
Stackdriver Logging Client Library for Node.js

Subscribe to dadonk

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
jamie@example.com
Subscribe