@nestjs/microservices
Version:
Microservices for NestJS: message and event handlers over Kafka, RabbitMQ, NATS, Redis, MQTT, gRPC or TCP.
47 lines (46 loc) • 1.53 kB
JavaScript
import { inspect } from 'util';
import { logLevel } from '../external/kafka.interface.js';
/**
* Serializes the details of a log entry. JSON.stringify() throws on circular
* references, on BigInt values and on values nested deeper than it can
* recurse, so such an entry is formatted with inspect() instead. kafkajs logs
* from inside its own error handling (such as the error an `eachMessage`
* handler rejected with), where an exception thrown by the logger would take
* the place of the error being handled and stop the consumer for good.
*/
const stringifyLogEntry = (entry) => {
try {
return JSON.stringify(entry);
}
catch {
try {
return inspect(entry, { compact: true, breakLength: Infinity });
}
catch {
return '[unserializable log entry]';
}
}
};
export const KafkaLogger = (logger) => ({ namespace, level, label, log }) => {
let loggerMethod;
switch (level) {
case logLevel.ERROR:
case logLevel.NOTHING:
loggerMethod = 'error';
break;
case logLevel.WARN:
loggerMethod = 'warn';
break;
case logLevel.INFO:
loggerMethod = 'log';
break;
case logLevel.DEBUG:
default:
loggerMethod = 'debug';
break;
}
const { message, ...others } = log;
if (logger[loggerMethod]) {
logger[loggerMethod](`${label} [${namespace}] ${message} ${stringifyLogEntry(others)}`);
}
};