Logging Application Events with Node.js

This part of the Bookshelf tutorial shows how an app can incorporate detailed logging to help with detecting, debugging, and monitoring potential issues. Logging application events can help you identify issues and solve problems, both during development and after your app is in production.

This page is part of a multi-page tutorial. To start from the beginning and see instructions for setting up, go to Node.js Bookshelf App.

Configuring settings

Copy your config.json file from the Authenticating Users part of this tutorial to the nodejs-getting-started/5-logging directory.

Installing dependencies

Install dependencies in the nodejs-getting-started/5-logging directory:

  • Using npm:

    npm install
    
  • Using yarn:

    yarn install
    

Running the app on your local machine

  1. Start a local web server using npm or yarn:

    • Using npm:

      npm start
      
    • Using yarn:

      yarn start
      
  2. In your web browser, enter the following address:

    http://localhost:8080

Deploying the app to the App Engine standard environment

  1. Deploy the sample app:

    gcloud app deploy
    

  2. In your web browser, enter this address. Replace [YOUR_PROJECT_ID] with your project ID:

    https://[YOUR_PROJECT_ID].appspot.com
    

If you update your app, you can deploy the updated version by entering the same command you used to deploy the app the first time. The new deployment creates a new version of your app and promotes it to the default version. The older versions of your app remain. By default the App Engine standard environment scales to 0 instances when there is no incoming traffic to a version, thus unused versions should not cost anything. However, all of these app versions are still billable resources.

See the Cleaning up section in the final step of this tutorial for more information on cleaning up billable resources, including non-default app versions.

Understanding the code

After your app is deployed and running, it's important to understand how well it is working. Google Cloud Platform provides tracing, logging, debugging, and monitoring tools built right into the Google Cloud Platform Console, so you can quickly get a powerful view into the detailed activity in your app, which can help you identify critical issues or trends.

The Bookshelf sample app uses Google Cloud Trace to trace RPC calls in the application. You can view the traces in the Cloud Trace Dashboard. The sample app uses Google Cloud Debug in conjunction with Cloud Source Repositories to help you debug the application once it has been deployed. You can debug the deployed sample app using the Cloud Debug Dashboard.

// Activate Google Cloud Trace and Debug when in production
if (process.env.NODE_ENV === 'production') {
  require('@google-cloud/trace-agent').start();
  require('@google-cloud/debug-agent').start();
}

The sample app uses Winston, which is a logging library for Node.js, along with express-winston middleware to manage request and error logging. The code below sets up logging of all requests made to the app to the console.

const requestLogger = expressWinston.logger({
  transports: [
    new StackdriverTransport(),
    new winston.transports.Console({
      json: false,
      colorize: colorize
    })
  ],
  expressFormat: true,
  meta: false
});

The next code block sets up logging of important errors that occur within the app.

const errorLogger = expressWinston.errorLogger({
  transports: [
    new StackdriverTransport(),
    new winston.transports.Console({
      json: true,
      colorize: colorize
    })
  ]
});

Now that the logging has been set up, the app can use it. The following code adds the request-logging middleware from logging.requestLogger to the application.

app.use(logging.requestLogger);

To handle errors, the following code installs the error-logging middleware from logging.errorLogger to the application. It’s important that this is added after all other middleware, but before any custom error handlers, so that it can accurately report errors.

app.use(logging.errorLogger);

// Basic 404 handler
app.use((req, res) => {
  res.status(404).send('Not Found');
});

// Basic error handler
app.use((err, req, res, next) => {
  /* jshint unused:false */
  // If our routes specified a specific response, then send that. Otherwise,
  // send a generic message so as not to leak anything.
  res.status(500).send(err.response || 'Something broke!');
});

The app can also log important events from anywhere by using the following code.

logging.info("Something happened");
logging.error("Something bad happened");

Understanding the logging configuration

Running in the App Engine standard environment

When the sample app is running in the App Engine standard environment, anything logged to stderr and stdout is automatically collected by Google Cloud Logging and available for viewing, searching, and exporting in the logs viewer in the GCP Console.

The Winston configuration ensures that all logs are written to stderr/stdout.

Viewing logs

After the sample app is deployed and running, logging data will begin to be collected. Analyzing this logging data can be done with the log monitoring tools built right into the GCP Console. The following image shows logged events in the GCP Console.

Logging in the console

If you want more detailed analysis, you can stream or import the app's logs into BigQuery or export them to a Google Cloud Storage Bucket. You can do both right from within the GCP Console.

Was this page helpful? Let us know how we did:

Send feedback about...