项目作者: Anubisss

项目描述 :
A simple winston JSON log formatter.
高级语言: JavaScript
项目地址: git://github.com/Anubisss/winston-json-log-formatter.git
创建时间: 2020-05-03T15:44:37Z
项目社区:https://github.com/Anubisss/winston-json-log-formatter

开源协议:MIT License

下载


winston-json-log-formatter

npm version

This is a very simple Node.js module which creates a console transport (by default) for winston to log messages in JSON format.

Requirements

  • Node.js >= 8.3.0
  • winston@3

Install

npm install winston-json-log-formatter

Usage/Features

Import the module in your source code which imports winston also.

  1. const winston = require('winston');
  2. const wjlf = require('winston-json-log-formatter');

Setup the console transport which will log in JSON.

  1. wjlf.setupTransport(winston);

You can log dates automatically.

  1. wjlf.setupTransport(winston, true);

Also you can bind properties to every log message.

  1. wjlf.setupTransport(winston, false, { requestId: 'id' });

If you want to use the formatter only then you can access it via wjlf.logFormatter

How to log: just use winston.

  1. winston.info('test message');
  2. winston.info('message with meta object', { propertyOne: 1, propertyTwo: 'two' });

Example Lambda handler function

  1. 'use strict';
  2. const winston = require('winston');
  3. const wjlf = require('winston-json-log-formatter');
  4. const handler = async (event, context) => {
  5. wjlf.setupTransport(winston, true, { awsRequestId: context.awsRequestId, foo: 'bar' });
  6. winston.log('info', 'starting', {
  7. nodeVersion: process.version,
  8. platform: process.platform,
  9. architecture: process.arch,
  10. timezoneOffset: new Date().getTimezoneOffset() / 60,
  11. });
  12. winston.info('test message');
  13. winston.error('error occurred', {
  14. error: {
  15. message: 'ERR_MSG',
  16. code: 145,
  17. },
  18. });
  19. return 'ok';
  20. };
  21. module.exports = {
  22. handler,
  23. };

Output log messages are filterable in AWS CloudWatch Logs.

JSON

  1. {"date":"2020-05-03T16:32:32.123Z","level":"info","message":"starting","meta":{"nodeVersion":"v12.16.1","platform":"linux","architecture":"x64","timezoneOffset":0},"awsRequestId":"fc121189-1778-40a0-882b-0f186f61285e","foo":"bar"}
  2. {"date":"2020-05-03T16:32:32.160Z","level":"info","message":"test message","awsRequestId":"fc121189-1778-40a0-882b-0f186f61285e","foo":"bar"}
  3. {"date":"2020-05-03T16:32:32.160Z","level":"error","message":"error occurred","meta":{"error":{"message":"ERR_MSG","code":145}},"awsRequestId":"fc121189-1778-40a0-882b-0f186f61285e","foo":"bar"}

AWS CloudWatch Logs
AWS CloudWatch Logs

License

The MIT License (MIT)