当前位置: 首页 > 软件库 > Web应用开发 > Web框架 >

koa2-winston

koa2 version winston logger like express-winston
授权协议 MIT License
开发语言 JavaScript
所属分类 Web应用开发、 Web框架
软件类型 开源软件
地区 不详
投 递 者 单淳
操作系统 跨平台
开源组织
适用人群 未知
 软件概览

koa2-winston

koa2 version winston logger like express-winston

Add logger to your koa2 server in 3 lines

中文介绍

Usage

Installation

npm i --save koa2-winston

Quick Start

const { logger } = require('koa2-winston');
app.use(logger());

request log will look like

{
  "req": {
    "header": {
      "host": "localhost:3000",
      "connection": "keep-alive",
      "upgrade-insecure-requests": "1",
      "user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36",
      "accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
      "dnt": "1",
      "accept-encoding": "gzip, deflate, sdch, br",
      "accept-language": "zh-CN,zh;q=0.8,en;q=0.6,zh-TW;q=0.4,de;q=0.2,ja;q=0.2,it;q=0.2"
    },
    "url": "/hello",
    "method": "GET",
    "href": "http://localhost:3000/hello",
    "query": {}
  },
  "started_at": 1494554053492,
  "res": {
    "header": {
      "content-type": "application/json; charset=utf-8",
      "content-length": "16"
    },
    "status": 200
  },
  "duration": 8,
  "level": "info",
  "message": "HTTP GET /hello"
}

Configuration

Each parameter has a default value, and you can customize your logger by changing the configuration

app.use(
  logger({
    transports: new winston.transports.Console({ json: true, stringify: true }),
    level: 'info',
    reqKeys: [
      'header',
      'url',
      'method',
      'httpVersion',
      'href',
      'query',
      'length',
    ],
    reqSelect: [],
    reqUnselect: ['header.cookie'],
    resKeys: ['header', 'status'],
    resSelect: [],
    resUnselect: [],
  })
);

Many configuration explain can be found in logger

Examples

Do not record any request fields

app.use(
  logger({
    reqKeys: [],
  })
);

The req object will be empty

{
  "req": {},
  "started_at": 1494486039864,
  "res": {
    "header": {
      "content-type": "text/plain; charset=utf-8",
      "content-length": "8"
    },
    "status": 200
  },
  "duration": 26,
  "level": "info",
  "message": "HTTP GET /"
}

Do not record any response fields

app.use(
  logger({
    resKeys: [],
  })
);

The res object will be empty

{
  "req": {
    "header": {
      "host": "127.0.0.1:59534",
      "accept-encoding": "gzip, deflate",
      "user-agent": "node-superagent/3.5.2",
      "connection": "close"
    },
    "url": "/",
    "method": "GET",
    "href": "http://127.0.0.1:59534/",
    "query": {}
  },
  "started_at": 1494486039864,
  "res": {},
  "duration": 26,
  "level": "info",
  "message": "HTTP GET /"
}

Do not record UA

app.use(
  logger({
    reqUnselect: ['header.cookie', 'header.user-agent'],
  })
);

The UA of request will be ignored

{
  "req": {
    "header": {
      "host": "127.0.0.1:59534",
      "accept-encoding": "gzip, deflate",
      "connection": "close"
    },
    "url": "/",
    "method": "GET",
    "href": "http://127.0.0.1:59534/",
    "query": {}
  },
  "started_at": 1494486039864,
  "res": {
    "header": {
      "content-type": "text/plain; charset=utf-8",
      "content-length": "8"
    },
    "status": 200
  },
  "duration": 26,
  "level": "info",
  "message": "HTTP GET /"
}

Record a response body filed

app.use(
  logger({
    resSelect: ['body.success'],
  })
);

The success field on body will be recorded

{
  "req": {
    "header": {
      "host": "127.0.0.1:59534",
      "accept-encoding": "gzip, deflate",
      "connection": "close"
    },
    "url": "/",
    "method": "GET",
    "href": "http://127.0.0.1:59534/",
    "query": {}
  },
  "started_at": 1494486039864,
  "res": {
    "header": {
      "content-type": "text/plain; charset=utf-8",
      "content-length": "8"
    },
    "status": 200,
    "body": {
      // Any possible value given by the server
      "success": false
    }
  },
  "duration": 26,
  "level": "info",
  "message": "HTTP GET /"
}

Simple Benchmark

At node 8.2

