sloplog 0.0.4 → 0.0.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,20 @@
1
1
  import type { WideEventBase, EventPartial } from '../index.js';
2
+ /**
3
+ * Truncate a stack trace to MAX_STACK_LINES lines
4
+ */
5
+ export declare function truncateStack(stack: string | undefined): string | undefined;
6
+ /**
7
+ * Flatten a nested object to dot-notation keys.
8
+ * Arrays use numeric indices: `partialName.0.subKey`
9
+ * Stack traces are automatically truncated.
10
+ */
11
+ export declare function flattenObject(obj: unknown, prefix?: string, result?: Record<string, unknown>): Record<string, unknown>;
12
+ /**
13
+ * Execute a function with all console methods suppressed.
14
+ * Useful for preventing Sentry SDK from outputting its own logs to console
15
+ * when we're already handling console output ourselves.
16
+ */
17
+ export declare function withSuppressedConsole<T>(fn: () => T): T;
2
18
  /**
3
19
  * Options passed to collectors when flushing an event
4
20
  */
@@ -19,16 +35,34 @@ export interface LogCollectorClient {
19
35
  }
20
36
  /** Type alias for partial values (singular or array) */
21
37
  type PartialValue = EventPartial<string> | EventPartial<string>[];
38
+ /**
39
+ * Options for StdioCollector
40
+ */
41
+ export interface StdioCollectorOptions {
42
+ /**
43
+ * Prefix to prepend to each log line.
44
+ * Default: "[wide-event]"
45
+ */
46
+ prefix?: string;
47
+ /**
48
+ * If true, pretty-print the JSON output with 2-space indentation.
49
+ * Default: true
50
+ */
51
+ prettyPrint?: boolean;
52
+ }
22
53
  /**
23
54
  * Simple collector to log the event to stdout/console
24
55
  */
25
56
  export declare class StdioCollector implements LogCollectorClient {
57
+ private prefix;
58
+ private prettyPrint;
59
+ constructor(options?: StdioCollectorOptions);
26
60
  flush(eventBase: WideEventBase, partials: Map<string, PartialValue>, _options: FlushOptions): Promise<void>;
27
61
  }
28
62
  /**
29
63
  * Create a collector that logs events to stdout/console.
30
64
  */
31
- export declare function stdioCollector(): StdioCollector;
65
+ export declare function stdioCollector(options?: StdioCollectorOptions): StdioCollector;
32
66
  /**
33
67
  * Composes multiple collectors together, flushing to all of them in parallel
34
68
  */
@@ -1,24 +1,116 @@
1
+ /**
2
+ * Maximum number of stack trace lines to include in error logs
3
+ */
4
+ const MAX_STACK_LINES = 10;
5
+ /**
6
+ * Truncate a stack trace to MAX_STACK_LINES lines
7
+ */
8
+ export function truncateStack(stack) {
9
+ if (!stack)
10
+ return stack;
11
+ const lines = stack.split('\n');
12
+ if (lines.length <= MAX_STACK_LINES)
13
+ return stack;
14
+ return lines.slice(0, MAX_STACK_LINES).join('\n') + '\n ... truncated';
15
+ }
16
+ /**
17
+ * Flatten a nested object to dot-notation keys.
18
+ * Arrays use numeric indices: `partialName.0.subKey`
19
+ * Stack traces are automatically truncated.
20
+ */
21
+ export function flattenObject(obj, prefix = '', result = {}) {
22
+ if (obj === null || obj === undefined) {
23
+ if (prefix) {
24
+ result[prefix] = obj;
25
+ }
26
+ return result;
27
+ }
28
+ if (Array.isArray(obj)) {
29
+ for (let i = 0; i < obj.length; i++) {
30
+ flattenObject(obj[i], prefix ? `${prefix}.${i}` : String(i), result);
31
+ }
32
+ return result;
33
+ }
34
+ if (typeof obj === 'object') {
35
+ for (const [key, value] of Object.entries(obj)) {
36
+ const newKey = prefix ? `${prefix}.${key}` : key;
37
+ // Truncate stack traces
38
+ if (key === 'stack' && typeof value === 'string') {
39
+ result[newKey] = truncateStack(value);
40
+ }
41
+ else {
42
+ flattenObject(value, newKey, result);
43
+ }
44
+ }
45
+ return result;
46
+ }
47
+ if (prefix) {
48
+ result[prefix] = obj;
49
+ }
50
+ return result;
51
+ }
52
+ /**
53
+ * Execute a function with all console methods suppressed.
54
+ * Useful for preventing Sentry SDK from outputting its own logs to console
55
+ * when we're already handling console output ourselves.
56
+ */
57
+ export function withSuppressedConsole(fn) {
58
+ /* eslint-disable no-console */
59
+ const noop = () => { };
60
+ const originalLog = console.log;
61
+ const originalInfo = console.info;
62
+ const originalWarn = console.warn;
63
+ const originalError = console.error;
64
+ const originalDebug = console.debug;
65
+ const originalTrace = console.trace;
66
+ console.log = noop;
67
+ console.info = noop;
68
+ console.warn = noop;
69
+ console.error = noop;
70
+ console.debug = noop;
71
+ console.trace = noop;
72
+ try {
73
+ return fn();
74
+ }
75
+ finally {
76
+ console.log = originalLog;
77
+ console.info = originalInfo;
78
+ console.warn = originalWarn;
79
+ console.error = originalError;
80
+ console.debug = originalDebug;
81
+ console.trace = originalTrace;
82
+ }
83
+ /* eslint-enable no-console */
84
+ }
1
85
  /**
2
86
  * Simple collector to log the event to stdout/console
3
87
  */
4
88
  export class StdioCollector {
89
+ prefix;
90
+ prettyPrint;
91
+ constructor(options = {}) {
92
+ this.prefix = options.prefix ?? '[wide-event]';
93
+ this.prettyPrint = options.prettyPrint ?? true;
94
+ }
5
95
  async flush(eventBase, partials, _options) {
6
96
  const partialsObj = {};
7
97
  for (const [key, value] of partials) {
8
98
  partialsObj[key] = value;
9
99
  }
10
- // eslint-disable-next-line no-console
11
- console.log({
100
+ const event = {
12
101
  ...eventBase,
13
102
  ...partialsObj,
14
- });
103
+ };
104
+ const json = this.prettyPrint ? JSON.stringify(event, null, 2) : JSON.stringify(event);
105
+ // eslint-disable-next-line no-console
106
+ console.log(this.prefix, json);
15
107
  }
16
108
  }
17
109
  /**
18
110
  * Create a collector that logs events to stdout/console.
19
111
  */
20
- export function stdioCollector() {
21
- return new StdioCollector();
112
+ export function stdioCollector(options = {}) {
113
+ return new StdioCollector(options);
22
114
  }
23
115
  /**
24
116
  * Composes multiple collectors together, flushing to all of them in parallel
@@ -17,25 +17,45 @@ export interface SentryLogger {
17
17
  */
18
18
  export interface SentryCollectorOptions {
19
19
  /**
20
- * Sentry logger instance (e.g. Sentry.logger). Requires the Sentry logger
21
- * integration to be configured during Sentry.init().
20
+ * Sentry logger instance (e.g. Sentry.logger) or a function that returns it.
21
+ * Using a getter function allows lazy initialization (e.g., waiting for Sentry.init()).
22
+ * Requires the Sentry logger integration to be configured during Sentry.init().
22
23
  */
23
- logger: SentryLogger;
24
+ logger: SentryLogger | (() => SentryLogger | undefined);
24
25
  /** Default log level for events (default: "info") */
25
26
  level?: SentryLogLevel;
26
27
  /** Optional function to derive log level per event */
27
28
  levelSelector?: (event: WideEventBase, partials: Map<string, PartialValue>, options: FlushOptions) => SentryLogLevel;
28
29
  /** Log message to use (default: "wide-event") */
29
30
  message?: string;
31
+ /**
32
+ * If true, flatten nested attributes to dot-notation keys for better
33
+ * queryability in Sentry (e.g., `error.message`, `spans.0.name`).
34
+ * Default: true
35
+ */
36
+ flattenAttributes?: boolean;
37
+ /**
38
+ * If true, suppress console output from Sentry SDK during logging.
39
+ * Useful when you're already handling console output via another collector.
40
+ * Default: true
41
+ */
42
+ suppressConsole?: boolean;
30
43
  }
31
44
  /**
32
- * Collector that sends events to Sentry Logs via the Sentry logger API
45
+ * Collector that sends events to Sentry Logs via the Sentry logger API.
46
+ *
47
+ * Note: This is a hacky implementation that doesn't fully take advantage
48
+ * of Sentry's features. It flattens nested objects to dot-notation keys
49
+ * for queryability, but Sentry's structured logging would be more powerful
50
+ * if used with proper Sentry integrations.
33
51
  */
34
52
  export declare class SentryCollector implements LogCollectorClient {
35
- private logger;
53
+ private getLogger;
36
54
  private defaultLevel;
37
55
  private levelSelector?;
38
56
  private message;
57
+ private flattenAttributes;
58
+ private suppressConsole;
39
59
  constructor(options: SentryCollectorOptions);
40
60
  flush(event: WideEventBase, partials: Map<string, PartialValue>, options: FlushOptions): Promise<void>;
41
61
  }
@@ -1,40 +1,69 @@
1
+ import { flattenObject, withSuppressedConsole } from './index.js';
1
2
  /**
2
- * Collector that sends events to Sentry Logs via the Sentry logger API
3
+ * Collector that sends events to Sentry Logs via the Sentry logger API.
4
+ *
5
+ * Note: This is a hacky implementation that doesn't fully take advantage
6
+ * of Sentry's features. It flattens nested objects to dot-notation keys
7
+ * for queryability, but Sentry's structured logging would be more powerful
8
+ * if used with proper Sentry integrations.
3
9
  */
4
10
  export class SentryCollector {
5
- logger;
11
+ getLogger;
6
12
  defaultLevel;
7
13
  levelSelector;
8
14
  message;
15
+ flattenAttributes;
16
+ suppressConsole;
9
17
  constructor(options) {
10
- this.logger = options.logger;
18
+ // Support both direct logger and getter function for lazy initialization
19
+ this.getLogger =
20
+ typeof options.logger === 'function' ? options.logger : () => options.logger;
11
21
  this.defaultLevel = options.level ?? 'info';
12
22
  this.levelSelector = options.levelSelector;
13
23
  this.message = options.message ?? 'wide-event';
24
+ this.flattenAttributes = options.flattenAttributes ?? true;
25
+ this.suppressConsole = options.suppressConsole ?? true;
14
26
  }
15
27
  async flush(event, partials, options) {
28
+ const logger = this.getLogger();
29
+ if (!logger) {
30
+ return;
31
+ }
16
32
  const partialsObj = {};
17
33
  for (const [key, value] of partials) {
18
34
  partialsObj[key] = value;
19
35
  }
20
- const attributes = {
36
+ const combined = {
21
37
  ...event,
22
38
  ...partialsObj,
23
39
  };
40
+ // Flatten nested attributes to dot-notation for better Sentry queryability
41
+ const attributes = this.flattenAttributes
42
+ ? flattenObject(combined)
43
+ : combined;
24
44
  const level = this.levelSelector
25
45
  ? this.levelSelector(event, partials, options)
26
46
  : this.defaultLevel;
27
- const loggerMethod = (level === 'trace' && this.logger.trace) ||
28
- (level === 'debug' && this.logger.debug) ||
29
- (level === 'info' && this.logger.info) ||
30
- (level === 'warn' && this.logger.warn) ||
31
- (level === 'error' && this.logger.error) ||
32
- (level === 'fatal' && this.logger.fatal);
33
- if (loggerMethod) {
34
- loggerMethod(this.message, attributes);
35
- return;
47
+ const logFn = () => {
48
+ const loggerMethod = (level === 'trace' && logger.trace) ||
49
+ (level === 'debug' && logger.debug) ||
50
+ (level === 'info' && logger.info) ||
51
+ (level === 'warn' && logger.warn) ||
52
+ (level === 'error' && logger.error) ||
53
+ (level === 'fatal' && logger.fatal);
54
+ if (loggerMethod) {
55
+ loggerMethod(this.message, attributes);
56
+ return;
57
+ }
58
+ logger.log?.(level, this.message, attributes);
59
+ };
60
+ // Suppress console output from Sentry SDK if configured
61
+ if (this.suppressConsole) {
62
+ withSuppressedConsole(logFn);
63
+ }
64
+ else {
65
+ logFn();
36
66
  }
37
- this.logger.log?.(level, this.message, attributes);
38
67
  }
39
68
  }
40
69
  /**
package/dist/index.d.ts CHANGED
@@ -1,8 +1,10 @@
1
1
  import type { ZodRawShape } from 'zod';
2
2
  import type { LogCollectorClient } from './collectors/index.js';
3
+ export * from './collectors/index.js';
4
+ export * from './collectors/sentry.js';
3
5
  import type { PartialMetadata, PartialDefinition, PartialOptions, Registry, RegistryType } from './registry.js';
4
6
  /** Current sloplog library version (propagated onto Service). */
5
- export declare const SLOPLOG_VERSION = "0.0.2";
7
+ export declare const SLOPLOG_VERSION = "0.0.6";
6
8
  /**
7
9
  * TYPES
8
10
  */
package/dist/index.js CHANGED
@@ -1,4 +1,7 @@
1
1
  import { extractPartialMetadata } from './registry.js';
2
+ // Re-export collectors from main entry point for easier bundler compatibility
3
+ export * from './collectors/index.js';
4
+ export * from './collectors/sentry.js';
2
5
  /**
3
6
  * Generate a nano ID for unique identifiers
4
7
  */
@@ -11,7 +14,7 @@ function nanoId() {
11
14
  return result;
12
15
  }
13
16
  /** Current sloplog library version (propagated onto Service). */
14
- export const SLOPLOG_VERSION = '0.0.2';
17
+ export const SLOPLOG_VERSION = '0.0.6';
15
18
  /** Default language marker when Service.sloplogLanguage is not set. */
16
19
  const SLOPLOG_LANGUAGE = 'typescript';
17
20
  function isOriginatorResult(input) {
@@ -11,11 +11,11 @@ declare const error: import("./registry.js").PartialFactory<"error", {
11
11
  declare const logMessage: import("./registry.js").PartialFactory<"log_message", {
12
12
  message: z.ZodString;
13
13
  level: z.ZodEnum<{
14
- error: "error";
15
14
  trace: "trace";
16
15
  debug: "debug";
17
16
  info: "info";
18
17
  warn: "warn";
18
+ error: "error";
19
19
  fatal: "fatal";
20
20
  }>;
21
21
  data: z.ZodOptional<z.ZodString>;
@@ -57,11 +57,11 @@ export declare const builtInPartials: {
57
57
  log_message: import("./registry.js").PartialFactory<"log_message", {
58
58
  message: z.ZodString;
59
59
  level: z.ZodEnum<{
60
- error: "error";
61
60
  trace: "trace";
62
61
  debug: "debug";
63
62
  info: "info";
64
63
  warn: "warn";
64
+ error: "error";
65
65
  fatal: "fatal";
66
66
  }>;
67
67
  data: z.ZodOptional<z.ZodString>;
@@ -102,11 +102,11 @@ export declare const builtInRegistry: import("./registry.js").Registry<(import("
102
102
  }> | import("./registry.js").PartialFactory<"log_message", {
103
103
  message: z.ZodString;
104
104
  level: z.ZodEnum<{
105
- error: "error";
106
105
  trace: "trace";
107
106
  debug: "debug";
108
107
  info: "info";
109
108
  warn: "warn";
109
+ error: "error";
110
110
  fatal: "fatal";
111
111
  }>;
112
112
  data: z.ZodOptional<z.ZodString>;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "sloplog",
3
- "version": "0.0.4",
3
+ "version": "0.0.6",
4
4
  "description": "A TypeScript library for constructing wide events",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",