Winston: Wie kann ich das Zeitstempelformat anpassen?

Erstellt am 10. Nov. 2017  ·  18Kommentare  ·  Quelle: winstonjs/winston

Ich verwende 3.0.0-rc1 und die Dokumentation ist nicht klar, wie das Format des Zeitstempels angepasst werden kann. Bitte helfen Sie.

Danke,
Alvaro

Hilfreichster Kommentar

Dies ist so extrem kompliziert für die einfachste Anforderung, nur einen Zeitstempel zu drucken (der sowieso Standard sein sollte): /

Alle 18 Kommentare

Sie können den Quellcode lesen, um das Format selbst anzupassen. Ich kann Ihnen ein Beispiel von mir geben.

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' })
    ]
});

Dies ist so extrem kompliziert für die einfachste Anforderung, nur einen Zeitstempel zu drucken (der sowieso Standard sein sollte): /

Hier ist, was ich tue ...

//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 Ich setze nur timestamp: auf eine Funktion, weil mir das Standardformat nicht gefällt, das Sie erhalten, wenn Sie timestamp: true setzen, dh 2017-12-05T08:22:09.179Z

@jimwhurr - für mich erzeugt Ihr Code (Knoten 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)

Anhand der Beispiele hier habe ich ein einfacheres eigenständiges Beispiel erstellt:

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')

Ausgabe:

{"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"}

Hallo, hier ist eine weitere Option zum Protokollieren mit Zeitstempel (getestet auf 3.0.0-rc0):

const winston = require('winston');
var customFormat = winston.format.combine(
winston.format(
function dynamicContent(info, opts) {
info.level = 'info';
if(info.time) {
var dt = neues Datum(),
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+' ';
}
Rücksendeinformationen;
}
)(),
winston.format.simple() //Ausgabe formatieren, auch möglich: .json() (statt .simple)
);

const logger = winston.createLogger({
Ebene: 'Info',
Format: benutzerdefiniertes Format,
Transporte: [
new winston.transports.File({ Dateiname: 'logs.log' })
]
});
module.exports = logger;`

Und zum Protokoll:

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

Vielleicht wird es hilfreich sein.

Sie können den Zeitstempel mit einer Formatzeichenfolge anpassen:

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: ...
});

Das sollte in den Unterlagen stehen. @felipemullen Danke!

@felipemullen danke für die Bereitstellung dieser Probe. Stimmen Sie @ricardoaat zu, dies sollte in den Dokumenten stehen, also ... jetzt ist es: example /custom-timestamp.js

@youngkylejan oh oh ..... Das ist eine gute Hilfe ...
Aber ich habe ein Problem ... was ist {} am Ende des Protokolls?

[2018-05-14 04:39:52] [INFO] API läuft auf localhost:3000 {}

Ich bin neu bei Winston und muss sagen, die Dokumente sind überraschend schwer zu befolgen :(

Irgendwie bin ich auf die folgende scheinbar einfachere Lösung gekommen:

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

@hosseinGanjyar
Veränderung
info[MESSAGE] = info.message + ' ' + JSON.stringify(...);
zu einfach
info[MESSAGE] = info.message;

Das hat bei mir funktioniert.

Konfiguration:

  • JSON-Protokolle
  • Zeitstempel
  • Protokollrotation
  • Datei- und Konsolenprotokollierung
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;

Dies gilt alles für winston 3.0.0 und @types/winston 2.3.9

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

Dies gibt einen Zeitstempel zurück, der nur die Zeit in der aktuellen Zeitzone ist.
für fileFormat verwende ich

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

dann

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

braucht wahrscheinlich kein Level zweimal. aber das ist, was ich derzeit benutze.

Sie können den Zeitstempel mit einer Formatzeichenfolge anpassen:

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: ...
});

Lebensretter. Vielen Dank!!!

Für diejenigen, die hier sind, um herauszufinden, wie man die Formatzeichenfolge neben YYYY-MM-DD HH:mm:ss anpasst: winston verwendet fecha unter der Haube , Sie können also auf die fecha-Dokumentation verweisen.

Alle diese Beispiele entfernen Restparameter in Protokollen. Wenn Sie format.simple() verwenden und nur den Zeitstempel am Anfang hinzufügen und aus dem Rest entfernen möchten, funktioniert dies möglicherweise für Sie:

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(),
  ),
}))
War diese Seite hilfreich?
0 / 5 - 0 Bewertungen

Verwandte Themen

xungwoo picture xungwoo  ·  3Kommentare

alditis picture alditis  ·  3Kommentare

greenhat616 picture greenhat616  ·  3Kommentare

Buzut picture Buzut  ·  3Kommentare

anks333 picture anks333  ·  3Kommentare