0Pricing
NestJS Enterprise Backend APIs · 课时

使用 Winston/Pino 进行日志记录

使用 Winston 或 Pino 等热门库设置结构化日志记录,以有效跟踪应用事件和错误。

使用 Winston/Pino 进行日志记录 是 CoddyKit 上的免费 NestJS Enterprise Backend APIs 课时。 这是第 2 节课,共 3 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 NestJS Enterprise Backend APIs 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 NestJS Enterprise Backend APIs 课程共包含 3 节课。

本课时的部分内容尚未翻译,以英文显示。

Why Logging Matters

When building applications, knowing what's happening inside is crucial. This is where logging comes in!

Logging is the process of recording events and messages from your application as it runs. These logs help you:

  • Debug issues
  • Monitor performance
  • Understand user behavior

The Power of Structured Logs

Traditional logs can be hard to read and analyze. Structured logging writes log messages in a consistent, machine-readable format, usually JSON.

Why is this better?

  • Easy Analysis: Tools can parse JSON logs automatically.
  • Searchable: Quickly find specific events or errors.
  • Consistent: All logs follow the same pattern, making debugging faster.

Introducing Winston Logger

Winston is a highly popular and flexible logging library for Node.js. It's known for its modularity, allowing you to customize how logs are formatted and where they are sent.

Key features include:

  • Transports: Send logs to multiple destinations.
  • Formats: Control how your log messages look.
  • Levels: Define severity (e.g., info, warn, error).

Your First Winston Logger

Let's set up a basic Winston logger that outputs to the console. First, you'd install it: npm install winston

Here's a simple example:

const winston = require('winston');

const logger = winston.createLogger({
  level: 'info',
  format: winston.format.json(),
  transports: [
    new winston.transports.Console()
  ],
});

logger.info('Hello from Winston!');
logger.warn('This is a warning.');
logger.error('Something went wrong!');

Sending Logs to Files

Winston's transports let you direct logs to different places. Besides the console, a common transport is a file.

Using a file transport helps persist logs for later review, especially in production environments.

const winston = require('winston');

const logger = winston.createLogger({
  level: 'info',
  format: winston.format.json(),
  transports: [
    new winston.transports.Console(),
    new winston.transports.File({ filename: 'app.log' })
  ],
});

logger.info('This log goes to console and app.log!');
logger.error('Error details here.', { component: 'AuthService' });

Discovering Pino Logger

Pino is another powerful logging library, specifically designed for speed and low overhead. If performance is a critical concern for your application, Pino is an excellent choice.

It focuses on:

  • Extreme Performance: Very fast logging, minimal impact on your app.
  • JSON Output: By default, it logs in JSON for easy parsing.
  • Extensible: Though minimal, it's highly configurable.

Your First Pino Logger

Setting up Pino is straightforward. Install it first: npm install pino

Pino logs to stdout (console) by default, making it simple to pipe logs to other tools.

const pino = require('pino');

const logger = pino({
  level: 'info',
  base: null // Remove default base properties like pid, hostname
});

logger.info('Hello from Pino!');
logger.warn('A warning from Pino.');
logger.error({ error: 'DB_CONN_FAILED', message: 'Could not connect' }, 'Database error');

Custom NestJS LoggerService

NestJS uses its own LoggerService internally. To use Winston or Pino, you'll replace the default NestJS logger.

You can create a custom logger class that implements LoggerService and uses your chosen library. This makes your custom logger available throughout your NestJS application via Dependency Injection.

import { LoggerService } from '@nestjs/common';
import * as winston from 'winston';

export class MyWinstonLogger implements LoggerService {
  private logger: winston.Logger;

  constructor() {
    this.logger = winston.createLogger({
      level: 'info',
      format: winston.format.json(),
      transports: [
        new winston.transports.Console(),
      ],
    });
  }

  log(message: string, context?: string) {
    this.logger.info(message, { context });
  }

  error(message: string, trace?: string, context?: string) {
    this.logger.error(message, { trace, context });
  }

  warn(message: string, context?: string) {
    this.logger.warn(message, { context });
  }

  debug(message: string, context?: string) {
    this.logger.debug(message, { context });
  }

  verbose(message: string, context?: string) {
    this.logger.verbose(message, { context });
  }
}

Adding Context to Logs

When logs become extensive, identifying the source of a message is key. Contextual logging adds extra information (like a class name, request ID, or user ID) to each log entry.

This makes it much easier to filter and understand logs, especially in complex microservice architectures or when debugging specific user flows.

const winston = require('winston');

const logger = winston.createLogger({
  level: 'info',
  format: winston.format.json(),
  transports: [
    new winston.transports.Console()
  ],
});

function processOrder(orderId) {
  logger.info('Processing order', { orderId, module: 'OrderService' });
  // ... more logic
  logger.warn('Order stock low', { orderId, sku: 'PROD-XYZ' });
}

processOrder('ORD-12345');

Choosing Your Logger

Both Winston and Pino are excellent choices, but they have different strengths:

  • Winston: Highly flexible with many transports and formatting options. Great for complex logging requirements.
  • Pino: Extremely fast and low overhead, ideal for performance-critical applications or high-throughput microservices.

Your choice often depends on your project's specific needs for flexibility versus raw performance.

Logging Library Check

You've learned about the benefits of structured logging and how to set up Winston and Pino.

Consider the following features:

  • High performance and low overhead.
  • Default JSON output.
  • Primarily logs to stdout.

Which logging library is best described by these characteristics?

Logging Essentials Recap

Great job! In this lesson, you explored the importance of structured logging for application observability and debugging.

  • We introduced Winston for its flexibility and extensive transport options.
  • We covered Pino for its unparalleled performance and default JSON output.
  • You learned how to integrate these powerful libraries into your NestJS applications using a custom LoggerService.

Well-implemented logging is key to maintaining healthy and understandable applications!

常见问题解答

「使用 Winston/Pino 进行日志记录」课时是免费的吗?

是的 — 「使用 Winston/Pino 进行日志记录」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 NestJS Enterprise Backend APIs 课程的其余内容,请升级到 CoddyKit PRO。 NestJS Enterprise Backend APIs 课程共包含 3 节课。

「使用 Winston/Pino 进行日志记录」这节课中我会学到什么?

使用 Winston 或 Pino 等热门库设置结构化日志记录,以有效跟踪应用事件和错误。 你通过在浏览器中直接运行的动手代码来练习 NestJS Enterprise Backend APIs,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 NestJS Enterprise Backend APIs 需要有经验吗?

无需任何先前经验。CoddyKit 上的 NestJS Enterprise Backend APIs 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 2 节课,共 3 节。

「使用 Winston/Pino 进行日志记录」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 NestJS Enterprise Backend APIs 课中编写并运行代码吗?

能。每节 NestJS Enterprise Backend APIs 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 速率限制与节流
  2. 使用 Winston/Pino 进行日志记录
  3. 使用 Prometheus 进行监控
← 返回 NestJS Enterprise Backend APIs