1

winston ロガーがあり、ロガーが実行されているファイルのファイル名をロガー情報オブジェクトのラベル オブジェクトとして設定したいと考えています。例えば:
[info]:[callingFileName.js] - 19.06.2019 14:09:19: [message]:...

これが私のコードです:

'use strict';
const { createLogger, format, transports } = require('winston');
const winston = require('winston');
const path = require('path');
var appRoot = require('app-root-path');

const { splat, combine, timestamp, colorize, printf, label } = winston.format;

const o = {
  a: [1, 2, [[
    'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do ' +
      'eiusmod tempor incididunt ut labore et dolore magna aliqua.',
    'test',
    'foo']], 4],
  b: new Map([['za', 1], ['zb', 'test']])
};

var options = {
      debugfile: {
        level: 'debug',
        filename: `${appRoot}/logs/debug.log`,
        handleExceptions: true,
        json: true,
        maxsize: 5242880, // 5MB
        maxFiles: 5,
        colorize: false,
      },
      errorfile: {
        level: 'error',
        filename: `${appRoot}/logs/error.log`,
        handleExceptions: true,
        json: true,
        maxsize: 5242880, // 5MB
        maxFiles: 5,
        colorize: false,
      },
      console: {
        colorize: true,
        handleExceptions: true,
        prettyPrint: true,
        json: true,

      }
    };

    const customFormat = printf(info => `[${info.level}]:[${info.label}] - ${info.timestamp}: [message]: ${info.message}  ${info.meta? JSON.stringify(info.meta) : ''}`);


    const simplelogger = createLogger({
      name: "debug-console",
      format: combine(
        colorize({all:false}),
        timestamp({
          format: 'DD.MM.YYYY HH:mm:ss'
        }),
        label({ 
          label: path.basename(process.mainModule.filename) 
        }),
        splat(),
        customFormat
      ),
      transports: [
        new transports.Console(options.console),
        new transports.File( options.errorfile),
        new transports.File( options.debugfile)
      ]
    });

ラベル部分は次のとおりです。

label({ label: path.basename(process.mainModule.filename) }),

しかし、プログラムを起動すると を実行するという問題があるnpm run index.jsため、呼び出し元のファイルは常に index.js label: としてログに記録されます[info]:[index.js] - 19.06.2019 14:09:19: [message]: ...logger.log()関数を実行しているファイル名としてラベルを動的に設定することは何とか可能ですか? または、 index.js 以外の新しいファイルにいるたびに、新しいクラス/インスタンスを作成する必要がありますか?

編集: npm logat モジュールに切り替えました。これにより、3 行のコードで問題がすぐに解決されました。しかし、ウィンストンで簡単な解決策はありますか? logat を使用すると winston はもう必要ないことがわかりました。

4

1 に答える 1