fix: log rotation weekly

Massimo Melina committed Mar 14, 2022 at 10:08 UTC 58095849789f20e16e33691d9ccdf14c8de99ea1
2 files changed +8 -3
server/src/const.ts
+1
@@ -10,6 +10,7 @@ export const BUILD_TIMESTAMP = ''
10 export const VERSION = ''
11 || DEV && String(_.attempt(() => JSON.parse(fs.readFileSync('package.json','utf8')).version)) // this should happen only in dev, build fills this value
12 export const SESSION_DURATION = 30*60_000
13 +export const DAY = 86_400_00
14
15 export const SPECIAL_URI = '/~/'
16 export const FRONTEND_URI = SPECIAL_URI + 'frontend/'
server/src/log.ts
+7 -3
@@ -6,6 +6,7 @@ import { defineConfig, getConfig, subscribeConfig } from './config'
6 import { createWriteStream } from 'fs'
7 import * as util from 'util'
8 import { rename, stat } from 'fs/promises'
9 +import { DAY } from './const'
10
11 class Logger {
12 stream?: Writable
@@ -56,14 +57,17 @@ export function log(): Koa.Middleware {
57 await next()
58 const isError = ctx.status >= 400
59 const logger = isError && !getConfig('errors_in_main_log') && errorLogger || accessLogger
59 - const freq = getConfig('log_rotation')
60 + const freq = getConfig('log_rotation')?.[0]
61 const { stream, last, path } = logger
62 if (!stream) return
63 const now = new Date()
64 const a = now.toString().split(' ')
65 if (freq && last) {
65 - const method = freq[0] === 'w' ? 'getDay' : freq[0] === 'm' ? 'getDate' : 'getTime'
66 - if (getMidnight(now)[method]() !== getMidnight(last)[method]()) {
66 + const passed = Number(now) - Number(last)
67 + - 3600_000 // be pessimistic and count a possible DST change
68 + if (freq === 'm' && (passed >= 31*DAY || now.getMonth() !== last.getMonth())
69 + || freq === 'd' && (passed >= DAY || now.getDate() !== last.getDate())
70 + || freq === 'w' && (passed >= 7*DAY || now.getDay() < last.getDay())) {
71 stream.end()
72 const postfix = last.getFullYear() + '-' + doubleDigit(last.getMonth() + 1) + '-' + doubleDigit(last.getDate())
73 await rename(path, path + '-' + postfix)