- 1. API with NestJS #1. Controllers, routing and the module structure
- 2. API with NestJS #2. Setting up a PostgreSQL database with TypeORM
- 3. API with NestJS #3. Authenticating users with bcrypt, Passport, JWT, and cookies
- 4. API with NestJS #4. Error handling and data validation
- 5. API with NestJS #5. Serializing the response with interceptors
- 6. API with NestJS #6. Looking into dependency injection and modules
- 7. API with NestJS #7. Creating relationships with Postgres and TypeORM
- 8. API with NestJS #8. Writing unit tests
- 9. API with NestJS #9. Testing services and controllers with integration tests
- 10. API with NestJS #10. Uploading public files to Amazon S3
- 11. API with NestJS #11. Managing private files with Amazon S3
- 12. API with NestJS #12. Introduction to Elasticsearch
- 13. API with NestJS #13. Implementing refresh tokens using JWT
- 14. API with NestJS #14. Improving performance of our Postgres database with indexes
- 15. API with NestJS #15. Defining transactions with PostgreSQL and TypeORM
- 16. API with NestJS #16. Using the array data type with PostgreSQL and TypeORM
- 17. API with NestJS #17. Offset and keyset pagination with PostgreSQL and TypeORM
- 18. API with NestJS #18. Exploring the idea of microservices
- 19. API with NestJS #19. Using RabbitMQ to communicate with microservices
- 20. API with NestJS #20. Communicating with microservices using the gRPC framework
- 21. API with NestJS #21. An introduction to CQRS
- 22. API with NestJS #22. Storing JSON with PostgreSQL and TypeORM
- 23. API with NestJS #23. Implementing in-memory cache to increase the performance
- 24. API with NestJS #24. Cache with Redis. Running the app in a Node.js cluster
- 25. API with NestJS #25. Sending scheduled emails with cron and Nodemailer
- 26. API with NestJS #26. Real-time chat with WebSockets
- 27. API with NestJS #27. Introduction to GraphQL. Queries, mutations, and authentication
- 28. API with NestJS #28. Dealing in the N + 1 problem in GraphQL
- 29. API with NestJS #29. Real-time updates with GraphQL subscriptions
- 30. API with NestJS #30. Scalar types in GraphQL
- 31. API with NestJS #31. Two-factor authentication
- 32. API with NestJS #32. Introduction to Prisma with PostgreSQL
- 33. API with NestJS #33. Managing PostgreSQL relationships with Prisma
- 34. API with NestJS #34. Handling CPU-intensive tasks with queues
- 35. API with NestJS #35. Using server-side sessions instead of JSON Web Tokens
- 36. API with NestJS #36. Introduction to Stripe with React
- 37. API with NestJS #37. Using Stripe to save credit cards for future use
- 38. API with NestJS #38. Setting up recurring payments via subscriptions with Stripe
- 39. API with NestJS #39. Reacting to Stripe events with webhooks
- 40. API with NestJS #40. Confirming the email address
- 41. API with NestJS #41. Verifying phone numbers and sending SMS messages with Twilio
- 42. API with NestJS #42. Authenticating users with Google
- 43. API with NestJS #43. Introduction to MongoDB
- 44. API with NestJS #44. Implementing relationships with MongoDB
- 45. API with NestJS #45. Virtual properties with MongoDB and Mongoose
- 46. API with NestJS #46. Managing transactions with MongoDB and Mongoose
- 47. API with NestJS #47. Implementing pagination with MongoDB and Mongoose
- 48. API with NestJS #48. Definining indexes with MongoDB and Mongoose
- 49. API with NestJS #49. Updating with PUT and PATCH with MongoDB and Mongoose
- 50. API with NestJS #50. Introduction to logging with the built-in logger and TypeORM
- 51. API with NestJS #51. Health checks with Terminus and Datadog
- 52. API with NestJS #52. Generating documentation with Compodoc and JSDoc
- 53. API with NestJS #53. Implementing soft deletes with PostgreSQL and TypeORM
- 54. API with NestJS #54. Storing files inside a PostgreSQL database
- 55. API with NestJS #55. Uploading files to the server
- 56. API with NestJS #56. Authorization with roles and claims
- 57. API with NestJS #57. Composing classes with the mixin pattern
- 58. API with NestJS #58. Using ETag to implement cache and save bandwidth
- 59. API with NestJS #59. Introduction to a monorepo with Lerna and Yarn workspaces
- 60. API with NestJS #60. The OpenAPI specification and Swagger
- 61. API with NestJS #61. Dealing with circular dependencies
- 62. API with NestJS #62. Introduction to MikroORM with PostgreSQL
- 63. API with NestJS #63. Relationships with PostgreSQL and MikroORM
- 64. API with NestJS #64. Transactions with PostgreSQL and MikroORM
- 65. API with NestJS #65. Implementing soft deletes using MikroORM and filters
- 66. API with NestJS #66. Improving PostgreSQL performance with indexes using MikroORM
- 67. API with NestJS #67. Migrating to TypeORM 0.3
- 68. API with NestJS #68. Interacting with the application through REPL
- 69. API with NestJS #69. Database migrations with TypeORM
- 70. API with NestJS #70. Defining dynamic modules
- 71. API with NestJS #71. Introduction to feature flags
- 72. API with NestJS #72. Working with PostgreSQL using raw SQL queries
- 73. API with NestJS #73. One-to-one relationships with raw SQL queries
- 74. API with NestJS #74. Designing many-to-one relationships using raw SQL queries
- 75. API with NestJS #75. Many-to-many relationships using raw SQL queries
- 76. API with NestJS #76. Working with transactions using raw SQL queries
- 77. API with NestJS #77. Offset and keyset pagination with raw SQL queries
- 78. API with NestJS #78. Generating statistics using aggregate functions in raw SQL
- 79. API with NestJS #79. Implementing searching with pattern matching and raw SQL
- 80. API with NestJS #80. Updating entities with PUT and PATCH using raw SQL queries
- 81. API with NestJS #81. Soft deletes with raw SQL queries
- 82. API with NestJS #82. Introduction to indexes with raw SQL queries
- 83. API with NestJS #83. Text search with tsvector and raw SQL
- 84. API with NestJS #84. Implementing filtering using subqueries with raw SQL
- 85. API with NestJS #85. Defining constraints with raw SQL
- 86. API with NestJS #86. Logging with the built-in logger when using raw SQL
- 87. API with NestJS #87. Writing unit tests in a project with raw SQL
- 88. API with NestJS #88. Testing a project with raw SQL using integration tests
- 89. API with NestJS #89. Replacing Express with Fastify
- 90. API with NestJS #90. Using various types of SQL joins
- 91. API with NestJS #91. Dockerizing a NestJS API with Docker Compose
- 92. API with NestJS #92. Increasing the developer experience with Docker Compose
- 93. API with NestJS #93. Deploying a NestJS app with Amazon ECS and RDS
- 94. API with NestJS #94. Deploying multiple instances on AWS with a load balancer
- 95. API with NestJS #95. CI/CD with Amazon ECS and GitHub Actions
- 96. API with NestJS #96. Running unit tests with CI/CD and GitHub Actions
- 97. API with NestJS #97. Introduction to managing logs with Amazon CloudWatch
- 98. API with NestJS #98. Health checks with Terminus and Amazon ECS
- 99. API with NestJS #99. Scaling the number of application instances with Amazon ECS
- 100. API with NestJS #100. The HTTPS protocol with Route 53 and AWS Certificate Manager
- 101. API with NestJS #101. Managing sensitive data using the AWS Secrets Manager
- 102. API with NestJS #102. Writing unit tests with Prisma
- 103. API with NestJS #103. Integration tests with Prisma
- 104. API with NestJS #104. Writing transactions with Prisma
- 105. API with NestJS #105. Implementing soft deletes with Prisma and middleware
- 106. API with NestJS #106. Improving performance through indexes with Prisma
- 107. API with NestJS #107. Offset and keyset pagination with Prisma
- 108. API with NestJS #108. Date and time with Prisma and PostgreSQL
- 109. API with NestJS #109. Arrays with PostgreSQL and Prisma
- 110. API with NestJS #110. Managing JSON data with PostgreSQL and Prisma
- 111. API with NestJS #111. Constraints with PostgreSQL and Prisma
- 112. API with NestJS #112. Serializing the response with Prisma
- 113. API with NestJS #113. Logging with Prisma
- 114. API with NestJS #114. Modifying data using PUT and PATCH methods with Prisma
- 115. API with NestJS #115. Database migrations with Prisma
- 116. API with NestJS #116. REST API versioning
- 117. API with NestJS #117. CORS – Cross-Origin Resource Sharing
- 118. API with NestJS #118. Uploading and streaming videos
- 119. API with NestJS #119. Type-safe SQL queries with Kysely and PostgreSQL
- 120. API with NestJS #120. One-to-one relationships with the Kysely query builder
- 121. API with NestJS #121. Many-to-one relationships with PostgreSQL and Kysely
As our application grows, more and more people start depending on it. At a time like this, it is crucial to ensure that our API works well. To do that, we could use a way to troubleshoot the application to detect anomalies and to be able to find their origin. This article serves as an introduction to how we can keep logs on what happens in our application.
Logger built into NestJS
Fortunately, NestJS comes with a logger built-in. Before using it, we should create its instance.
posts.service.ts
1 2 3 4 5 6 7 8 |
import { Injectable, Logger } from '@nestjs/common'; @Injectable() export default class PostsService { private readonly logger = new Logger(PostsService.name) // ... } |
Although we could use the Logger we import from @nestjs/common directly, creating a brand new instance for every service is a good practice and allows us to supply the name of the service for the Logger constructor.
Log levels
A crucial thing about the Logger is that it comes with a few methods:
- error
- warn
- log
- verbose
- debug
The above methods correspond with log levels that we can configure for our application.
main.ts
1 2 3 4 5 6 7 8 9 10 11 12 |
import { NestFactory } from '@nestjs/core'; import { AppModule } from './app.module'; import getLogLevels from './utils/getLogLevels'; async function bootstrap() { const app = await NestFactory.create(AppModule, { logger: getLogLevels(process.env.NODE_ENV === 'production') }); // ... } bootstrap(); |
We don’t use the ConfigService above to read the environment variables because it isn’t initialized yet.
getLogLevels.ts
1 2 3 4 5 6 7 8 9 10 |
import { LogLevel } from '@nestjs/common/services/logger.service'; function getLogLevels(isProduction: boolean): LogLevel[] { if (isProduction) { return ['log', 'warn', 'error']; } return ['error', 'warn', 'log', 'verbose', 'debug']; } export default getLogLevels; |
Because of the above setup, the debug and verbose methods won’t produce logs on production.
If we take a look at the isLogLevelEnabled function, we can notice that providing ['debug'] turns on all of the log levels, not only verbose. This is because NestJS assumes that if we want to display the verbose logs, we also want to display logs of all of the lower levels. Because of that, ['debug'] is the same as ['error', 'warn', 'log', 'verbose', 'debug'].
We can find the importance of each log level here.
After doing all of the above, let’s start using the logger.
posts.service.ts
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
import { Injectable, Logger } from '@nestjs/common'; import Post from './post.entity'; import { InjectRepository } from '@nestjs/typeorm'; import { Repository } from 'typeorm'; import PostNotFoundException from './exceptions/postNotFound.exception'; @Injectable() export default class PostsService { private readonly logger = new Logger(PostsService.name) constructor( @InjectRepository(Post) private postsRepository: Repository<Post>, ) {} async getPostById(id: number) { const post = await this.postsRepository.findOne(id, { relations: ['author'] }); if (post) { return post; } this.logger.warn('Tried to access a post that does not exist'); throw new PostNotFoundException(id); } // ... } |
Now we can see that passing PostsService.name caused PostService to appear as a prefix to our log message.
Using the logger in a middleware
Even though the above approach might come in handy, it might be cumbersome to write log messages manually. Thankfully, we can produce logs from middleware.
logs.middleware.ts
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
import { Injectable, Logger, NestMiddleware } from '@nestjs/common'; import { Request, Response, NextFunction } from 'express'; @Injectable() class LogsMiddleware implements NestMiddleware { private readonly logger = new Logger('HTTP'); use(request: Request, response: Response, next: NextFunction) { response.on('finish', () => { const { method, originalUrl } = request; const { statusCode, statusMessage } = response; const message = `${method} ${originalUrl} ${statusCode} ${statusMessage}`; if (statusCode >= 500) { return this.logger.error(message); } if (statusCode >= 400) { return this.logger.warn(message); } return this.logger.log(message); }); next(); } } export default LogsMiddleware; |
Check out the MDN documentation to read more about HTTP response status codes.
Above, we gather information about the request and response and log it based on the status code. Of course, the request and response objects contain more helpful information, so feel free to make your logs even more verbose.
The last step is to apply our middleware for all of our routes.
app.module.ts
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
import { MiddlewareConsumer, Module } from '@nestjs/common'; import { PostsModule } from './posts/posts.module'; import { DatabaseModule } from './database/database.module'; import LogsMiddleware from './utils/logs.middleware'; @Module({ imports: [ PostsModule, DatabaseModule, // ... ], // ... }) export class AppModule { configure(consumer: MiddlewareConsumer) { consumer .apply(LogsMiddleware) .forRoutes('*'); } } |
Using the logger with TypeORM
Another helpful thing we can do is to log all SQL queries that happen in our application. To do that with TypeORM, we need to implement the Logger interface:
databaseLogger.ts
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 |
import { Logger as TypeOrmLogger } from 'typeorm'; import { Logger as NestLogger } from '@nestjs/common'; class DatabaseLogger implements TypeOrmLogger { private readonly logger = new NestLogger('SQL'); logQuery(query: string, parameters?: unknown[]) { this.logger.log(`${query} -- Parameters: ${this.stringifyParameters(parameters)}`); } logQueryError(error: string, query: string, parameters?: unknown[]) { this.logger.error(`${query} -- Parameters: ${this.stringifyParameters(parameters)} -- ${error}`); } logQuerySlow(time: number, query: string, parameters?: unknown[]) { this.logger.warn(`Time: ${time} -- Parameters: ${this.stringifyParameters(parameters)} -- ${query}`); } logMigration(message: string) { this.logger.log(message); } logSchemaBuild(message: string) { this.logger.log(message); } log(level: 'log' | 'info' | 'warn', message: string) { if (level === 'log') { return this.logger.log(message); } if (level === 'info') { return this.logger.debug(message); } if (level === 'warn') { return this.logger.warn(message); } } private stringifyParameters(parameters?: unknown[]) { try { return JSON.stringify(parameters); } catch { return ''; } } } export default DatabaseLogger; |
The last step is to use the above class in our TypeORM configuration:
database.module.ts
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
import { Module } from '@nestjs/common'; import { TypeOrmModule } from '@nestjs/typeorm'; import { ConfigModule, ConfigService } from '@nestjs/config'; import DatabaseLogger from './databaseLogger'; @Module({ imports: [ TypeOrmModule.forRootAsync({ imports: [ConfigModule], inject: [ConfigService], useFactory: (configService: ConfigService) => ({ type: 'postgres', logger: new DatabaseLogger(), host: configService.get('POSTGRES_HOST'), // ... }) }), ], }) export class DatabaseModule {} |
When we start looking into the logs from TypeORM, we notice that it often produces quite lengthy queries. For example, the below query happens when we retrieve the data of the user that attempts to log in:
Saving logs into a PostgreSQL database
So far, we’ve only been logging all of the messages to the console. While that might work fine when developing the application on our machine, it wouldn’t make a lot of sense in a deployed application. There are a lot of services that can help us gather and manage logs, such as DataDog and Loggly. They are not free of charge, though. Therefore, in this article, we save logs into a PostgreSQL database.
For starters, let’s create an entity for our log:
log.entity.ts
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
import { Column, CreateDateColumn, Entity, PrimaryGeneratedColumn } from 'typeorm'; @Entity() class Log { @PrimaryGeneratedColumn() public id: number; @Column() public context: string; @Column() public message: string; @Column() public level: string; @CreateDateColumn() creationDate: Date; } export default Log; |
Above, we use the @CreateDateColum decorator. If you want to know more about dates in PostgreSQL, check out Managing date and time with PostgreSQL and TypeORM
Once we’ve got the above done, let’s create a service that allows us to create logs:
logs.service.ts
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
import { Injectable } from '@nestjs/common'; import { InjectRepository } from '@nestjs/typeorm'; import { Repository } from 'typeorm'; import Log from './log.entity'; import CreateLogDto from './dto/createLog.dto'; @Injectable() export default class LogsService { constructor( @InjectRepository(Log) private logsRepository: Repository<Log> ) {} async createLog(log: CreateLogDto) { const newLog = await this.logsRepository.create(log); await this.logsRepository.save(newLog, { data: { isCreatingLogs: true } }); return newLog; } } |
Above, you can notice that we pass isCreatingLogs: true when saving our logs to the database. The above is because we need to overcome the issue of an infinite loop. When we store logs in the database, it causes SQL queries to be logged. When we log SQL queries, they are saved to the database, causing an infinite loop. Because of that, we need to adjust our DatabaseLogger slightly:
databaseLogger.ts
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 |
import { Logger as TypeOrmLogger, QueryRunner } from 'typeorm'; import { Logger as NestLogger } from '@nestjs/common'; class DatabaseLogger implements TypeOrmLogger { private readonly logger = new NestLogger('SQL'); logQuery(query: string, parameters?: unknown[], queryRunner?: QueryRunner) { if (queryRunner?.data?.isCreatingLogs) { return; } this.logger.log(`${query} -- Parameters: ${this.stringifyParameters(parameters)}`); } logQueryError(error: string, query: string, parameters?: unknown[], queryRunner?: QueryRunner) { if (queryRunner?.data?.isCreatingLogs) { return; } this.logger.error(`${query} -- Parameters: ${this.stringifyParameters(parameters)} -- ${error}`); } logQuerySlow(time: number, query: string, parameters?: unknown[], queryRunner?: QueryRunner) { if (queryRunner?.data?.isCreatingLogs) { return; } this.logger.warn(`Time: ${time} -- Parameters: ${this.stringifyParameters(parameters)} -- ${query}`); } logMigration(message: string) { this.logger.log(message); } logSchemaBuild(message: string) { this.logger.log(message); } log(level: 'log' | 'info' | 'warn', message: string, queryRunner?: QueryRunner) { if (queryRunner?.data?.isCreatingLogs) { return; } if (level === 'log') { return this.logger.log(message); } if (level === 'info') { return this.logger.debug(message); } if (level === 'warn') { return this.logger.warn(message); } } private stringifyParameters(parameters?: unknown[]) { try { return JSON.stringify(parameters); } catch { return ''; } } } export default DatabaseLogger; |
Above, we don’t log SQL queries if they are involved in creating logs.
Now we need to extend the logger built into NestJS and use the LogsService:
customLogger.ts
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 |
import { Injectable, ConsoleLogger } from '@nestjs/common'; import { ConsoleLoggerOptions } from '@nestjs/common/services/console-logger.service'; import { ConfigService } from '@nestjs/config'; import getLogLevels from '../utils/getLogLevels'; import LogsService from './logs.service'; @Injectable() class CustomLogger extends ConsoleLogger { private readonly logsService: LogsService; constructor( context: string, options: ConsoleLoggerOptions, configService: ConfigService, logsService: LogsService ) { const environment = configService.get('NODE_ENV'); super( context, { ...options, logLevels: getLogLevels(environment === 'production') } ); this.logsService = logsService; } log(message: string, context?: string) { super.log.apply(this, [message, context]); this.logsService.createLog({ message, context, level: 'log' }) } error(message: string, stack?: string, context?: string) { super.error.apply(this, [message, stack, context]); this.logsService.createLog({ message, context, level: 'error' }) } warn(message: string, context?: string) { super.warn.apply(this, [message, context]); this.logsService.createLog({ message, context, level: 'error' }) } debug(message: string, context?: string) { super.debug.apply(this, [message, context]); this.logsService.createLog({ message, context, level: 'error' }) } verbose(message: string, context?: string) { super.debug.apply(this, [message, context]); this.logsService.createLog({ message, context, level: 'error' }) } } export default CustomLogger; |
We also need to create the LoggerModule so that we can add it into our AppModule:
logger.module.ts
1 2 3 4 5 6 7 8 9 10 11 12 13 |
import { Module } from '@nestjs/common'; import CustomLogger from './customLogger'; import { ConfigModule } from '@nestjs/config'; import LogsService from './logs.service'; import { TypeOrmModule } from '@nestjs/typeorm'; import Log from './log.entity'; @Module({ imports: [ConfigModule, TypeOrmModule.forFeature([Log])], providers: [CustomLogger, LogsService], exports: [CustomLogger], }) export class LoggerModule {} |
The final step is to call the useLogger method to inject our custom logger into the application:
main.ts
1 2 3 4 5 6 7 8 9 10 11 12 13 |
import { NestFactory } from '@nestjs/core'; import { AppModule } from './app.module'; import CustomLogger from './logger/customLogger'; async function bootstrap() { const app = await NestFactory.create(AppModule, { bufferLogs: true, }); app.useLogger(app.get(CustomLogger)); // ... } bootstrap(); |
We could store some data in separate columns. Fore example, we could do that with the HTTP methods to be able to query the logs looking only for POST request, for example.
Summary
In this article, we’ve gone through the basics of logging with NestJS and TypeORM. We’ve learned about various log levels and how we can log messages directly and through middleware. We’ve also learned how to save our logs into an SQL database. Doing that has some benefits. For example, we could store more data in separate columns and use them when querying the data.
Even if saving logs into an SQL database has some advantages, the performance might not be the best if we have a lot of logs. Also, it could fill up the available space of our database. Therefore, it might be a good idea to look into services such as DataDog and Loggly. However, it is a topic for another article, so stay tuned!
one little error. if is not indicated context the error is like so:
ERROR [AuthController] Data too long for column ‘password’ at row 1
ERROR [AuthController] undefined
two records is created and not one. why not use this.context
error (message: string, stack?: string) {
super.error(message, stack, this.context)
this.logsService.createLog({
message,
context: this.context,
stack: stack,
level: ‘error’
})
}
Hey can you please also demonstrate implementing logger to mongoose
How would you limit logging to only specific routes
HI !
Thank you for your article but I am so confusing that in case we need to create brand new instance of Logger in service class, so why we need to setup in main.ts like below
const app = await NestFactory.create(AppModule, {
logger: console // or LogLevel or LogService,
});
why we need to do that, I have read the code and do not know how it can related in Service and in app
If we create brand new instance of Logger in each service how we can make sure that both are in same config