log will recover in case the file is deleted at run-time
Massimo Melina committed
Aug 9, 2022 at 11:17 UTC
e3b8eb85c4162e80e0c931cd878ed2492ffd843b
1 file changed
+4
-1
server/src/log.ts
+4
-1
@@ -60,6 +60,7 @@ errorLogFile.sub(path => {
60
const logRotation = defineConfig('log_rotation', 'weekly')
61
62
export function log(): Koa.Middleware {
63
+ const debounce = _.debounce(cb => cb(), 1000)
64
return async (ctx, next) => { // wrapping in a function will make it use current 'mw' value
65
await next()
66
const isError = ctx.status >= 400
@@ -74,7 +75,7 @@ export function log(): Koa.Middleware {
75
const passed = Number(now) - Number(last)
76
- 3600_000 // be pessimistic and count a possible DST change
77
if (rotate === 'm' && (passed >= 31*DAY || now.getMonth() !== last.getMonth())
77
- || rotate === 'd' && (passed >= DAY || now.getDate() !== last.getDate())
78
+ || rotate === 'd' && (passed >= DAY || now.getDate() !== last.getDate()) // checking passed will solve the case when the day of the month is the same but a month has passed
79
|| rotate === 'w' && (passed >= 7*DAY || now.getDay() < last.getDay())) {
80
stream.end()
81
const postfix = last.getFullYear() + '-' + doubleDigit(last.getMonth() + 1) + '-' + doubleDigit(last.getDate())
@@ -92,6 +93,8 @@ export function log(): Koa.Middleware {
93
const user = getCurrentUsername(ctx)
94
events.emit(logger.name, Object.assign(_.pick(ctx, ['ip', 'method','status','length']), { user, ts: now, uri: ctx.path }))
95
console.debug(ctx.status, ctx.method, ctx.path)
96
+ debounce(() => // once in a while we check if the file is still good (not deleted, etc), or we'll reopen it
97
+ stat(logger.path).catch(() => logger.reopen())) // async = smoother but we may lose some entries
98
stream.write(util.format( format,
99
ctx.ip,
100
user || '-',