koa-log4js icon indicating copy to clipboard operation
koa-log4js copied to clipboard

How to get request body with customize token?

Open fancyoung opened this issue 9 years ago • 6 comments

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?

fancyoung avatar Nov 11 '16 07:11 fancyoung

You can pass the replacement as a replace function.

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

dominhhai avatar Nov 15 '16 01:11 dominhhai

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.

fancyoung avatar Nov 21 '16 09:11 fancyoung

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).

dominhhai avatar Nov 24 '16 06:11 dominhhai

Wonderful.

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

fancyoung avatar Nov 28 '16 09:11 fancyoung

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

fancyoung avatar Dec 04 '16 04:12 fancyoung

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

dominhhai avatar Apr 20 '17 12:04 dominhhai