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

如何用log4js基于当前日期分类日志并自动每日生成新文件?

解决log4js按日自动分割日志的问题

Got it, let's get your daily log rolling sorted out! The basic file appender you're using now only writes to a single static file—what you need is log4js's built-in dateFile appender, which is purpose-built for automatically creating new log files on a daily basis.

Here's the updated configuration that does exactly what you want:

module.exports.log = log4js.configure({
  appenders: {
    "log-info": {
      type: "dateFile",
      filename: "logs/info", // 基础文件名,不要加后缀,pattern会补上日期和扩展名
      pattern: ".yyyy-MM-dd.text", // 日期后缀格式,生成的文件会是 info.2024-05-20.text 这样
      alwaysIncludePattern: true, // 让当前正在写入的日志文件也带日期,避免新旧文件混淆
      createDir: true, // 自动创建logs目录(如果不存在的话)
      daysToKeep: 7, // 可选:保留最近7天的日志,超过自动删除
      compress: true // 可选:压缩旧日志文件(gzip格式)节省空间
    }
  },
  categories: {
    default: { appenders: ["log-info"], level: "info" }
  }
});

Let me break down the key changes for you:

  • type: "dateFile":替换原来的file类型,启用按日期滚动的日志功能
  • filename: "logs/info":设置基础文件名,把.text移到pattern里,确保每个日期的文件都带正确扩展名
  • pattern: ".yyyy-MM-dd.text":定义日志文件的日期后缀格式,你可以调整格式(比如改成.yyyyMMdd.text)
  • alwaysIncludePattern: true:默认当前写入的日志文件不带日期,开启后所有文件(包括正在写的)都带日期,更清晰
  • createDir: true:自动创建logs目录,避免因目录不存在导致日志写入失败

If you need to roll logs more frequently (like hourly), just adjust the pattern to something like .yyyy-MM-dd-hh.text—log4js will handle the rest automatically.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 03:57:31