limit debug.log to 1MB
Massimo Melina committed
Feb 23, 2024 at 15:43 UTC
5088fceea734e4e2426ca7d719f852da5309e7f4
1 file changed
+12
-4
src/log.ts
+12
-4
@@ -3,13 +3,13 @@
3
import Koa from 'koa'
4
import { once, Writable } from 'stream'
5
import { defineConfig } from './config'
6
-import { createWriteStream, renameSync } from 'fs'
6
+import { createWriteStream, renameSync, statSync } from 'fs'
7
import * as util from 'util'
8
import { stat } from 'fs/promises'
9
import _ from 'lodash'
10
import { createFileWithPath, prepareFolder } from './util-files'
11
import { getCurrentUsername } from './auth'
12
-import { DAY, makeNetMatcher, tryJson, Dict, Falsy, CFG, strinsert } from './misc'
12
+import { DAY, makeNetMatcher, tryJson, Dict, Falsy, CFG, strinsert, repeat } from './misc'
13
import { extname } from 'path'
14
import events from './events'
15
import { getConnection } from './connections'
@@ -158,12 +158,20 @@ function doubleDigit(n: number) {
158
}
159
160
// dump console.error to file
161
-const debugLogFile = createWriteStream('debug.log', { flags: 'a' })
162
-debugLogFile.on('open', () => {
161
+let debugLogFile = createWriteStream('debug.log', { flags: 'a' })
162
+debugLogFile.once('open', () => {
163
const was = console.error
164
console.error = function(...args: any[]) {
165
was.apply(this, args)
166
args = args.map(x => typeof x === 'string' ? x : (tryJson(x) ?? String(x)))
167
debugLogFile.write(new Date().toLocaleString() + ': ' + args.join(' ') + '\n')
168
}
169
+ // limit log size
170
+ const LIMIT = 1_000_000
171
+ const { path } = debugLogFile
172
+ repeat(DAY, () => { // do it sync, to avoid overlapping
173
+ if (statSync(path).size < LIMIT) return // no need
174
+ renameSync(path, 'old-' + path)
175
+ debugLogFile = createWriteStream(path, { flags: 'w' }) // new file
176
+ })
177
}).on('error', () => console.log("cannot create debug.log"))