startup-logging.ts 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. import { performance } from "node:perf_hooks";
  2. import type { LogContext, Logger, LoggerFactory, LogLevel } from "@zcode/contracts";
  3. interface StartupTimerLogOptions {
  4. context?: LogContext;
  5. event: string;
  6. stage: string;
  7. }
  8. export class StartupTimer {
  9. private lastMarkAt: number;
  10. constructor(
  11. private readonly logger: Logger,
  12. private readonly baseContext: LogContext,
  13. private readonly startedAt: number = startupNow(),
  14. ) {
  15. this.lastMarkAt = startedAt;
  16. }
  17. start(message: string, options: StartupTimerLogOptions): void {
  18. const now = startupNow();
  19. this.logger.info(message, this.createContext(options, now, 0, "started"));
  20. }
  21. mark(message: string, options: StartupTimerLogOptions): void {
  22. const now = startupNow();
  23. const durationMs = elapsedMs(this.lastMarkAt, now);
  24. this.lastMarkAt = now;
  25. this.logger.info(message, this.createContext(options, now, durationMs, "completed"));
  26. }
  27. complete(message: string, options: StartupTimerLogOptions): void {
  28. const now = startupNow();
  29. this.logger.info(
  30. message,
  31. this.createContext(options, now, elapsedMs(this.startedAt, now), "completed"),
  32. );
  33. }
  34. fail(message: string, error: unknown, options: StartupTimerLogOptions): void {
  35. const now = startupNow();
  36. this.logger.error(
  37. message,
  38. toError(error),
  39. this.createContext(options, now, elapsedMs(this.startedAt, now), "failed"),
  40. );
  41. }
  42. private createContext(
  43. options: StartupTimerLogOptions,
  44. now: number,
  45. durationMs: number,
  46. status: NonNullable<LogContext["status"]>,
  47. ): LogContext {
  48. return {
  49. ...this.baseContext,
  50. ...options.context,
  51. durationMs,
  52. event: options.event,
  53. stage: options.stage,
  54. status,
  55. totalDurationMs: elapsedMs(this.startedAt, now),
  56. };
  57. }
  58. }
  59. export function startupNow(): number {
  60. return performance.now();
  61. }
  62. function toError(error: unknown): Error {
  63. if (error instanceof Error) {
  64. return error;
  65. }
  66. return new Error(String(error));
  67. }
  68. function elapsedMs(startedAt: number, endedAt: number): number {
  69. return Math.max(0, Math.round(endedAt - startedAt));
  70. }