plugins: neater parameters for 'log'
Massimo Melina committed
May 9, 2025 at 00:29 UTC
e1d54f1ece08e5a044c0e09ea456347f5de35414
4 files changed
+9
-2
dev-plugins.md
+2
@@ -633,7 +633,9 @@ This section is still partially documented, and you may need to have a look at t
633
- `httpsReady`
634
- `spam`
635
- `log`
636
+ - parameters: { ctx, length, user, ts, uri, extra }
637
- `error_log`
638
+ - parameters: { ctx, length, user, ts, uri, extra }
639
- `accountRenamed`
640
- parameters: { from, to }
641
- `pluginDownload`
src/api.log.ts
+2
-1
@@ -61,7 +61,8 @@ export default {
61
return list.error(HTTP_NOT_FOUND, true)
62
list.ready()
63
// unsubscribe when connection is interrupted
64
- ctx.res.once('close', events.on(files, x => list.add(x)))
64
+ ctx.res.once('close', events.on(files, x =>
65
+ list.add(Object.assign(_.pick(x.ctx, ['ip', 'method','status']), x, { ctx: undefined }))))
66
}
67
})
68
src/events.ts
+3
@@ -53,6 +53,9 @@ export class BetterEventEmitter {
53
for (const cb of cbs) cb()
54
}
55
}
56
+ anyListener(event: string) {
57
+ return Boolean(this.listeners.get(event)?.size)
58
+ }
59
emit(event: string, ...args: any[]) {
60
let cbs = this.listeners.get(event)
61
if (!cbs?.size) return
src/log.ts
+2
-1
@@ -133,7 +133,8 @@ export const logMw: Koa.Middleware = async (ctx, next) => {
133
if (logUA.get())
134
ctx.logExtra({ ua: ctx.get('user-agent') || undefined })
135
const extra = ctx.state.logExtra
136
- events.emit(logger.name, Object.assign(_.pick(ctx, ['ip', 'method','status']), { length, user, ts: now, uri, extra }))
136
+ if (events.anyListener(logger.name)) // small optimization: this event can happen often, while most times there's no listener, and the parameters object is constructed pointlessly. A benchmark measured it 20% faster (just the line), while maybe it was not necessary.
137
+ events.emit(logger.name, { ctx, length, user, ts: now, uri, extra })
138
debounce(() => // once in a while we check if the file is still good (not deleted, etc), or we'll reopen it
139
stat(logger.path).catch(() => logger.reopen())) // async = smoother but we may lose some entries
140
stream!.write(util.format( format,