-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
67 lines (58 loc) · 1.77 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
import { ConsoleLogger, DynamicModule, Module } from '@nestjs/common'
const loglevels = {
'debug': ['debug', 'log', 'warn', 'error'],
'info': ['log', 'warn', 'error'],
'warn': ['warn', 'error'],
'error': ['error']
}
export class LoggerTaService extends ConsoleLogger {
static path = ''
constructor(context: string) {
super(context,
{
logLevels: loglevels[process.env.LOG_LEVEL?.toLowerCase() ?? 'error']
})
}
error(message: string) {
if (!this.isLevelEnabled('error')) return
super.error(message)
this.writeToFile(message, 'ERROR')
}
log(message: string) {
if (!this.isLevelEnabled('log')) return
super.log(message)
this.writeToFile(message, 'INFO')
}
warn(message: string) {
if (!this.isLevelEnabled('warn')) return
super.warn(message)
this.writeToFile(message, 'WARN')
}
debug(message: string) {
if (!this.isLevelEnabled('debug')) return
super.debug(message)
this.writeToFile(message, 'DEBUG')
}
private writeToFile(message: string, level: string) {
const fs = require('fs')
const dir = LoggerTaService.path;
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir);
}
fs.appendFile(`${LoggerTaService.path}/${this.context}.log`,
`${new Date().toISOString()} ${level} ${this.context} ${message}\n`, () => 0);
}
}
@Module({
providers: [LoggerTaService],
exports: [LoggerTaService]
})
export class LoggerTaModule {
static register(options: { path: string }): DynamicModule {
LoggerTaService.path = options.path
return {
module: LoggerTaModule,
exports: [LoggerTaService],
};
}
}