nicer console warnings when running on a read-only cwd
Massimo Melina committed
Aug 28, 2022 at 20:32 UTC
42aee2bb3f6a780452cfda08c8392d5a4b83f077
1 file changed
+11
-13
src/log.ts
+11
-13
@@ -3,7 +3,7 @@
3
import Koa from 'koa'
4
import { Writable } from 'stream'
5
import { defineConfig } from './config'
6
-import { createWriteStream, existsSync, renameSync, WriteStream } from 'fs'
6
+import { createWriteStream, renameSync } from 'fs'
7
import * as util from 'util'
8
import { mkdir, stat } from 'fs/promises'
9
import { DAY } from './const'
@@ -32,12 +32,14 @@ class Logger {
32
}
33
catch {
34
await mkdir(dirname(path), { recursive: true })
35
+ .catch(() => console.log("cannot create folder for", path))
36
}
37
this.reopen()
38
}
39
40
reopen() {
41
return this.stream = createWriteStream(this.path, { flags: 'a' })
42
+ .on('error', () => this.stream = undefined)
43
}
44
}
45
@@ -86,6 +88,7 @@ export function log(): Koa.Middleware {
88
console.error(e)
89
}
90
stream = logger.reopen() // keep variable updated
91
+ if (!stream) return
92
}
93
}
94
const format = '%s - %s [%s] "%s %s HTTP/%s" %d %s\n' // Apache's Common Log Format
@@ -112,19 +115,14 @@ function doubleDigit(n: number) {
115
return n > 9 ? n : '0'+n
116
}
117
115
-{ // dump console.error to file
118
+// dump console.error to file
119
+const debugLogFile = createWriteStream('debug.log', { flags: 'a' })
120
+debugLogFile.on('open', () => {
121
const was = console.error
122
console.error = function(...args: any[]) {
123
was.apply(this, args)
119
- debugLog(...args)
124
+ const params = args.map(x =>
125
+ typeof x === 'string' ? x : JSON.stringify(x)).join(' ')
126
+ debugLogFile.write(new Date().toLocaleString() + ': ' + params + '\n')
127
}
121
-}
122
-
123
-let debugLogFile: WriteStream
124
-export function debugLog(...args: any[]) {
125
- if (!debugLogFile || !existsSync(debugLogFile.path))
126
- debugLogFile = createWriteStream('debug.log', { flags: 'a' })
127
- const params = args.map(x =>
128
- typeof x === 'string' ? x : JSON.stringify(x)).join(' ')
129
- debugLogFile.write(new Date().toLocaleString() + ': ' + params + '\n')
130
-}
128
+}).on('error', () => console.log("cannot create debug.log"))