1

我正在尝试使用自定义序列化程序,但它似乎对我不起作用,我的序列化程序永远不会被调用。我究竟做错了什么?

我创建一个这样的记录器:

const mask = token => {
  console.log({token})
  return typeof token === 'string' ? token.replace(/[^\.]+$/, 'REDACTED') : token
}
const log = context.log = createLogger({
  name: '_placeholder',
  level: process.env.LOG_LEVEL || 'info',
  serializers: {authorization: mask, bearer: mask, Authorization: mask}
})

然后我像这样记录:

console.log({properties})
log[!status ? 'error' : status < 500 ? 'info' : 'warn']({error: merge({message, ...properties}, status && {status})})

输出管道到 bunyan:

{ properties:
   { reason: 'InvalidToken', authorization: 'Bearer foo.bar.baz' } }
[2018-08-14T14:37:11.775Z]  INFO: _placeholder/9920 on XXX: 
   error: {
     "message": "Invalid token",
     "reason": "InvalidToken",
     "authorization": "Bearer foo.bar.baz",
     "status": 401
   }

编辑:

我看到它只适用于顶级属性;有没有办法实现我在这里尝试做的事情 - 适当命名的掩码嵌套属性?

4

1 回答 1

0

从技术上讲,这是可行的,但是考虑到性能受到影响,我不确定我是否想将其付诸实践:

const jp = require('jsonpath')

class Sanitized extends Writable {
  write(object) {
    console.log(JSON.stringify(
      ['authorization', 'bearer'].reduce((object, property) => {
        jp.apply(object, `$..${property}`, token => token.replace(/[^.]+$/, 'REDACTED'))
        return object
      }, merge({}, object))))
  }
}

...

const log = context.log = createLogger({
  name: '_placeholder',
  level: process.env.LOG_LEVEL || 'info',
  streams: [{type: 'raw', stream: new Sanitized()}]
})
于 2018-08-14T16:22:37.270 回答