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

Moment格式化时间在winston.transports.File中不生效问题求助

Fixing Winston Timestamp Format for File & MongoDB Transports

Hey there! I see you're having trouble getting your custom Moment.js timestamp to work with Winston's File and MongoDB transports, even though it works fine for Console. Let's break down why this happens and how to fix it.

The Root Cause

Winston doesn't automatically inherit the top-level timestamp configuration from the Logger to individual transports. Each transport (Console, File, MongoDB) has its own independent settings for timestamp handling—so you need to explicitly set the timestamp function for each transport that needs it. On top of that, the MongoDB transport has some special behavior around how it stores timestamps by default.

Step-by-Step Solution

First, let's create a reusable timestamp function to avoid repeating code, then apply it to each transport:

const moment = require('moment');
const winston = require('winston');

// Reusable custom timestamp function
const getCustomTimestamp = () => moment().format('YYYY-MM-DD hh:mm:ss');

const logger = new winston.Logger({
  level: 'debug',
  transports: [
    // Console transport (already working, let's align it with the others)
    new winston.transports.Console({
      timestamp: getCustomTimestamp,
      formatter: (options) => {
        return `${options.timestamp()} [${options.level.toUpperCase()}] ${options.message}`;
      }
    }),
    // File transport: add the timestamp function explicitly here
    new winston.transports.File({
      filename: 'application.log',
      level: 'debug',
      timestamp: getCustomTimestamp,
      formatter: (options) => {
        return `${options.timestamp()} [${options.level.toUpperCase()}] ${options.message}`;
      }
    }),
    // MongoDB transport: handle timestamp formatting properly
    new winston.transports.MongoDB({
      db: 'dbpath',
      collection: 'Logs',
      level: 'error',
      capped: true,
      // By default, MongoDB transport stores timestamps as Date objects.
      // If you want to store the formatted string instead, use a formatter:
      formatter: (options) => {
        return {
          timestamp: getCustomTimestamp(),
          level: options.level,
          message: options.message,
          meta: options.meta || {}
        };
      }
      // Alternative: Keep timestamp as Date object (better for time-range queries)
      // timestamp: () => new Date(), // Default behavior, format when querying logs later
    })
  ]
});

Key Notes

  • Explicit Transport Configuration: Always set timestamp directly on each transport—don't rely on the top-level Logger setting for anything except the Console (and even then, explicit setup is more reliable).
  • MongoDB Transport Quirk: Storing timestamps as formatted strings makes date-range queries in MongoDB less efficient. If you need to filter logs by time later, stick with the default Date object and format the timestamp when retrieving logs instead.
  • Formatter for Readability: The formatter option ensures your custom timestamp is actually included in the log output (for Console/File) or stored correctly (for MongoDB). Without it, some transports might fall back to default formatting.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 04:04:10