dominhhai / koa-log4js

log4js-node supports Koa-middleware
https://www.npmjs.com/package/koa-log4
MIT License
82 stars 16 forks source link

How to get request body with customize token? #5

Open fancyoung opened 8 years ago

fancyoung commented 8 years ago

The code support custom_tokens, but if the replacement is something like ctx.request.body, I can't pass the option just like:

app.use(log4js.koaLogger(log4js.getLogger("http"), { level: 'auto',
    tokens: [
        { token: ':body', replacement: ctx.request.body}
    ],
    format: ':remote-addr - -' +
    ' ":method :url HTTP/:http-version"' +
    ' :status :content-length ":referrer"' +
    ' ":user-agent"' +
    ' :body'
}))

because ctx is not defined here.

I can use a wrapper, but is there any simple way to solve this problem?

dominhhai commented 8 years ago

You can pass the replacement as a replace function.

tokens: [
  { token: ':body', replacement: function() { return ctx.request.body } }
]
fancyoung commented 7 years ago

But it seems can't use as Koa-middleware way, such as

app.use(log4js.koaLogger(log4js.getLogger('http'), { level: 'auto', tokens: [
  { token: ':body', replacement: function() { return ctx.request.body } }
] }))

because ctx is not defined here.

dominhhai commented 7 years ago

I have just added a new syntax to allow replacing token with ctx.

tokens: [
  { token: ':body', content: function(ctx) { return ctx.request.body } }
]

You can upgrade your package to v1.1.0 (for Koa v1) or v2.1.0 (for Koa v2).

fancyoung commented 7 years ago

Wonderful.

Now I use { token: ':body', content: function(ctx) { return JSON.stringify(ctx.request.body) } } log the body'

fancyoung commented 7 years ago

It not work, it save the first time request param, and return it everytime

dominhhai commented 7 years ago

Which should be fix by this https://github.com/dominhhai/koa-log4js/pull/8 PR.