Winston: タイムスタンプ形式をカスタマイズする方法は?

作成日 2017年11月10日  ·  18コメント  ·  ソース: winstonjs/winston

3.0.0-rc1を使用していますが、タイムスタンプの形式をカスタマイズする方法についてのドキュメントが明確ではありません。 助けてください。

ありがとう、
アルバロ

最も参考になるコメント

これは、タイムスタンプを印刷するという最も単純な要件(とにかくデフォルトであるはずです)のために非常に複雑です:/

全てのコメント18件

ソースコードを読んで、フォーマットをカスタマイズするのに役立てることができます。 私はあなたに私の例をあげることができます。

const winston = require('winston');
const moment = require('moment');
const util = require('util');
const MESSAGE = Symbol.for('message');

const logger = winston.createLogger({
    level: 'info',
    format: winston.format.combine(
        winston.format(function(info, opts) {
            prefix = util.format('[%s] [%s]', moment().format('YYYY-MM-DD hh:mm:ss').trim(), info.level.toUpperCase());
            if (info.splat) {
                info.message = util.format('%s %s', prefix, util.format(info.message, ...info.splat));
            } else {
                info.message = util.format('%s %s', prefix, info.message);
            }
            return info;
        })(),
        winston.format(function(info) {
            info[MESSAGE] = info.message + ' ' + JSON.stringify(
                Object.assign({}, info, {
                    level: undefined,
                    message: undefined,
                    splat: undefined
                })
            );
            return info;
        })()
    ),
    transports: [
        new winston.transports.Console(),
        new winston.transports.File({ filename: './logs/bitcoin.log' })
    ]
});

これは、タイムスタンプを印刷するという最も単純な要件(とにかくデフォルトであるはずです)のために非常に複雑です:/

これが私がすることです...

//logger.js

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

// create formatter for dates used as timestamps
//const tsFormat = () => (new Date()).toLocaleTimeString();
const tsFormat = () => moment().format('YYYY-MM-DD hh:mm:ss').trim();

// define a logger with 2 transports - console and a file
const logger = new (winston.Logger)({
  transports: [
    // colorize the output to the console
    new (winston.transports.Console)({
        timestamp: tsFormat,
        colorize: true
    }),
    new winston.transports.File({
        filename: './logs/ttracker.log',
        timestamp: tsFormat,            // makes timestamp 'pretty'
        json: false                 // makes log format just like console output
    })
  ]
});

// set logging level one of { error: 0, warn: 1, info: 2, verbose: 3, debug: 4, silly: 5 }
logger.level = 'debug';

module.exports = logger;

PSタイムスタンプ:trueを設定することで得られるデフォルトの形式が気に入らないため、タイムスタンプ:を関数に設定するだけです。つまり、2017-12-05T08:22:09.179Z

@ jimwhurr-私にとって、あなたのコード(ノードv6.11.0)は以下を生成します:

Error: winston.Logger was moved in [email protected].
Use a winston.createLogger instead.
    at new <anonymous> (/Users/adrian/Documents/winston_test/node_modules/winston/lib/winston/common.js:162:15)
    at Object.<anonymous> (/Users/adrian/Documents/winston_test/index.js:7:16)
    at Module._compile (module.js:570:32)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
    at Module.runMain (module.js:604:10)
    at run (bootstrap_node.js:389:7)
    at startup (bootstrap_node.js:149:9)

ここで例を取り上げて、より単純なスタンドアロンの例を作成しました。

https://gist.github.com/ah/d02bd4ff238e5923fcf5369233e51401

const winston = require('winston');
const MESSAGE = Symbol.for('message');

const jsonFormatter = (logEntry) => {
  const base = { timestamp: new Date() };
  const json = Object.assign(base, logEntry)
  logEntry[MESSAGE] = JSON.stringify(json);
  return logEntry;
}

const logger = winston.createLogger({
  level: 'info',
  format: winston.format(jsonFormatter)(),
  transports: new winston.transports.Console(),
});

logger.info('message content', { "context": "index.js", "metric": 1 })
logger.info('message content 2')

出力:

{"timestamp":"2017-12-07T16:07:10.518Z","context":"index.js","metric":1,"level":"info","message":"message content"}
{"timestamp":"2017-12-07T16:07:10.520Z","message":"message content 2","level":"info"}

こんにちは、タイムスタンプを使用してログを記録するための別のオプションがあります(3.0.0-rc0でテスト済み):

const winston = require( 'winston');
var customFormat = winston.format.combine(
winston.format(
関数dynamicContent(info、opts){
info.level = '情報';
if(info.time){
var dt = new Date()、
date_now = dt.getDate()<10? '0' + dt.getDate():dt.getDate()、
month_now =(dt.getMonth()+ 1)<10? '0' +(dt.getMonth()+ 1):( dt.getMonth()+ 1)、
year_now = dt.getFullYear()、
hrs_now = dt.getHours()、
mins_now = dt.getMinutes()、
secs_now = dt.getSeconds()、
millisec_now = dt.getMilliseconds();
info.time = '' + date_now + '-' + month_now + '-' + year_now + '' + hrs_now + ':' + mins_now + ':' + secs_now + ':' + millisec_now + '';
}
情報を返す;
}
)()、
winston.format.simple()//フォーマット出力。使用も可能:.json()(。simpleの代わりに)
);

