You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Node.js新手求助:Winston日志分文件配置相关问题

Guide to Separating Winston Logs into Independent Files

Hey there! Since you're new to Node.js and Winston, let's break down how to refine your existing setup to get logs into separate files smoothly. You're already on the right track with using DailyRotateFile—let's fill in the gaps and make it work perfectly.

First, Fix the Basics

Your current code is missing a couple of key pieces:

  • You're using path but haven't imported it—add that at the top of your file.
  • You need to create a proper Winston logger instance (your let ... is incomplete).
  • It's helpful to handle the development environment with console logs for debugging.

Step-by-Step Refined Code

Here's a complete, working version of your configuration with explanations:

1. Import Required Modules

const winston = require('winston');
const { DailyRotateFile } = winston.transports; // Destructure for cleaner code
const path = require('path');
const fs = require('fs');

2. Ensure Log Directories Exist

Winston won't automatically create missing directories, so let's add code to handle that:

// Create logs directory if it doesn't exist
const baseLogDir = path.resolve(__dirname, '../logs');
if (!fs.existsSync(baseLogDir)) {
  fs.mkdirSync(baseLogDir, { recursive: true }); // Recursive creates nested folders
}

3. Configure Transports

We'll keep your existing daily rotation setup and add a console transport for development:

const transports = [];

if (process.env.NODE_ENV !== 'development') {
  // Transport for source 1 logs
  transports.push(new DailyRotateFile({
    filename: path.resolve(baseLogDir, '%DATE%/source1.log'),
    level: 'info',
    datePattern: 'YYYY-MM-DD',
    maxSize: '20m', // Optional: Split file when it hits 20MB
    maxFiles: '14d', // Optional: Keep logs for 14 days
    zippedArchive: true // Optional: Archive old logs as ZIP files
  }));

  // Transport for source 2 logs
  transports.push(new DailyRotateFile({
    filename: path.resolve(baseLogDir, '%DATE%/source2.log'),
    level: 'info',
    datePattern: 'YYYY-MM-DD',
    maxSize: '20m',
    maxFiles: '14d',
    zippedArchive: true
  }));
} else {
  // Development: Log to console with colors for readability
  transports.push(new winston.transports.Console({
    format: winston.format.combine(
      winston.format.colorize(),
      winston.format.simple()
    )
  }));
}

4. Create the Logger Instance

Now let's put it all together into a usable logger:

// Define a consistent log format
const logFormat = winston.format.combine(
  winston.format.timestamp({ format: 'YYYY-MM-DD HH:mm:ss' }),
  winston.format.printf(({ timestamp, level, message }) => {
    return `${timestamp} [${level.toUpperCase()}]: ${message}`;
  })
);

const logger = winston.createLogger({
  level: 'info', // Default minimum log level
  format: logFormat,
  transports: transports
});

How to Log to Specific Files

If you want to ensure certain logs only go to source1.log or source2.log, the cleanest approach is to create separate logger instances for each source:

// Logger for source 1
const source1Logger = winston.createLogger({
  level: 'info',
  format: logFormat,
  transports: [
    new DailyRotateFile({
      filename: path.resolve(baseLogDir, '%DATE%/source1.log'),
      level: 'info',
      datePattern: 'YYYY-MM-DD',
      maxSize: '20m',
      maxFiles: '14d'
    })
  ].concat(
    process.env.NODE_ENV === 'development' 
      ? [new winston.transports.Console({ format: winston.format.combine(winston.format.colorize(), winston.format.simple()) })] 
      : []
  )
});

// Logger for source 2
const source2Logger = winston.createLogger({
  level: 'info',
  format: logFormat,
  transports: [
    new DailyRotateFile({
      filename: path.resolve(baseLogDir, '%DATE%/source2.log'),
      level: 'info',
      datePattern: 'YYYY-MM-DD',
      maxSize: '20m',
      maxFiles: '14d'
    })
  ].concat(
    process.env.NODE_ENV === 'development' 
      ? [new winston.transports.Console({ format: winston.format.combine(winston.format.colorize(), winston.format.simple()) })] 
      : []
  )
});

Then use them like this:

// Logs to source1.log (and console in dev)
source1Logger.info('User logged in from source 1');

// Logs to source2.log (and console in dev)
source2Logger.info('API request processed by source 2');

Quick Tips

  • Set NODE_ENV: When running your app in production, set the environment variable:
    • Linux/macOS: NODE_ENV=production node your-app.js
    • Windows (Command Prompt): set NODE_ENV=production && node your-app.js
  • Customize Log Levels: If you need more granularity (like debug, warn, or error), adjust the level property in transports or the logger.
  • Add Metadata: Extend the log format to include extra details like request IDs or module names by modifying the printf function.

Let me know if you hit any issues getting this up and running—happy to help you tweak things further!

内容的提问来源于stack exchange,提问作者Andre1991

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 03:52:38