This guide explains how to integrate cloud logging into your Express application using the cloud-app-logger
library. Each log will include a unique request ID for tracking the entire journey of a request, including request body, response, and any additional logs or errors for that request.
Note: Currently, only Google Cloud Logging is supported.
-
Add the following to your
package.json
:"cloud-app-logger": "^0.0.17"
-
Add the following environment variables:
LOGGING_PROJECT_ID=<YOUR_PROJECT_ID> # Name for the Google Cloud project where logs should be stored LOGGING_ENABLED=true # Enable logs being sent to the cloud. Keep false when running local code LOGGING_LOG_NAME=<LOG_NAME> # Log name in Google Cloud. For example, app-name-staging
-
Import the necessary functions wherever your Express app object is created:
import { initAppLogger, configureErrorLogging, configureRequestLogging } from 'cloud-app-logger'; // Call this as early as possible but after calling dotenv.config() initAppLogger();
-
After adding body parsing middlewares such as
json
orurlencoded
, configure request logging:app.use(express.json()); app.use(express.urlencoded({ extended: false })); // Call the function here !!! configureRequestLogging(app);
-
Call the error logging configuration function after adding all middlewares/routes:
configureErrorLogging(app);
-
Call the
logUnhandledExceptions
function in each file where you have defined a router after importingRouter
orExpress
:import { Router, Request, Response } from 'express'; import { logUnhandledExceptions } from 'cloud-app-logger'; // Call the function here logUnhandledExceptions(); const router = Router();
-
Run the project, and logging should now be enabled and visible in Google Cloud Logging.