Created
August 30, 2018 16:14
-
-
Save cyril-lakech/4c00f9acefb87cb691dac14924287dbd to your computer and use it in GitHub Desktop.
Simplest Morgan NestJS Middleware
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Injectable, MiddlewareFunction, NestMiddleware } from '@nestjs/common'; | |
import * as morgan from 'morgan'; | |
import { LoggerService } from './mylogger'; | |
@Injectable() | |
export class MorganMiddleware implements NestMiddleware { | |
constructor(private readonly logger: LoggerService) {} | |
resolve(): MiddlewareFunction { | |
return morgan('combined', { | |
stream: { write: str => this.logger.info(str) }, | |
}); | |
} | |
} |
This is how I solved it:
This does not make use of a NestMiddleware, but connects morgan directly to winston.
main.ts
async function bootstrap() {
const app = await NestFactory.create(AppModule);
// Add Winston logger middleware
const logger = app.get(WINSTON_MODULE_NEST_PROVIDER);
app.useLogger(logger);
// Log request/responses
app.use(
morgan("common", {
stream: {
write: (message) => {
logger.log(message);
},
},
})
);
await app.listen(PORT);
}
bootstrap();
app.module.ts
@Module({
imports: [
WinstonModule.forRootAsync({
useClass: WinstonConfigService,
}),
],
})
export class AppModule {}
HI 👋,
I do this:
import { Injectable, Logger, NestMiddleware } from '@nestjs/common'
import * as morgan from 'morgan'
@Injectable()
export class HttpLoggerMiddleware implements NestMiddleware {
private readonly logger = new Logger(HttpLoggerMiddleware.name)
use(req: any, res: any, next: () => void) {
morgan(process.env.NODE_ENV === 'production' ? 'common' : 'dev', {
stream: {
write: (message) => this.logger.log(message)
}
})(req, res, next)
}
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi,
Thanks for sharing!
In the new version of NestJS, it should look like
And it needs to be consumed in the app module, like so