繁体   English   中英

在节点 js 的 lof 文件中记录打印时显示当前日期和时间

[英]show current date and time when log print in lof file in node js

您能告诉我在打印/写入文件时如何在日志中添加时间戳吗? 这意味着it shows current data and time

我试过这样,但没有显示正确的 output。 我添加了这个

const consoleLogger = new winston.transports.Console({
  timestamp: function() {
    const today = moment();
    return today.format("DD-MM-YYYY");
  },
  format: winston.format.json(),
  colorize: true,
  level: "debug"
});

还是行不通

https://codesandbox.io/s/beautiful-kapitsa-j1sku

当前 output 无时间戳

{"message":"running → PORT (src/index.js:10)","level":"info"}

希望以下解决方案对您有用。

const { createLogger, format, transports } = require('winston');
const { combine, timestamp, printf} = format;

const transport = new transports.Console({
  exitOnError: false,
  format: combine(
    ...(environment === 'dev' ? [format.colorize()] : []),
    timestamp(),
    printf(info => `${info.timestamp} [${info.level}]: ${info.message}`)
  ),
  colorize: true,
  level: 'debug',
});

const myFormat = printf(({ level, message, timestamp }) => {
  return `${timestamp} ${level}: ${message}`;
});

const logger = createLogger({
  format: combine(timestamp(), appendTimestamp({ tz: 'Add your timezone'}), myFormat),
  transports: [transport],
  exceptionHandlers: [
    new transports.File({
      filename: 'FILE_NAME.log'
    }),
  ],
});

大多数选项,如timestampjson成为winston@3的格式化程序 您必须将 2 个格式化程序合二为一。

consoleLogger将变为:

const consoleLogger = new winston.transports.Console({
  timestamp: true,
  colorize: true,
  level: "debug",
  format: winston.format.combine(
    // the order is important
    winston.format.timestamp({
      format: "YYYY-MM-DD HH:mm:ss"
    }),
    winston.format.json()
  )
});

logger

const logger = winston.createLogger({
  transports: [consoleLogger]
});

我的完整示例: https://codesandbox.io/s/intelligent-knuth-yon2u

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM