All files / varjoliitokauppa/lib monitoring.ts

75.86% Statements 22/29
57.89% Branches 11/19
85.71% Functions 6/7
75% Lines 21/28

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105                              1x   2x   2x           1x 2x 2x                   1x 2x   2x         2x                             1x 2x         2x 2x 1x 1x     1x         1x     1x       1x                   1x                    
type LogLevel = 'info' | 'warn' | 'error';
 
type ErrorPayload = {
  name?: string;
  message: string;
  stack?: string;
  cause?: string;
};
 
type LogPayload = Record<string, unknown> & {
  timestamp?: string;
  service?: string;
  env?: string;
};
 
const SERVICE_NAME = process.env.MONITORING_SERVICE_NAME || 'varjoliitokauppa';
 
const getTimestamp = () => new Date().toISOString();
 
const baseFields = (): LogPayload => ({
  timestamp: getTimestamp(),
  service: SERVICE_NAME,
  env: process.env.NODE_ENV || 'unknown',
});
 
const safeStringify = (payload: LogPayload) => {
  try {
    return JSON.stringify(payload);
  } catch {
    return JSON.stringify({
      ...baseFields(),
      type: 'log-serialization-error',
      message: 'Failed to serialize log payload',
    });
  }
};
 
export const normalizeError = (error: unknown): ErrorPayload => {
  Eif (error instanceof Error) {
    const cause =
      typeof error.cause === 'string'
        ? error.cause
        : error.cause instanceof Error
          ? error.cause.message
          : undefined;
    return {
      name: error.name,
      message: error.message,
      stack: error.stack,
      cause,
    };
  }
 
  if (typeof error === 'string') {
    return { message: error };
  }
 
  return { message: 'Unknown error' };
};
 
export const logEvent = (event: LogPayload, level: LogLevel = 'info') => {
  const payload = {
    ...baseFields(),
    ...event,
  };
 
  const line = safeStringify(payload);
  if (level === 'error') {
    console.error(line);
    return;
  }
 
  Iif (level === 'warn') {
    console.warn(line);
    return;
  }
 
  console.log(line);
};
 
export const logError = (
  error: unknown,
  context: Record<string, unknown> = {}
) => {
  logEvent(
    {
      type: 'error',
      error: normalizeError(error),
      ...context,
    },
    'error'
  );
};
 
export const logPerformance = (
  metric: Record<string, unknown>,
  context: Record<string, unknown> = {}
) => {
  logEvent({
    type: 'performance',
    metric,
    ...context,
  });
};