Repository navigation
Expand file tree
/
Copy pathlogger.ts
More file actions
297 lines (269 loc) · 8.95 KB
/
Copy pathlogger.ts
File metadata and controls
297 lines (269 loc) · 8.95 KB
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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
<
8000
div data-line-number="289" class="react-line-number react-code-text" style="padding-right:16px">289290
291
292
293
294
295
296
297
import * as Sentry from '@sentry/react-native';
// =============================================================================
// Verbose Logging Control
// =============================================================================
/**
* Module-level state for verbose logging.
* When false, only warn and error levels are logged to console.
* When true, all levels (debug, info, warn, error, trace) are logged.
* Defaults to true in development mode.
*/
let verboseLoggingEnabled = __DEV__;
/**
* Set whether verbose logging is enabled.
* Called by DevToolsContext to sync its state with the logger.
*
* @param enabled - Whether to enable verbose logging
*/
export function setVerboseLogging(enabled: boolean): void {
verboseLoggingEnabled = enabled;
}
/**
* Get the current verbose logging state.
*
* @returns Whether verbose logging is enabled
*/
export function getVerboseLogging(): boolean {
return verboseLoggingEnabled;
}
// =============================================================================
// Types & Interfaces
// =============================================================================
export type LogLevel = 'debug' | 'info' | 'warn' | 'error' | 'trace';
/**
* Type-safe metadata for log entries.
* Uses `unknown` instead of `any` to enforce type checking at call sites.
*/
export type LogMetadata = Record<string, unknown>;
export interface Logger {
debug(message: string, metadata?: LogMetadata): void;
info(message: string, metadata?: LogMetadata): void;
warn(message: string, metadata?: LogMetadata): void;
error(message: string, error?: Error, metadata?: LogMetadata): void;
trace(message: string, metadata?: LogMetadata): void;
}
export enum LogCategory {
AUTH = 'auth',
NAVIGATION = 'navigation',
DATABASE = 'database',
API = 'http',
UI = 'ui',
STORAGE = 'storage',
NOTIFICATION = 'notification',
SYNC = 'sync',
ERROR = 'error',
ANALYTICS = 'analytics',
}
// =============================================================================
// Internal Functions
// =============================================================================
/**
* Internal log function that handles Sentry breadcrumbs, error capture, and console output.
*
* @param level - The severity level of the log
* @param message - Human-readable log message
* @param error - Optional Error object for error-level logs
* @param metadata - Optional structured data to attach to the log
*/
function log(level: LogLevel, message: string, error?: Error, metadata?: LogMetadata): void {
createBreadcrumb(level, message, error, metadata);
// For error-level logs with an Error object, capture to Sentry
// This sends the error to Sentry immediately (not just as a breadcrumb)
if (level === 'error' && error) {
captureErrorToSentry(message, error, metadata);
}
if (__DEV__) {
// When verbose logging is disabled, only log warn and error levels
const isImportantLevel = level === 'warn' || level === 'error';
if (verboseLoggingEnabled || isImportantLevel) {
logToConsole(level, message, error, metadata);
}
}
}
/**
* Capture an error to Sentry with context.
* Silently fails if Sentry is not initialized.
*
* @param message - Human-readable error message
* @param error - The Error object to capture
* @param metadata - Optional additional context
*/
function captureErrorToSentry(message: string, error: Error, metadata?: LogMetadata): void {
try {
const { category, ...extraContext } = metadata ?? {};
Sentry.captureException(error, {
tags: {
category: typeof category === 'string' ? category : 'uncategorized',
},
extra: {
message,
...extraContext,
},
});
} catch {
// Silently fail if Sentry not initialized
if (__DEV__) {
console.debug('[Logger] Sentry not initialized, error not captured');
}
}
}
<
8000
div>
/**
* Reserved keys used internally for error information in breadcrumb data.
* These keys should not be used in metadata to avoid silent overwrites.
*/
const RESERVED_ERROR_KEYS = ['error_message', 'error_stack', 'error_name'] as const;
/**
* Build error info object with namespaced keys to avoid conflicts with user metadata.
* Uses 'error_message', 'error_stack', and 'error_name' instead of 'error' and 'stack'
* to prevent silent overwrites if metadata contains those common keys.
*
* @param error - The Error object to extract info from
* @returns Object with namespaced error properties
*/
function buildErrorInfo(error: Error): Record<string, unknown> {
return {
error_message: error.message,
error_stack: error.stack,
error_name: error.name,
};
}
/**
* Create Sentry breadcrumb with proper level mapping.
* Silently fails if Sentry is not initialized to prevent errors.
*
* @remarks
* Error information is stored with namespaced keys ('error_message', 'error_stack',
* 'error_name') to avoid conflicts with user-provided metadata. These keys are
* reserved and should not be used in metadata.
*
* @param level - The log level (debug, info, warn, error, trace)
* @param message - The log message
* @param error - Optional Error object with stack trace
* @param metadata - Optional additional context (avoid using reserved keys)
*/
function createBreadcrumb(
level: LogLevel,
message: string,
error?: Error,
metadata?: LogMetadata
): void {
try {
// Warn in development if metadata contains reserved keys
if (__DEV__ && metadata) {
const conflicts = RESERVED_ERROR_KEYS.filter((key) => key in metadata);
if (conflicts.length > 0) {
console.warn(
`[Logger] Metadata contains reserved keys that will be overwritten: ${conflicts.join(', ')}`
);
}
}
// Extract category for breadcrumb field, spread remaining metadata into data
// This prevents duplicate 'category' keys in the breadcrumb
const { category, ...restMetadata } = metadata ?? {};
// Build breadcrumb data with namespaced error keys to avoid conflicts
const breadcrumbData: Record<string, unknown> = {
...restMetadata,
...(error && buildErrorInfo(error)),
};
Sentry.addBreadcrumb({
level: mapLevelToSentry(level),
category: typeof category === 'string' ? category : 'log',
message,
data: breadcrumbData,
timestamp: Date.now() / 1000,
});
} catch {
// Silently fail if Sentry not initialized
}
}
/**
* Map logger levels to Sentry breadcrumb levels
*/
function mapLevelToSentry(level: LogLevel): Sentry.SeverityLevel {
const mapping: Record<LogLevel, Sentry.SeverityLevel> = {
debug: 'debug',
info: 'info',
warn: 'warning',
error: 'error',
trace: 'debug',
};
return mapping[level];
}
/**
* Output formatted log to console in development.
* Console methods accept unknown values and stringify them appropriately.
*
* @param level - The log level for formatting
* @param message - The log message
* @param error - Optional Error object
* @param metadata - Optional metadata to display
*/
function logToConsole(
level: LogLevel,
message: string,
error?: Error,
metadata?: LogMetadata
): void {
const consoleMethod = getConsoleMethod(level);
const formattedMessage = `[${level.toUpperCase()}] ${message}`;
const hasMetadata = metadata && Object.keys(metadata).length > 0;
if (error) {
// Only include metadata if it has content to avoid cluttering output
if (hasMetadata) {
consoleMethod(formattedMessage, error, metadata);
} else {
consoleMethod(formattedMessage, error);
}
} else if (hasMetadata) {
consoleMethod(formattedMessage, metadata);
} else {
consoleMethod(formattedMessage);
}
}
/**
* Map log level to appropriate console method
*/
function getConsoleMethod(level: LogLevel): Console['log'] {
const methods: Record<LogLevel, Console['log']> = {
debug: console.debug,
info: console.info,
warn: console.warn,
error: console.error,
trace: console.trace,
};
return methods[level];
}
// =============================================================================
// Exported Logger
// =============================================================================
/**
* Universal logger that routes all logs through Sentry breadcrumbs
* with development console fallback.
*
* @example
* ```typescript
* import { logger, LogCategory } from '@/lib/logger';
*
* // Basic logging
* logger.info('User logged in');
*
* // With metadata
* logger.info('Task completed', { taskId: '123', duration: 450 });
*
* // With category
* logger.info('User signed in', {
* category: LogCategory.AUTH,
* userId: '123',
* });
*
* // Errors with context
* logger.error('Failed to fetch data', fetchError, { userId: '456' });
* ```
*/
export const logger: Logger = {
debug: (msg, meta) => log('debug', msg, undefined, meta),
info: (msg, meta) => log('info', msg, undefined, meta),
warn: (msg, meta) => log('warn', msg, undefined, meta),
error: (msg, err, meta) => log('error', msg, err, meta),
trace: (msg, meta) => log('trace', msg, undefined, meta),
};