-
-
Notifications
You must be signed in to change notification settings - Fork 7.7k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
[Feature Request] @nestjs/platform-fastify support Custom Log Level #14137
Comments
If I understand you correctly, you want to know how to use |
@Tony133, I need a configuration in nest to close some route log. like this |
I found the key code. I'll try modifying it. |
I have already completed this work, but I encountered an issue that is preventing me from submitting the PR.
export const FASTIFY_ROUTE_LOG_METADATA = '__fastify_route_log__';
import { SetMetadata } from '@nestjs/common';
import { FASTIFY_ROUTE_LOG_METADATA } from '../constants';
import { LogLevel } from 'fastify';
/**
* @publicApi
*
* @param config See {@link https://fastify.dev/docs/latest/Reference/Routes/#custom-log-level}
*/
export const RouteLog = (config: { logLevel: LogLevel }) =>
SetMetadata(FASTIFY_ROUTE_LOG_METADATA, config);
const routeConfig = Reflect.getMetadata(
FASTIFY_ROUTE_CONFIG_METADATA,
handlerRef,
);
// Here
const routeLog = Reflect.getMetadata(
FASTIFY_ROUTE_LOG_METADATA,
handlerRef,
);
const routeConstraints = Reflect.getMetadata(
FASTIFY_ROUTE_CONSTRAINTS_METADATA,
handlerRef,
);
const hasConfig = !isUndefined(routeConfig);
// Here
const hasLog = !isUndefined(routeLog);
const hasConstraints = !isUndefined(routeConstraints);
// Here
if (isVersioned || hasConstraints || hasConfig || hasLog) {
const isPathAndRouteTuple = args.length === 2;
if (isPathAndRouteTuple) {
const constraints = {
...(hasConstraints && routeConstraints),
...(isVersioned && {
version: handlerRef.version,
}),
};
const options = {
constraints,
...(hasConfig && {
config: {
...routeConfig,
},
}),
// Here
...(hasLog && {
...routeLog,
}),
};
const routeToInjectWithOptions = { ...routeToInject, ...options };
return this.instance.route(routeToInjectWithOptions);
}
} usage: @Get('')
@RouteLog({ logLevel: 'silent' })
public getCredit(
@Req() req: FastifyRequest,
@User('userId') userId: string,
): Promise<any> {
req.log.info('This log will never take effect.');
return this.creditService.getCredit(userId);
} @kamilmysliwiec Hi, Could you help me finish the remaining work? |
If I'm not mistaken fastify is using pino logger under the hood. If you do pass pino as custom logger within your nest application you'll have full control over your logger rather than trying to get the encapsulated one within the fastify platform. resources: |
@iiAku This custom-logger is very simple.I want to log everything from request to response for an API, but it can't be done because it lacks trace ID or request ID functionality. When using tools like Grafana, you can't filter by trace ID or request ID. The built-in Pino logger in Fastify automatically adds a request ID and allows you to call log methods directly from the request object, such as const fastifyInstance = fastify({
logger: true,
}); When you use the I have audit requirements, and I need to avoid logging unimportant routes. Instead of writing a log method for each desired route, I prefer to enable a global log method and only disable it for a few routes. I am already using my modified version of the |
If anyone else wants this feature, please help by submitting a PR. I encountered unsolvable type issues in my environment and cannot resolve them at the moment. |
@daimalou why don't you create a middleware and use the als package https://docs.nestjs.com/recipes/async-local-storage? |
@kamilmysliwiec I previously discovered an problem. I have a requirement to log the request body and response body. When I used Nest's middleware or interceptor, I can access request body, but I couldn't access the response body or raw body when using fastify adaptor. To access the response body in Fastify, need to use its built-in hooks. It's fastify part. https://fastify.dev/docs/latest/Reference/Hooks/#onsend This is like a black-box to Nest. const fastifyInstance = fastify({
logger: true,
});
fastifyInstance.addHook('onSend', function (request, reply, payload, next) {
const responseInfo = {
body: payload,
};
// It can also use request.log.*
request.log.info(responseInfo, 'reply body');
next();
});
const app = await NestFactory.create<NestFastifyApplication>(
AppModule,
new FastifyAdapter(fastifyInstance),
{
logger: false,
},
); It can also access request body in Fastify. https://fastify.dev/docs/latest/Reference/Hooks/#prehandler fastifyInstance.addHook('preHandler', function (request, reply, next) {
if (request.body) {
request.log.info({ body: request.body }, 'parsed body');
}
next();
}); Sometimes, Nest,I think it's like an abstraction layer. Some features cannot be configured in Nest. But compared to Fastify, I prefer Nest, as its philosophy is more similar to OOP. Introducing If I use Express, I would definitely use these two libraries. It's not have build-in logger. However, Express's performance is poor. Fastify is four times faster than Express. By the way, I’m also using Nestia, which makes Nest + Fastify incredibly fast. |
hello, Can you provide a demo of how you use it? thanks |
@0x0bit https://nestia.io/docs/core/TypedRoute/ |
thanks |
Is there an existing issue that is already proposing this?
Is your feature request related to a problem? Please describe it
I use fastify buildin logger, this logger is awesome, has builtin traceId feature and can access by
request.log.info()
https://fastify.dev/docs/v4.28.x/Reference/Logging/
It works.
But this logger log every request and response. I find a solution to close some route. But In Nest I can't find place to config.
solution:
fastify/fastify#2120
fastify/help#140
https://fastify.dev/docs/latest/Reference/Routes/#custom-log-level
Describe the solution you'd like
Give a config.
Teachability, documentation, adoption, migration strategy
None
What is the motivation / use case for changing the behavior?
None
The text was updated successfully, but these errors were encountered: