/
LogFactory.ts
86 lines (78 loc) · 2.93 KB
/
LogFactory.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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
import { AppConfig } from "../../model/AppConfig"
import { LogLevel } from "../../model/logging/LogLevel"
import { ILogger, LogFormat } from "./ILogger"
import { ConsoleLogger } from "./ConsoleLogger"
/**
* Builds implementations of [[ILogger]].
*/
export class LogFactory {
/**
* Build a new log factory using application config.
*
* @param appConfig Config object to read logging config from.
* @param logLevel (Optional) Lowest level to log, defaults to `info`.
* @param logFormat (Optional) Format to output log messages in, defaults to `string`.
* @param logTimestamp (Optional) Print an ISO 8601 timestamp before every log message?
* (string format only, defaults to `false`).
*/
public constructor(
appConfig: AppConfig,
private readonly logLevel: LogLevel = LogLevel.info,
private readonly logFormat: LogFormat = "string",
private readonly logTimestamp = false
) {
if (appConfig && appConfig.serverLogger) {
if (appConfig.serverLogger.level) {
this.logLevel = appConfig.serverLogger.level
}
if (appConfig.serverLogger.format) {
this.logFormat = appConfig.serverLogger.format
}
if (appConfig.serverLogger.logTimestamp !== null &&
appConfig.serverLogger.logTimestamp !== undefined) {
this.logTimestamp = appConfig.serverLogger.logTimestamp
}
}
}
/**
* Create a new logger.
*
* @param clazz The enclosing class that will use the new logger.
*/
public getLogger(clazz: Function): ILogger {
return new ConsoleLogger(clazz ? clazz.name : "?", this.logLevel, this.logFormat, this.logTimestamp)
}
/**
* Create a new logger using [[AppConfig]] config defaults.
*
* @param clazz The enclosing class that will use the new logger.
*/
public static getDefaultLogger(clazz: Function) {
let logFactory = new LogFactory(new AppConfig())
return logFactory.getLogger(clazz)
}
/**
* Create a new logger using custom log configuration.
*
* @param clazz The enclosing class that will use the new logger.
* @param logLevel (Optional) Lowest level to log, defaults to `info`.
* @param logFormat (Optional) Format to output log messages in, defaults to `string`.
* @param logTimestamp (Optional) Print an ISO 8601 timestamp before every log message?
* (string format only, defaults to `false`).
*/
public static getCustomLogger(
clazz: Function,
level: LogLevel = LogLevel.info,
format: LogFormat = "string",
logTimestamp = false
) {
let logFactory = new LogFactory({
serverLogger: {
format,
level,
logTimestamp
}
})
return logFactory.getLogger(clazz)
}
}