Bunyan and Express

Demonstrates how to set up and use Bunyan with Cloud Logging in a Node.js Express application.

Explore further

For detailed documentation that includes this code sample, see the following:

Code sample

Node.js

To learn how to install and use the client library for Logging, see Logging client libraries .

To authenticate to Logging, set up Application Default Credentials. For more information, see Set up authentication for a local development environment .

  // Imports the Google Cloud client library for Bunyan. 
 const 
  
 lb 
  
 = 
  
 require 
 ( 
 ' @google-cloud/logging-bunyan 
' 
 ); 
 // Import express module and create an http server. 
 const 
  
 express 
  
 = 
  
 require 
 ( 
 'express' 
 ); 
 async 
  
 function 
  
 startServer 
 () 
  
 { 
  
 const 
  
 { 
 logger 
 , 
  
 mw 
 } 
  
 = 
  
 await 
  
 lb 
 . 
 express 
 . 
  middleware 
 
 ({ 
  
 logName 
 : 
  
 'samples_express' 
 , 
  
 }); 
  
 const 
  
 app 
  
 = 
  
 express 
 (); 
  
 // Install the logging middleware. This ensures that a Bunyan-style `log` 
  
 // function is available on the `request` object. This should be the very 
  
 // first middleware you attach to your app. 
  
 app 
 . 
 use 
 ( 
 mw 
 ); 
  
 // Setup an http route and a route handler. 
  
 app 
 . 
 get 
 ( 
 '/' 
 , 
  
 ( 
 req 
 , 
  
 res 
 ) 
  
 = 
>  
 { 
  
 // `req.log` can be used as a bunyan style log method. All logs generated 
  
 // using `req.log` use the current request context. That is, all logs 
  
 // corresponding to a specific request will be bundled in the Stackdriver 
  
 // UI. 
  
 req 
 . 
 log 
 . 
 info 
 ( 
 'this is an info log message' 
 ); 
  
 res 
 . 
 send 
 ( 
 'hello world' 
 ); 
  
 }); 
  
 const 
  
 port 
  
 = 
  
 process 
 . 
 env 
 . 
 PORT 
  
 || 
  
 8080 
 ; 
  
 // `logger` can be used as a global logger, one not correlated to any specific 
  
 // request. 
  
  logger 
 
 . 
 info 
 ({ 
 port 
 }, 
  
 'bonjour' 
 ); 
  
 // Start listening on the http server. 
  
 const 
  
 server 
  
 = 
  
 app 
 . 
 listen 
 ( 
 port 
 , 
  
 () 
  
 = 
>  
 { 
  
 console 
 . 
 log 
 ( 
 `http server listening on port 
 ${ 
 port 
 } 
 ` 
 ); 
  
 }); 
  
 app 
 . 
 get 
 ( 
 '/shutdown' 
 , 
  
 ( 
 req 
 , 
  
 res 
 ) 
  
 = 
>  
 { 
  
 res 
 . 
 sendStatus 
 ( 
 200 
 ); 
  
 server 
 . 
 close 
 (); 
  
 }); 
 } 
 startServer 
 (); 
 

What's next

To search and filter code samples for other Google Cloud products, see the Google Cloud sample browser .

Create a Mobile Website
View Site in Mobile | Classic
Share by: