NodeJS 如何使用Winston在子目录而不是根目录下设置日志?

dwbf0jvd  于 2023-01-16  发布在  Node.js
关注(0)|答案(3)|浏览(161)

我想在名为logs的目录中设置nodejs项目的日志
根据文件here
我正在:

winston.add(winston.transports.File, { filename: 'logs/mylogs.log' });

但它什么也没做。
我如何达到同样的效果?

du7egjpx

du7egjpx1#

将下面的代码放入服务器文件中。

var winston = require('winston');
var fs = require( 'fs' );
var path = require('path');
var logDir = 'log'; // directory path you want to set
if ( !fs.existsSync( logDir ) ) {
    // Create the directory if it does not exist
    fs.mkdirSync( logDir );
}
var logger = new (winston.Logger)({
    transports: [
        new (winston.transports.Console)({
            colorize: 'all'
        }),
        new (winston.transports.File)({filename: path.join(logDir, '/log.txt')})
    ]
});
logger.info("Anything you want to write in logfile");
2ul0zpep

2ul0zpep2#

Winston提供了在创建日志文件时设置dirname的选项。
默认情况下,Winston创建项目根目录:

new transports.File({
  filename: 'errors.log',
  dirname: 'logs',
  level: 'error',
})

例如,如果您希望日志位于src目录中:

new transports.File({
  filename: 'errors.log',
  dirname: './src/logs',
  level: 'error',
})

完整代码示例:

import { createLogger, transports, format } from 'winston'
const { timestamp, combine, json, errors } = format

const buildLogger = () => {
  return createLogger({
    format: combine(
      timestamp(),
      errors({stack: true}),
      json()
    ),
    defaultMeta: {service: "your-service"},
    transports: [
      new transports.File({
        filename: 'events.log',
        dirname: 'logs',
        level: 'info',
      }),
      new transports.File({
        filename: 'errors.log',
        dirname: 'logs',
        level: 'error',
      }),
    ]
  })
}

export default buildLogger
nfs0ujit

nfs0ujit3#

应使用相对路径**(点和反斜杠)**:

winston.add(winston.transports.File, { filename: './logs/mylogs.log' });

相关问题