middleware x 90,281 ops/sec ±7.89% (13 runs sampled)

At node 8.4

middleware x 112,011 ops/sec ±10.26% (18 runs sampled)

Schema Stringify

With fast-json-stringify support, default transport logger is much faster

total ops/sec { jsonstringify: 73544 }
▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓
total ops/sec { schemastringify: 90223 }
▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓

schemastringify is 1.23x faster then jsonstringify in this case

v1.7.1 vs v2.4.0

total ops/sec { 'v1.7.1': 111416 }
▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓
total ops/sec { 'v2.4.0': 131234 }
▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓

v2.4.0 is 1.18x faster then v1.7.1 in this case

Math.floor vs parseInt

Related commit in HERE

JSPerf link in HERE

Testing in Chrome 70.0.3505 / Mac OS X 10.13.5

parseInt(401 / 100, 10) { 160,092,130 Ops/sec }
▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓
Math.floor(401 / 100) { 810,032,369 Ops/sec }
▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓

Math.floor is 5.06x faster then parseInt in this case

v3

Finally, winston v3 support. But winston will install as dependencies not peerDependencies.

With better backward compatibility, users don't have to worry about the new version of koa2-winston will conflict with other winston usage in the project.

v3.1

The fastest koa2-winston ever. Nearly 3x faster than previous versions.

total ops/sec { 'v3.0.2': 180020 }
▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓
total ops/sec { 'v3.1.0': 541854 }
▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓

The above statistics come from npm run bench.

Biggest change

  • Remove key recorder
  • Generate json-schema for fast-json-stringify, not only for object serialization (log message), but also as key selector.
  • Log info object key rename.
    - {req,res}.headers
    + {req,res}.header

JSDoc

Table of Contents

logger

logger middleware for koa2 use winston

Parameters

  • payload object input arguments (optional, default {})
    • payload.transports Array<object> customize transports (optional, default [newwinston.transports.Stream({stream:process.stdout})])
    • payload.level string default log level of logger (optional, default 'info')
    • payload.reqKeys string default request fields to be logged (optional, default ['header','url','method','httpVersion','href','query','length'])
    • payload.reqSelect string additional request fields to be logged (optional, default [])
    • payload.reqUnselect string request field will be removed from the log (optional, default ['header.cookie'])
    • payload.resKeys string default response fields to be logged (optional, default ['header','status'])
    • payload.resSelect string additional response fields to be logged (optional, default [])
    • payload.resUnselect string response field will be removed from the log (optional, default [])
    • payload.logger winston.transports.StreamTransportInstance? customize winston logger
    • payload.msg string customize log msg (optional, default HTTP%s%s)

Examples

const { logger } = require('koa2-winston');
app.use(logger());
// request logger look like down here
// {
//   "req": {
//     "header": {
//       "host": "127.0.0.1:59534",
//       "accept-encoding": "gzip, deflate",
//       "user-agent": "node-superagent/3.5.2",
//       "connection": "close"
//     },
//     "url": "/",
//     "method": "GET",
//     "href": "http://127.0.0.1:59534/",
//     "query": {}
//   },
//   "started_at": 1494486039864,
//   "res": {
//     "header": {
//       "content-type": "text/plain; charset=utf-8",
//       "content-length": "8"
//     },
//     "status": 200
//   },
//   "duration": 26,
//   "level": "info",
//   "message": "HTTP GET /"
// }

Returns function logger middleware

asJsonSchemaPath

Parameters

ensureTypeObject

Parameters

  • schema object generated json schema

schemaKeysHandlerFn

Type: Function

Parameters

schemaKeysHandler

Parameters

generateSchema

logger middleware for koa2 use winston

