LogBook.ts 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  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>;
  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 default 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: false,
  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. // Title will be the jobname, or category of jobname is undefined
  122. const title =
  123. logObject.data?.jobName ?? logObject.category ?? undefined;
  124. // If memory is not excluded and memory is enabled, store the log object in the memory (logs array) of this logbook instance
  125. if (!exclude.memory && this.outputs.memory.enabled)
  126. this.logs.push(logObject);
  127. // If console is not excluded, format the log object, and then write the formatted message to the console
  128. if (!exclude.console) {
  129. const message = this.formatMessage(logObject, String(title));
  130. const logArgs: (string | Record<string, unknown>)[] = [message];
  131. // Append logObject data, if enabled and it's not falsy
  132. if (this.outputs.console.data && logObject.data)
  133. logArgs.push(logObject.data);
  134. switch (logObject.type) {
  135. case "debug": {
  136. console.debug(...logArgs);
  137. break;
  138. }
  139. case "error": {
  140. console.error(...logArgs);
  141. break;
  142. }
  143. default:
  144. console.log(...logArgs);
  145. }
  146. }
  147. }
  148. /**
  149. * Center a string within a given length, by padding spaces at the start and end
  150. *
  151. * @param string - The string we want to center
  152. * @param length - The total amount of space we have to work with
  153. * @returns
  154. */
  155. private centerString(string: string, length: number) {
  156. const spaces = Array(
  157. Math.floor((length - Math.max(0, string.length)) / 2)
  158. ).join(" ");
  159. return `${spaces}${string}${spaces}${
  160. string.length % 2 === 0 ? "" : " "
  161. }`;
  162. }
  163. /**
  164. * Creates a formatted log message, with various options. Used for console
  165. *
  166. * @param log - Log
  167. * @param title - Log title
  168. * @returns Formatted log string
  169. */
  170. private formatMessage(log: Log, title: string | undefined): string {
  171. let message = "";
  172. // If we want to show colors, prepend the color code
  173. if (this.outputs.console.color)
  174. switch (log.type) {
  175. case "success":
  176. message += COLOR_GREEN;
  177. break;
  178. case "error":
  179. message += COLOR_RED;
  180. break;
  181. case "debug":
  182. message += COLOR_YELLOW;
  183. break;
  184. case "info":
  185. default:
  186. message += COLOR_CYAN;
  187. break;
  188. }
  189. // If we want to show timestamps, e.g. 2022-11-28T18:13:28.081Z
  190. if (this.outputs.console.timestamp)
  191. message += `| ${new Date(log.timestamp).toISOString()} `;
  192. // If we want to show titles, show it centered and capped at 20 characters
  193. if (this.outputs.console.title)
  194. message += `| ${this.centerString(
  195. title ? title.substring(0, 20) : "",
  196. 24
  197. )} `;
  198. // If we want to show the log type, show it centered, in uppercase
  199. if (this.outputs.console.type)
  200. message += `| ${this.centerString(
  201. log.type ? log.type.toUpperCase() : "INFO",
  202. 10
  203. )} `;
  204. // If we want to the message, show it
  205. if (this.outputs.console.message) message += `| ${log.message} `;
  206. // Reset the color at the end of the message, if we have colors enabled
  207. if (this.outputs.console.color) message += COLOR_RESET;
  208. return message;
  209. }
  210. /**
  211. * Update output settings for LogBook
  212. * 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
  213. * LogBook is currently used as a singleton, so changing it will update outputs for the same logbook used everywhere
  214. *
  215. * @param output - Output name (console or memory)
  216. * @param key - Output key to update (include, exclude, enabled, name, type, etc.)
  217. * @param action - Action (set, add or reset)
  218. * @param values - Value we want to set
  219. */
  220. public async updateOutput(
  221. output: "console" | "memory",
  222. key: keyof LogOutputOptions | "enabled",
  223. action: "set" | "add" | "reset",
  224. values?: LogOutputOptions[keyof LogOutputOptions]
  225. ) {
  226. switch (key) {
  227. // Set, add-to or reset (to) the include/exclude filter lists for a specific output
  228. case "include":
  229. case "exclude": {
  230. if (action === "set" || action === "add") {
  231. if (!values || typeof values !== "object")
  232. throw new Error("No filters provided");
  233. const filters = Array.isArray(values) ? values : [values];
  234. if (action === "set") this.outputs[output][key] = filters;
  235. if (action === "add")
  236. this.outputs[output][key] = [
  237. ...(this.outputs[output][key] || []),
  238. ...filters
  239. ];
  240. } else if (action === "reset") {
  241. this.outputs[output][key] = this.default[output][key] || [];
  242. } else
  243. throw new Error(
  244. `Action "${action}" not found for ${key} in ${output}`
  245. );
  246. break;
  247. }
  248. // Set an output to be enabled or disabled
  249. case "enabled": {
  250. if (output === "memory" && action === "set") {
  251. if (values === undefined)
  252. throw new Error("No value provided");
  253. this.outputs[output][key] = !!values;
  254. } else
  255. throw new Error(
  256. `Action "${action}" not found for ${key} in ${output}`
  257. );
  258. break;
  259. }
  260. // Set some other property of an output
  261. default: {
  262. if (output !== "memory" && action === "set") {
  263. if (values === undefined)
  264. throw new Error("No value provided");
  265. this.outputs[output][key] = !!values;
  266. } else if (output !== "memory" && action === "reset") {
  267. this.outputs[output][key] = this.default[output][key];
  268. } else
  269. throw new Error(
  270. `Action "${action}" not found for ${key} in ${output}`
  271. );
  272. }
  273. }
  274. }
  275. }