LogBook.ts 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  1. import config from "config";
  2. export type Log = {
  3. timestamp: number;
  4. message: string;
  5. type?: "info" | "success" | "error" | "debug";
  6. category?: string;
  7. data?: Record<string, unknown> | Error;
  8. };
  9. export type LogFilters = {
  10. include: Partial<Omit<Log, "timestamp">>[];
  11. exclude: Partial<Omit<Log, "timestamp">>[];
  12. };
  13. export type LogOutputOptions = Record<
  14. "timestamp" | "title" | "type" | "message" | "data" | "color",
  15. boolean
  16. > &
  17. Partial<LogFilters>;
  18. export type LogOutputs = {
  19. console: LogOutputOptions;
  20. memory: { enabled: boolean } & Partial<LogFilters>;
  21. };
  22. // Color escape codes for stdout
  23. const COLOR_GREEN = "\x1b[32m";
  24. const COLOR_RED = "\x1b[31m";
  25. const COLOR_YELLOW = "\x1b[33m";
  26. const COLOR_CYAN = "\x1b[36m";
  27. const COLOR_RESET = "\x1b[0m";
  28. export class LogBook {
  29. // A list of log objects stored in memory, if enabled generally
  30. private _logs: Log[];
  31. private _default: LogOutputs;
  32. // Settings for different outputs. Currently only memory and outputs is supported as an output
  33. // Constructed first via defaults, then via settings set in the config, and then you can make any other changes via a backend command (not persistent)
  34. private _outputs: LogOutputs;
  35. /**
  36. * Log Book
  37. */
  38. public constructor() {
  39. this._logs = [];
  40. this._default = {
  41. console: {
  42. timestamp: true,
  43. title: true,
  44. type: true,
  45. message: true,
  46. data: false,
  47. color: true,
  48. exclude: [
  49. // Success messages for jobs don't tend to be very helpful, so we exclude them by default
  50. {
  51. category: "jobs",
  52. type: "success"
  53. },
  54. // We don't want to show debug messages in the console by default
  55. {
  56. type: "debug"
  57. }
  58. ]
  59. },
  60. memory: {
  61. // Log messages in memory never get deleted, so we don't have this output on by default, only when debugging
  62. enabled: false
  63. }
  64. };
  65. if (config.has("logging"))
  66. (["console", "memory"] as (keyof LogOutputs)[]).forEach(output => {
  67. if (config.has(`logging.${output}`))
  68. this._default[output] = {
  69. ...this._default[output],
  70. ...config.get(`logging.${output}`)
  71. };
  72. });
  73. this._outputs = this._default;
  74. }
  75. /**
  76. * Log a message to console and/or memory, if the log matches the filters of those outputs
  77. *
  78. * @param log - Log message or log object (without timestamp)
  79. */
  80. public log(log: string | Omit<Log, "timestamp">) {
  81. // Construct the log object
  82. const logObject: Log = {
  83. timestamp: Date.now(),
  84. ...(typeof log === "string" ? { message: log } : log)
  85. };
  86. // Whether we want to exclude console or memory, which we get in the next code block
  87. const exclude = {
  88. console: false,
  89. memory: false
  90. };
  91. // Loop through log object entries
  92. (Object.entries(logObject) as [keyof Log, Log[keyof Log]][]).forEach(
  93. ([key, value]) => {
  94. // Timestamp is useless, so just return
  95. if (key === "timestamp") return;
  96. // Loop through outputs to see if they have any include/exclude filters
  97. (
  98. Object.entries(this._outputs) as [
  99. keyof LogOutputs,
  100. LogOutputs[keyof LogOutputs]
  101. ][]
  102. ).forEach(([outputName, output]) => {
  103. // This output has an include array, but the current key/value is not in any of the include filters, so exclude this output
  104. if (
  105. output.include &&
  106. output.include.length > 0 &&
  107. output.include.filter(filter => filter[key] === value)
  108. .length === 0
  109. )
  110. exclude[outputName] = true;
  111. // We have an exclude array, and the current key/value is in one or more of the filters, so exclude this output
  112. if (
  113. output.exclude &&
  114. output.exclude.filter(filter => filter[key] === value)
  115. .length > 0
  116. )
  117. exclude[outputName] = true;
  118. });
  119. }
  120. );
  121. const jobName =
  122. logObject.data && "jobName" in logObject.data
  123. ? logObject.data.jobName
  124. : null;
  125. // Title will be the jobname, or category of jobname is undefined
  126. const title = jobName ?? logObject.category ?? undefined;
  127. // If memory is not excluded and memory is enabled, store the log object in the memory (logs array) of this logbook instance
  128. if (!exclude.memory && this._outputs.memory.enabled)
  129. this._logs.push(logObject);
  130. // If console is not excluded, format the log object, and then write the formatted message to the console
  131. if (!exclude.console) {
  132. const message = this._formatMessage(logObject, String(title));
  133. const logArgs: (string | Record<string, unknown> | Error)[] = [
  134. message
  135. ];
  136. // Append logObject data, if enabled and it's not falsy
  137. if (this._outputs.console.data && logObject.data)
  138. logArgs.push(logObject.data);
  139. switch (logObject.type) {
  140. case "debug": {
  141. console.debug(...logArgs);
  142. break;
  143. }
  144. case "error": {
  145. console.error(...logArgs);
  146. break;
  147. }
  148. default:
  149. console.log(...logArgs);
  150. }
  151. }
  152. }
  153. /**
  154. * Center a string within a given length, by padding spaces at the start and end
  155. *
  156. * @param string - The string we want to center
  157. * @param length - The total amount of space we have to work with
  158. * @returns
  159. */
  160. private _centerString(string: string, length: number) {
  161. const spaces = Array(
  162. Math.floor((length - Math.max(0, string.length)) / 2)
  163. ).join(" ");
  164. return `${spaces}${string}${spaces}${
  165. string.length % 2 === 0 ? "" : " "
  166. }`;
  167. }
  168. /**
  169. * Creates a formatted log message, with various options. Used for console
  170. *
  171. * @param log - Log
  172. * @param title - Log title
  173. * @returns Formatted log string
  174. */
  175. private _formatMessage(log: Log, title: string | undefined): string {
  176. const messageParts = [];
  177. // If we want to show timestamps, e.g. 2022-11-28T18:13:28.081Z
  178. if (this._outputs.console.timestamp)
  179. messageParts.push(`${new Date(log.timestamp).toISOString()}`);
  180. // If we want to show the log type, in uppercase
  181. if (this._outputs.console.type)
  182. messageParts.push(
  183. `[${log.type ? log.type.toUpperCase() : "INFO"}]`
  184. );
  185. // If we want to show titles, show it
  186. if (this._outputs.console.title && title)
  187. messageParts.push(`[${title}]`);
  188. // If we want to the message, show it
  189. if (this._outputs.console.message) messageParts.push(log.message);
  190. const message = messageParts.join(" ");
  191. // If we want to show colors, prepend the color code
  192. if (this._outputs.console.color) {
  193. let coloredMessage = "";
  194. switch (log.type) {
  195. case "success":
  196. coloredMessage += COLOR_GREEN;
  197. break;
  198. case "error":
  199. coloredMessage += COLOR_RED;
  200. break;
  201. case "debug":
  202. coloredMessage += COLOR_YELLOW;
  203. break;
  204. case "info":
  205. default:
  206. coloredMessage += COLOR_CYAN;
  207. break;
  208. }
  209. coloredMessage += message;
  210. // Reset the color at the end of the message
  211. coloredMessage += COLOR_RESET;
  212. return coloredMessage;
  213. }
  214. return message;
  215. }
  216. /**
  217. * Update output settings for LogBook
  218. * These are stored in the current instance of LogBook, not saved in a file, so when the backend restarts this data will not be persisted
  219. * LogBook is currently used as a singleton, so changing it will update outputs for the same logbook used everywhere
  220. *
  221. * @param output - Output name (console or memory)
  222. * @param key - Output key to update (include, exclude, enabled, name, type, etc.)
  223. * @param action - Action (set, add or reset)
  224. * @param values - Value we want to set
  225. */
  226. public async updateOutput(
  227. output: "console" | "memory",
  228. key: keyof LogOutputOptions | "enabled",
  229. action: "set" | "add" | "reset",
  230. values?: LogOutputOptions[keyof LogOutputOptions]
  231. ) {
  232. switch (key) {
  233. // Set, add-to or reset (to) the include/exclude filter lists for a specific output
  234. case "include":
  235. case "exclude": {
  236. if (action === "set" || action === "add") {
  237. if (!values || typeof values !== "object")
  238. throw new Error("No filters provided");
  239. const filters = Array.isArray(values) ? values : [values];
  240. if (action === "set") this._outputs[output][key] = filters;
  241. if (action === "add")
  242. this._outputs[output][key] = [
  243. ...(this._outputs[output][key] || []),
  244. ...filters
  245. ];
  246. } else if (action === "reset") {
  247. this._outputs[output][key] =
  248. this._default[output][key] || [];
  249. } else
  250. throw new Error(
  251. `Action "${action}" not found for ${key} in ${output}`
  252. );
  253. break;
  254. }
  255. // Set an output to be enabled or disabled
  256. case "enabled": {
  257. if (output === "memory" && action === "set") {
  258. if (values === undefined)
  259. throw new Error("No value provided");
  260. this._outputs[output][key] = !!values;
  261. } else
  262. throw new Error(
  263. `Action "${action}" not found for ${key} in ${output}`
  264. );
  265. break;
  266. }
  267. // Set some other property of an output
  268. default: {
  269. if (output !== "memory" && action === "set") {
  270. if (values === undefined)
  271. throw new Error("No value provided");
  272. this._outputs[output][key] = !!values;
  273. } else if (output !== "memory" && action === "reset") {
  274. this._outputs[output][key] = this._default[output][key];
  275. } else
  276. throw new Error(
  277. `Action "${action}" not found for ${key} in ${output}`
  278. );
  279. }
  280. }
  281. }
  282. }
  283. export default new LogBook();