Winston/Pino를 활용한 로깅
Winston이나 Pino 같은 인기 라이브러리로 구조화된 로깅을 설정하여 애플리케이션 이벤트와 오류를 효과적으로 추적합니다.
Winston/Pino를 활용한 로깅은(는) CoddyKit의 무료 NestJS Enterprise Backend APIs 강의입니다. 이것은 3개 중 2번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 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를 활용한 로깅” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 NestJS Enterprise Backend APIs 강의 전체를 잠금 해제할 수 있습니다. NestJS Enterprise Backend APIs 강의에는 총 3개의 강의가 포함되어 있습니다.
“Winston/Pino를 활용한 로깅”에서 뭘 배우나요?
Winston이나 Pino 같은 인기 라이브러리로 구조화된 로깅을 설정하여 애플리케이션 이벤트와 오류를 효과적으로 추적합니다. 브라우저에서 직접 실행하는 실습 코드로 NestJS Enterprise Backend APIs을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
NestJS Enterprise Backend APIs을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 NestJS Enterprise Backend APIs은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 3개 중 2번째 강의입니다.
“Winston/Pino를 활용한 로깅” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 NestJS Enterprise Backend APIs 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 NestJS Enterprise Backend APIs 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- 요청률 제한과 조절
- Winston/Pino를 활용한 로깅
- Prometheus를 활용한 모니터링