LogBook.ts 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319
  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: true,
  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. const messageParts = [];
  173. // If we want to show timestamps, e.g. 2022-11-28T18:13:28.081Z
  174. if (this._outputs.console.timestamp)
  175. messageParts.push(`${new Date(log.timestamp).toISOString()}`);
  176. // If we want to show the log type, in uppercase
  177. if (this._outputs.console.type)
  178. messageParts.push(
  179. `[${log.type ? log.type.toUpperCase() : "INFO"}]`
  180. );
  181. // If we want to show titles, show it
  182. if (this._outputs.console.title && title)
  183. messageParts.push(`[${title}]`);
  184. // If we want to the message, show it
  185. if (this._outputs.console.message) messageParts.push(log.message);
  186. const message = messageParts.join(" ");
  187. // If we want to show colors, prepend the color code
  188. if (this._outputs.console.color) {
  189. let coloredMessage = "";
  190. switch (log.type) {
  191. case "success":
  192. coloredMessage += COLOR_GREEN;
  193. break;
  194. case "error":
  195. coloredMessage += COLOR_RED;
  196. break;
  197. case "debug":
  198. coloredMessage += COLOR_YELLOW;
  199. break;
  200. case "info":
  201. default:
  202. coloredMessage += COLOR_CYAN;
  203. break;
  204. }
  205. coloredMessage += message;
  206. // Reset the color at the end of the message
  207. coloredMessage += COLOR_RESET;
  208. return coloredMessage;
  209. }
  210. return message;
  211. }
  212. /**
  213. * Update output settings for LogBook
  214. * 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
  215. * LogBook is currently used as a singleton, so changing it will update outputs for the same logbook used everywhere
  216. *
  217. * @param output - Output name (console or memory)
  218. * @param key - Output key to update (include, exclude, enabled, name, type, etc.)
  219. * @param action - Action (set, add or reset)
  220. * @param values - Value we want to set
  221. */
  222. public async updateOutput(
  223. output: "console" | "memory",
  224. key: keyof LogOutputOptions | "enabled",
  225. action: "set" | "add" | "reset",
  226. values?: LogOutputOptions[keyof LogOutputOptions]
  227. ) {
  228. switch (key) {
  229. // Set, add-to or reset (to) the include/exclude filter lists for a specific output
  230. case "include":
  231. case "exclude": {
  232. if (action === "set" || action === "add") {
  233. if (!values || typeof values !== "object")
  234. throw new Error("No filters provided");
  235. const filters = Array.isArray(values) ? values : [values];
  236. if (action === "set") this._outputs[output][key] = filters;
  237. if (action === "add")
  238. this._outputs[output][key] = [
  239. ...(this._outputs[output][key] || []),
  240. ...filters
  241. ];
  242. } else if (action === "reset") {
  243. this._outputs[output][key] =
  244. this._default[output][key] || [];
  245. } else
  246. throw new Error(
  247. `Action "${action}" not found for ${key} in ${output}`
  248. );
  249. break;
  250. }
  251. // Set an output to be enabled or disabled
  252. case "enabled": {
  253. if (output === "memory" && action === "set") {
  254. if (values === undefined)
  255. throw new Error("No value provided");
  256. this._outputs[output][key] = !!values;
  257. } else
  258. throw new Error(
  259. `Action "${action}" not found for ${key} in ${output}`
  260. );
  261. break;
  262. }
  263. // Set some other property of an output
  264. default: {
  265. if (output !== "memory" && action === "set") {
  266. if (values === undefined)
  267. throw new Error("No value provided");
  268. this._outputs[output][key] = !!values;
  269. } else if (output !== "memory" && action === "reset") {
  270. this._outputs[output][key] = this._default[output][key];
  271. } else
  272. throw new Error(
  273. `Action "${action}" not found for ${key} in ${output}`
  274. );
  275. }
  276. }
  277. }
  278. static getPrimaryInstance(): LogBook {
  279. return this.primaryInstance;
  280. }
  281. static setPrimaryInstance(instance: LogBook) {
  282. this.primaryInstance = instance;
  283. }
  284. }