const logger = winston.createLogger({
レベル: '情報'、
フォーマット:customFormat、
トランスポート:[
new winston.transports.File({filename: 'logs.log'})
]
});
module.exports = logger; `

そしてログの場合:

logger.log({ time: true, level: 'info', message: 'message for logging' });

役に立つかもしれません。

フォーマット文字列を使用してタイムスタンプをカスタマイズできます。

winston.createLogger({
    level: ...
    format: winston.format.combine(
        winston.format.label({ label: '[my-label]' }),
        winston.format.timestamp({
            format: 'YYYY-MM-DD HH:mm:ss'
        }),
        winston.format.simple()
    ),
    transports: ...
});
winston.createLogger({
    level: ...
    format: winston.format.combine(
        winston.format.label({ label: '[my-label]' }),
        winston.format.timestamp({
            format: 'YYYY-MM-DD HH:mm:ss'
        }),
        winston.format.simple()
    ),
    transports: ...
});

これはドキュメントにあるはずです。 @felipemullenありがとうございます!

@felipemullenそのサンプルを提供してくれてありがとう。 @ricardoaatに同意します。これはドキュメントに含まれているはずなので、現在は次のようになっています: examples / custom-timestamp.js

@youngkylejanああああ.....それは良い助けです...
しかし、私は問題があります...ログの最後の{}は何ですか?

[2018-05-14 04:39:52] [INFO] localhost:3000で実行されているAPI {}

私はウィンストンに不慣れで、言うまでもなく、ドキュメントをフォローするのは驚くほど難しいです:(

どういうわけか、私は次の明らかにより単純な解決策に行き着きました:

winston.createLogger({
    level: ...
    format: winston.format.printf(info => `${new Date().toISOString()} ${info.message}`),
    transports: ...
});

@hosseinGanjyar
変化する
info[MESSAGE] = info.message + ' ' + JSON.stringify(...);
ただ
info[MESSAGE] = info.message;

これは私のために働いた。

設定:

  • JSONログ
  • タイムスタンプ
  • ログローテーション
  • ファイルとコンソールのログ
import winston from 'winston';
import DailyRotateFile from 'winston-daily-rotate-file';
import fs from 'fs';
import path from 'path';

const LOG_DIR = path.normalize(`${process.cwd()}/logs`);

if (!fs.existsSync(LOG_DIR)) {
  fs.mkdirSync(LOG_DIR);
}

const logger = winston.createLogger({
  exitOnError: false,
  silent: process.env.SUPPRESS_LOGS,
  level: process.env.LOG_LEVEL || 'info',
  format: winston.format.combine(
    winston.format.timestamp({
      format: 'YYYY-MM-DD HH:mm:ss',
    }),
    winston.format.json(),
  ),
  transports: [
    new winston.transports.Console(),
    new DailyRotateFile({
      dirname: LOG_DIR,
      filename: '%DATE%.log',
      datePattern: 'YYYY-MM-DD-HH',
      zippedArchive: false,
      maxSize: '1m',
      maxFiles: '14d',
    }),
  ],
});

export default logger;

これはすべてwinston3.0.0と@types / winston2.3.9の場合です

const consoleFormat = winston.format.printf(info => {
    const d = new Date();
    const timestamp = d.toLocaleTimeString();
    return `${timestamp} ${info.level}: ${info.message}`;

これは、現在のタイムゾーンの時刻であるタイムスタンプを返します。
私が使用するfileFormatの場合

const timestamp = `${d.toISOString()} (${d.toLocalTimeString()})`;

それから

const logger = winston.createLogger({
    level: "debug",
    format: fileFormat,
    transports: [ new winston.transports.File({ filename: "yourname.log", level: "debug"}) ]
});

おそらくレベルを2回必要としません。 しかし、それは私が現在使用しているものです。

フォーマット文字列を使用してタイムスタンプをカスタマイズできます。

winston.createLogger({
    level: ...
    format: winston.format.combine(
        winston.format.label({ label: '[my-label]' }),
        winston.format.timestamp({
            format: 'YYYY-MM-DD HH:mm:ss'
        }),
        winston.format.simple()
    ),
    transports: ...
});

命の恩人。 どうもありがとう!!!

YYYY-MM-DD HH:mm:ss以外のフォーマット文字列をカスタマイズする方法を見つけるためにここにいる人のために:winstonは内部でfechaを使用しているので、 fechaのドキュメントを参照できます。

これらの例はすべて、ログの残りのパラメーターを削除します。 format.simple()を使用し、最初にタイムスタンプのみを追加して残りから削除する場合は、次のように機能する可能性があります。

const simpleFormat = format.simple()
const MESSAGE = Symbol.for('message')
const simpleTimestamp = format(info => {
  const { timestamp, ...rest } = info
  const simpled = simpleFormat.transform(rest)
  if (typeof simpled !== 'boolean') {
    // @ts-ignore
    simpled[MESSAGE] = `${timestamp} ${simpled[MESSAGE]}`
  }
  return simpled
})

logger.add(new transports.Console({
  format: format.combine(
      format.timestamp(),
      format.colorize(),
      simpleTimestamp(),
  ),
}))
このページは役に立ちましたか?
0 / 5 - 0 評価