web-dev-qa-db-fra.com

Comment changer la sortie de mon nœud winston JSON en une seule ligne

Lorsque je crée un enregistreur de console nodejs winston et que je définis json:true, il affiche toujours les journaux JSON au format multiligne. Si je les redirige vers un fichier et que j'essaye de grep ce fichier, mes hits grep n'incluent qu'une partie de la ligne de journal. Je veux que Winston produise mes lignes de journal au format JSON, mais pas pour imprimer assez le JSON

Voici ma config (coffeescript, excuses):

winston = require 'winston'
logger = new (winston.Logger)(
  transports: [
    new winston.transports.Console({
     json: true
    })
  ]
)

Et quelques exemples de sortie:

{
  "name": "User4",
  "level": "info",
  "message": "multi line whyyyyy"
}
15
zayquan

winston 3.x (version actuelle)

Formateur par défaut

const winston = require('winston');
const logger = winston.createLogger({
  format: winston.format.json(),
  transports: [
    new winston.transports.Console()
  ]
});

Exemple

const test = { t: 'test', array: [1, 2, 3] };
logger.info('your message', test);
// logger output:
// {"t":"test","array":[1,2,3],"level":"info","message":"your message"}

Formateur personnalisé

const winston = require('winston');

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

// meta param is ensured by splat()
const myFormat = printf(({ timestamp, level, message, meta }) => {
  return `${timestamp};${level};${message};${meta? JSON.stringify(meta) : ''}`;
});

const logger = winston.createLogger({
  format: combine(
    timestamp(),
    splat(),
    myFormat
  ),
  transports: [
    new winston.transports.Console()
  ]
});

Exemple:

const test = { t: 'test', array: [1, 2, 3] };
// NOTE: wrapping object name in `{...}` ensures that JSON.stringify will never 
// return an empty string e.g. if `test = 0` you won't get any info if 
// you pass `test` instead of `{ test }` to the logger.info(...)
logger.info('your message', { test });
// logger output:
// 2018-09-18T20:21:10.899Z;info;your message;{"test": {"t":"test","array":[1,2,3]}}

winston 2.x (version héritée)

Il semble que la réponse acceptée soit dépassée. Voici comment procéder pour la version actuelle de Winston (2.3.1):

var winston = require('winston');
var logger = new (winston.Logger)({
  transports: [
    new (winston.transports.Console)({
     json: true,
     stringify: (obj) => JSON.stringify(obj),
    })
  ]
})

Notez les parenthèses autour de winston.transports.Console.

27
jmarceli

Les transports winston fournissent un moyen de remplacer la méthode stringify, donc en modifiant la configuration ci-dessus, j'ai obtenu une sortie JSON sur une seule ligne.

Nouvelle configuration:

winston = require('winston')
logger = new (winston.Logger)({
  transports: [
    new winston.transports.Console({
     json: true,
     stringify: (obj) => JSON.stringify(obj)
    })
  ]
})
3
zayquan

"winston": "^3.0.0"

function createAppLogger() {
  const { combine, timestamp, printf, colorize } = format;

  return createLogger({
    level: 'info',
    format: combine(
      colorize(),
      timestamp(),
      printf(info => {
        return `${info.timestamp} [${info.level}] : ${JSON.stringify(info.message)}`;
      })
    ),
    transports: [new transports.Console()]
  });
}

Production:

2018-08-11T13:13:37.554Z [info] : {"data":{"hello":"Hello, World"}}

3
slideshowp2

Sur "winston": "^3.2.1"

C'est très bien pour moi

const {createLogger, format} = require('winston');

// instantiate a new Winston Logger with the settings defined above
var logger = createLogger({

    format: format.combine(
      format.timestamp(),
      // format.timestamp({format:'MM/DD/YYYY hh:mm:ss.SSS'}),
      format.json(),
      format.printf(info => {
        return `${info.timestamp} [${info.level}] : ${info.message}`;
      })
  ),
  transports: [
    new winston.transports.File(options.file),
    new winston.transports.Console(options.console)
  ],
  exitOnError: false, // do not exit on handled exceptions
});
1
Gajen Sunthara
winston.format.printf(
    info => `${info.timestamp} ${info.level}: ${JSON.stringify(info.message, null, 2)}`))

va assez imprimer l'objet json

0
sohel