Skip to content
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

docs(logging): add logging with timestamp enabled #2992

Open
wants to merge 6 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions content/techniques/logger.md
Original file line number Diff line number Diff line change
Expand Up @@ -187,6 +187,33 @@ That way if we follow the steps from the previous section and call `app.useLogge

This should be suitable for most cases. But if you need more customization (like adding and calling custom methods), move to the next section.

#### Logs with timestamps

You can enable Nest like system logging by providing the optional `timestamp: true` setting when creating the logger instance.

```typescript
import { Logger, Injectable } from '@nestjs/common';

@Injectable()
class MyService {
private readonly logger = new Logger(MyService.name, { timestamp: true }); // optional timestamp parameter to enable timestamps

doSomething() {
this.logger.log('Doing something with timestamp here ->');
}
}
```

This will print the output in the following manner:

```bash
[Nest] 19096 - 04/19/2024, 7:12:59 AM [MyService] Doing something with timestamp here +5ms
```

Notice the `+5ms` at the end of the line above.

For each log statement, the time difference from the last message will be calculated and printed at the end of the line.

#### Injecting a custom logger

To start, extend the built-in logger with code like the following. We supply the `scope` option as configuration metadata for the `ConsoleLogger` class, specifying a [transient](/fundamentals/injection-scopes) scope, to ensure that we'll have a unique instance of the `MyLogger` in each feature module. In this example, we do not extend the individual `ConsoleLogger` methods (like `log()`, `warn()`, etc.), though you may choose to do so.
Expand Down