new version
This commit is contained in:
38
apps/api/src/lib/logger.ts
Normal file
38
apps/api/src/lib/logger.ts
Normal file
@@ -0,0 +1,38 @@
|
||||
import { generateUlid } from '../utils/ulid';
|
||||
import { getTraceId } from './trace-store';
|
||||
|
||||
const instanceId = generateUlid();
|
||||
|
||||
function getCallerInfo(): { file: string; line: number } {
|
||||
const stack = new Error().stack;
|
||||
if (!stack) return { file: 'unknown', line: 0 };
|
||||
|
||||
const lines = stack.split('\n');
|
||||
// Skip: Error, logger method, actual caller
|
||||
const callerLine = lines[3] || '';
|
||||
const match = callerLine.match(/\((.+):(\d+):\d+\)/) || callerLine.match(/at (.+):(\d+):\d+/);
|
||||
if (match) return { file: match[1], line: parseInt(match[2]) };
|
||||
return { file: 'unknown', line: 0 };
|
||||
}
|
||||
|
||||
function log(level: string, message: string): void {
|
||||
const caller = getCallerInfo();
|
||||
const entry = {
|
||||
timestamp: new Date().toISOString(),
|
||||
level,
|
||||
instance_id: instanceId,
|
||||
file: caller.file,
|
||||
line: caller.line,
|
||||
trace_id: getTraceId(),
|
||||
message,
|
||||
};
|
||||
process.stdout.write(JSON.stringify(entry) + '\n');
|
||||
}
|
||||
|
||||
export const logger = {
|
||||
instanceId,
|
||||
info: (msg: string) => log('INFO', msg),
|
||||
warn: (msg: string) => log('WARN', msg),
|
||||
error: (msg: string) => log('ERROR', msg),
|
||||
debug: (msg: string) => log('DEBUG', msg),
|
||||
};
|
||||
7
apps/api/src/lib/trace-store.ts
Normal file
7
apps/api/src/lib/trace-store.ts
Normal file
@@ -0,0 +1,7 @@
|
||||
import { AsyncLocalStorage } from 'node:async_hooks';
|
||||
|
||||
export const traceStore = new AsyncLocalStorage<string>();
|
||||
|
||||
export function getTraceId(): string {
|
||||
return traceStore.getStore() || 'N/A';
|
||||
}
|
||||
Reference in New Issue
Block a user