Parameters

  • payload object input arguments (optional, default {})
    • payload.reqKeys Array<string> default request fields to be logged (optional, default ['header','url','method','httpVersion','href','query','length'])
    • payload.reqSelect Array<string> additional request fields to be logged (optional, default [])
    • payload.reqUnselect Array<string> request field will be removed from the log (optional, default ['header.cookie'])
    • payload.resKeys Array<string> default response fields to be logged (optional, default ['header','status'])
    • payload.resSelect Array<string> additional response fields to be logged (optional, default [])
    • payload.resUnselect Array<string> response field will be removed from the log (optional, default [])
  • 日志是程序很重要的组成部分,程序在线上只能通过日志才能观察到运行情况,所以好的日志能够帮助你了解情况,分析问题。 一般来说,日志记录应以rotate方式记录成文件,常规日志文件会采用plain text, [INFO] 11:06:12 login ok. 但现在更多的倾向于持久化为结构化JSON, {"requestId":"0f111049-09f9-4f8e-9306-900652c833b

  • Github上的脚手架实在太多,可能大多数都是只专注在前端的web开发,例如流行的React生态中的create-react-app和Vue生态中的Vue-cli, 但是可能作为像我一样的全栈开发,一个只关注在前端开发的脚手架满足不了所有的需求,我们可能需要开发更复杂的全栈JS的项目,所以这里介绍又一个基于NodeJS的全栈开发框架 koa-web-kit,不一定适合所有人,但至少又多了个选择?。

  • 最近在为服务端添加日志,主要是利用PM2和winston、log4js,现将遇到的问题记录下来。 PM2被用于生产环境下进程管理,能够及时获取业务代码中日志信息。 PM2 基本设置如下 PM2 能够获得项目中 winston.log.error or console.log.info 信息。基本配置如下,访问localhost:8087,会在error_file打印出一条日志。 PS:建议不用直接

  • Github上的脚手架实在太多,可能大多数都是只专注在前端的web开发,例如流行的React生态中的create-react-app和Vue生态中的Vue-cli, 但是可能作为像我一样的全栈开发,一个只关注在前端开发的脚手架满足不了所有的需求,我们可能需要开发更复杂的全栈JS的项目,所以这里介绍又一个基于NodeJS的全栈开发框架 koa-web-kit,不一定适合所有人,但至少又多了个选择?。

  • 最近接了个新需求,让在服务器通过Nodejs去打日志文件,捕捉请求日志。。。 然后我就想到了log4js…… 废话不多说,上代码 安装log4js npm install log4js --save 复制代码 对log4js不熟的查看文档 log4js; 在config文件夹下新建log_config.js文件: var log4js = require("log4js"); var path =

 相关资料
  • Koa2-blog(有问题可以加qq群:725165362) node+koa2+mysql (欢迎star) 现在最新的代码有变动,请参照最新的代码,新增了上传头像、分页、markdown语法等 教程 Node+Koa2+Mysql 搭建简易博客 创建数据库 登录数据库 $ mysql -u root -p 创建数据库 $ create database nodesql; 使用创建的数据库 $

  • Koa2 Boilerplate 这是团队近两年的 Koa2 + ES 2017 做 API 项目的最佳实践,项目中用到一些新的 Feature,并完成了从 request 到 service 和 DB(Sequlize)到 response 的全部流程。同时也包含了一些基本的 middleware。 项目用到的功能 �� Koa2 & koa-router Koa 相对于 Express 更吸引

  • 基于koa2的代理工具 功能 代理http和https 转发本地请求到网络 本地服务器 本地模拟数据配置 解析smarty模板 随意修改请求和响应结果 安装 安装node之后执行 npm install koa2-proxy 使用 var proxy = require('koa2-proxy');// 本地静态服务器proxy.static(__dirname);// 本地模拟文件proxy.m

  • 注意: 请使用Node6以上版本,获得更好的性能与ES6支持。启用Babel-es2017,不再对一些Node6已支持的特性转码。 起因 因为Koa2已经在蓬勃发展中,Async/Await能切实的避免回调地狱。所以基于Koa2订制了一套模板。 全局安装koa2-easy,之后使用koa2命令即可在当前目录一键生成服务端程序。地址为:当前目录/koa2-easy npm i koa2-easy -

  • 《Koa2进阶学习笔记》已完结 序言 从2017年2月份开始写这本开源电子书,是为了记录自己的学习轨迹和分享技术心得,本开源书的Koa2的基础进阶教程已经完结,更多的Koa.js的高阶学习会在后续新开几本书进行探索。感谢这一年来所有读者的关注!O(∩_∩)O。 本书为Koa.js 2.x 的入门书籍,如果想了解更多 Koa.js 的原理,可阅读 《Koa.js 设计模式-学习笔记》 更多前端技术学

  • Koa2 RESTful API 服务器脚手架 这是一个基于 Koa2 的轻量级 RESTful API Server 脚手架,支持 ES6。 约定使用 JSON 格式传输数据,POST、PUT、DELET 方法支持的 Content-Type 为 application/x-www-form-urlencoded、multipart/form-data、application/json可配置支持