An Express Gateway custom policy for logging request bodies, execution times, and more
Express Gateway directs public API requests to private backend services. It features customizable pipelines that invoke policies: plug-in functions that accept NodeJS request and response objects. Policies can, for example, enforce security or add headers to requests.
This article presents a custom policy that logs requests. Although Express Gateway provides a logging policy, integrating it with a particular logging library can be challenging if not impossible. By implementing a custom policy, additional information can be logged, such as execution times, client IP addresses, referrers, and response status codes.
The custom policy logs two messages (at separate times) for each request:
- A request has been received
- The request has been processed
Both messages contain the same unique correlation identifier.
The policy outputs to @goodware/log: a Winston3 wrapper that writes to the console, files, and/or AWS CloudWatch Logs. @goodware/log provides easy configuration and supports large objects (messages are truncated one they reach a maximum size) that may have cyclic references. Of course, you are encouraged to copy this code and use your logger of choice.
Parsing a request body consumed days of trial and error. Although the Express Gateway documentation provides some advice, there’s a trick for working with bodies that don’t fit in a single packet: next() must execute outside the callback provided to Express parser functions.
This article does not explain how to create Express Gateway projects or how to add custom policies to them. Better articles can be found elsewhere. Assuming you have an Express Gateway project up and running, install dependencies and add a custom policy named ‘request-logger’ with the implementation shown below. Questions welcome!
npm install --save @goodware/log ulidx humanize-duration