In this article, I’ll show you how to nicely log every HTTP queries made to Elasticsearch by your NestJS application.


Part 2 of this series was about logging HTTP requests to external HTTP services whether they are other services in your stack or public APIs.

Logging business logic is easy (or at least it starts easy): create a Logger or get it from somewhere (I actually prefer obtaining a fresh instance from a factory) and start logging whatever is relevant to your business logic.

But I have a larger goal which is to log every call (HTTP or anything else) to the services my app depends on.

For instance, logging SQL queries is easy with Postgres and the Sequelize ORM:

import { Module } from '@nestjs/common';
	import { SequelizeModule } from '@nestjs/sequelize';

	const logger = new Logger('SQL');

	  imports: [
	      logging: (sql) => logger.log(sql),
	      dialect: 'mysql',
	      host: 'localhost',
	      port: 3306,
	      username: 'root',
	      password: 'root',
	      database: 'test',
	      models: [],
	export class AppModule {}

Logging HTTP queries to Elasticsearch is a bit trickier because, as describe here, Elasticsearch doesn’t provide a default way to log and we have to correlate requests and responses via a Correlation ID instead. So let’s do it.

#typescript #nodejs #tutorial #nestjs #software-development

Advanced NestJS techniques — Part 3 — Logging Elasticsearch queries
19.80 GEEK