LogBook.ts 8.9 KB

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