@gratheon/log-lib 2.2.6 → 2.2.7

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.
package/dist/logger.js CHANGED
@@ -34,6 +34,7 @@ const fs = __importStar(require("fs"));
34
34
  const path = __importStar(require("path"));
35
35
  let conn = null;
36
36
  let dbInitialized = false;
37
+ let initPromise = null;
37
38
  const LOG_LEVELS = {
38
39
  debug: 0,
39
40
  info: 1,
@@ -316,26 +317,39 @@ function safeMeta(meta) {
316
317
  return meta;
317
318
  }
318
319
  function storeInDB(level, message, meta, stacktrace) {
319
- if (!conn || !dbInitialized) {
320
- // Database not ready yet, skip DB logging
320
+ if (!conn) {
321
+ // Database not configured, skip DB logging
321
322
  return;
322
323
  }
323
- try {
324
- const msg = safeToStringMessage(message);
325
- const metaObj = safeMeta(meta);
326
- const metaStr = (0, fast_safe_stringify_1.default)(metaObj).slice(0, 2000);
327
- const stackStr = stacktrace || '';
328
- // Fire and forget; avoid awaiting in hot path. Catch errors to avoid unhandled rejection.
329
- conn.query((0, mysql_1.sql) `INSERT INTO \`logs\` (level, message, meta, stacktrace, timestamp) VALUES (${level}, ${msg}, ${metaStr}, ${stackStr}, NOW())`).catch(e => {
324
+ // Wait for initialization to complete before writing
325
+ const doStore = async () => {
326
+ if (initPromise) {
327
+ await initPromise.catch(() => { }); // Wait but ignore errors
328
+ }
329
+ if (!dbInitialized) {
330
+ // Initialization failed, skip DB logging
331
+ return;
332
+ }
333
+ try {
334
+ const msg = safeToStringMessage(message);
335
+ const metaObj = safeMeta(meta);
336
+ const metaStr = (0, fast_safe_stringify_1.default)(metaObj).slice(0, 2000);
337
+ const stackStr = stacktrace || '';
338
+ await conn.query((0, mysql_1.sql) `INSERT INTO \`logs\` (level, message, meta, stacktrace, timestamp) VALUES (${level}, ${msg}, ${metaStr}, ${stackStr}, NOW())`);
339
+ }
340
+ catch (e) {
330
341
  // fallback console output only - but don't spam
331
342
  if (process.env.ENV_ID === 'dev') {
332
343
  console.error('Failed to persist log to DB', e);
333
344
  }
334
- });
335
- }
336
- catch (e) {
337
- console.error('Unexpected failure preparing log for DB', e);
338
- }
345
+ }
346
+ };
347
+ // Fire and forget
348
+ doStore().catch(e => {
349
+ if (process.env.ENV_ID === 'dev') {
350
+ console.error('Unexpected failure preparing log for DB', e);
351
+ }
352
+ });
339
353
  }
340
354
  function createLogger(config = {}) {
341
355
  // Set up log level filtering
@@ -344,11 +358,9 @@ function createLogger(config = {}) {
344
358
  process.env.LOG_LEVEL ||
345
359
  (process.env.ENV_ID === 'dev' ? 'debug' : 'info');
346
360
  currentLogLevel = LOG_LEVELS[configuredLevel] ?? LOG_LEVELS.info;
347
- // Start initialization asynchronously but don't wait for it (only if MySQL config provided)
361
+ // Start initialization asynchronously (only if MySQL config provided)
348
362
  if (config.mysql) {
349
- initializeConnection(config).catch(err => {
350
- console.error('Error during log database initialization:', err);
351
- });
363
+ initPromise = initializeConnection(config);
352
364
  }
353
365
  const logger = {
354
366
  info: (message, meta) => {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@gratheon/log-lib",
3
- "version": "2.2.6",
3
+ "version": "2.2.7",
4
4
  "description": "Logging library with console and MySQL database persistence",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
package/src/logger.ts CHANGED
@@ -7,6 +7,7 @@ import { LoggerConfig, Logger, FastifyLogger, LogMetadata, LogLevel } from "./ty
7
7
 
8
8
  let conn: ConnectionPool | null = null;
9
9
  let dbInitialized = false;
10
+ let initPromise: Promise<void> | null = null;
10
11
 
11
12
  const LOG_LEVELS: Record<LogLevel, number> = {
12
13
  debug: 0,
@@ -297,25 +298,43 @@ function safeMeta(meta: any): any {
297
298
  }
298
299
 
299
300
  function storeInDB(level: string, message: any, meta?: any, stacktrace?: string) {
300
- if (!conn || !dbInitialized) {
301
- // Database not ready yet, skip DB logging
301
+ if (!conn) {
302
+ // Database not configured, skip DB logging
302
303
  return;
303
304
  }
304
- try {
305
- const msg = safeToStringMessage(message);
306
- const metaObj = safeMeta(meta);
307
- const metaStr = jsonStringify(metaObj).slice(0, 2000);
308
- const stackStr = stacktrace || '';
309
- // Fire and forget; avoid awaiting in hot path. Catch errors to avoid unhandled rejection.
310
- conn.query(sql`INSERT INTO \`logs\` (level, message, meta, stacktrace, timestamp) VALUES (${level}, ${msg}, ${metaStr}, ${stackStr}, NOW())`).catch(e => {
305
+
306
+ // Wait for initialization to complete before writing
307
+ const doStore = async () => {
308
+ if (initPromise) {
309
+ await initPromise.catch(() => {}); // Wait but ignore errors
310
+ }
311
+
312
+ if (!dbInitialized) {
313
+ // Initialization failed, skip DB logging
314
+ return;
315
+ }
316
+
317
+ try {
318
+ const msg = safeToStringMessage(message);
319
+ const metaObj = safeMeta(meta);
320
+ const metaStr = jsonStringify(metaObj).slice(0, 2000);
321
+ const stackStr = stacktrace || '';
322
+
323
+ await conn!.query(sql`INSERT INTO \`logs\` (level, message, meta, stacktrace, timestamp) VALUES (${level}, ${msg}, ${metaStr}, ${stackStr}, NOW())`);
324
+ } catch (e: any) {
311
325
  // fallback console output only - but don't spam
312
326
  if (process.env.ENV_ID === 'dev') {
313
327
  console.error('Failed to persist log to DB', e);
314
328
  }
315
- });
316
- } catch (e) {
317
- console.error('Unexpected failure preparing log for DB', e);
318
- }
329
+ }
330
+ };
331
+
332
+ // Fire and forget
333
+ doStore().catch(e => {
334
+ if (process.env.ENV_ID === 'dev') {
335
+ console.error('Unexpected failure preparing log for DB', e);
336
+ }
337
+ });
319
338
  }
320
339
 
321
340
  export function createLogger(config: LoggerConfig = {}): { logger: Logger; fastifyLogger: FastifyLogger } {
@@ -327,11 +346,9 @@ export function createLogger(config: LoggerConfig = {}): { logger: Logger; fasti
327
346
 
328
347
  currentLogLevel = LOG_LEVELS[configuredLevel] ?? LOG_LEVELS.info;
329
348
 
330
- // Start initialization asynchronously but don't wait for it (only if MySQL config provided)
349
+ // Start initialization asynchronously (only if MySQL config provided)
331
350
  if (config.mysql) {
332
- initializeConnection(config).catch(err => {
333
- console.error('Error during log database initialization:', err);
334
- });
351
+ initPromise = initializeConnection(config);
335
352
  }
336
353
 
337
354
  const logger: Logger = {