NestJS Enterprise Backend APIs · Урок

Логирование с Winston/Pino

Настройте структурированное логирование с помощью популярных библиотек Winston или Pino, чтобы эффективно отслеживать события и ошибки приложения.

Урок 2 из 312 шагов

«Логирование с Winston/Pino» — бесплатный урок NestJS Enterprise Backend APIs на CoddyKit. Это урок 2 из 3. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения 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!

Можно начать бесплатно

Изучай TypeScript с ИИ-репетитором — бесплатно

Пиши и запускай код прямо в браузере, получай мгновенную помощь от ИИ-репетитора 24/7 и продолжи учиться на сайте или в приложении.

Курсы
20
Уроки
76

Часто задаваемые вопросы

Урок «Логирование с Winston/Pino» бесплатный?

Да — полный текст урока «Логирование с Winston/Pino» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс NestJS Enterprise Backend APIs, подпишись на CoddyKit PRO. Курс NestJS Enterprise Backend APIs содержит 3 уроков всего.

Чему я научусь в уроке «Логирование с Winston/Pino»?

Настройте структурированное логирование с помощью популярных библиотек Winston или Pino, чтобы эффективно отслеживать события и ошибки приложения. Ты практикуешь NestJS Enterprise Backend APIs с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.

Нужен ли мне опыт, чтобы начать NestJS Enterprise Backend APIs?

Предыдущий опыт не требуется. NestJS Enterprise Backend APIs на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 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