logixia 2.0.8 → 2.0.10

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/README.md CHANGED
@@ -35,7 +35,7 @@ Most Node loggers give you a fast `info()` and leave the rest to you. logixia ke
35
35
  - **Transports for real destinations.** Console, rotating files, PostgreSQL, MySQL, MongoDB, SQLite, CloudWatch, Google Cloud Logging, Azure Monitor, Datadog, OTLP, Slack, Discord, and a worker-thread wrapper. Several can run on one log call.
36
36
  - **OpenTelemetry-native.** Read the active span for trace/log correlation, or export logs as OTLP/HTTP records. The OTLP transport builds the JSON itself, so no `@opentelemetry/*` SDK is required to emit logs.
37
37
  - **Runs outside Node too.** `logixia/browser` has no Node built-ins and is written for browsers and edge runtimes such as Cloudflare Workers.
38
- - **Small footprint.** Three runtime dependencies (`commander`, `fast-json-stringify`, `picocolors`), no install scripts, ESM and CommonJS builds with types.
38
+ - **Small footprint.** Two runtime dependencies (`commander`, `picocolors`), no install scripts, ESM and CommonJS builds with types.
39
39
 
40
40
  Log calls are `async` and transport failures are caught internally, so a full disk or a flaky database does not crash your process.
41
41
 
@@ -6,8 +6,6 @@ const require_internal_log = require("./internal-log-DwqTjhpb.js");
6
6
  const require_coerce_utils = require("./coerce.utils-C1C5sIX0.js");
7
7
  const require_safe_stringify = require("./safe-stringify-CN7icp8S.js");
8
8
  const require_otel = require("./otel-ChnVYRLA.js");
9
- let fast_json_stringify = require("fast-json-stringify");
10
- fast_json_stringify = require_secret_config.__toESM(fast_json_stringify);
11
9
  let node_os = require("node:os");
12
10
  // src/types/index.ts
13
11
  const LogLevel = {
@@ -195,6 +193,16 @@ const EXTRA_FIELDS = [
195
193
  "port",
196
194
  "type"
197
195
  ];
196
+ const SKIPPED_FIELDS = /* @__PURE__ */ new Set([
197
+ "name",
198
+ "message",
199
+ "stack",
200
+ "cause",
201
+ "errors",
202
+ ...EXTRA_FIELDS
203
+ ]);
204
+ const NO_OPTIONS = Object.freeze({});
205
+ const NO_FIELDS = [];
198
206
  /**
199
207
  * Serialize an Error into a plain JSON-safe object, including:
200
208
  * - `name`, `message`, `stack`
@@ -203,8 +211,8 @@ const EXTRA_FIELDS = [
203
211
  * - standard Node.js error fields (`code`, `statusCode`, `errno`, …)
204
212
  * - any other enumerable own properties
205
213
  */
206
- function serializeError(error, options = {}) {
207
- const { includeStack = true, maxDepth = 5, excludeFields = [] } = options;
214
+ function serializeError(error, options = NO_OPTIONS) {
215
+ const { includeStack = true, maxDepth = 5, excludeFields = NO_FIELDS } = options;
208
216
  return _serializeError(error, includeStack, maxDepth, excludeFields, 0, /* @__PURE__ */ new WeakSet());
209
217
  }
210
218
  function _serializeError(error, includeStack, maxDepth, excludeFields, depth, seen) {
@@ -232,16 +240,8 @@ function _serializeError(error, includeStack, maxDepth, excludeFields, depth, se
232
240
  const aggregateError = error;
233
241
  if (Array.isArray(aggregateError.errors)) serialized.errors = aggregateError.errors.map((e) => e instanceof Error ? _serializeError(e, includeStack, maxDepth, excludeFields, depth + 1, seen) : serializeValue(e, maxDepth - depth - 1, seen));
234
242
  const errorRecord = error;
235
- for (const field of EXTRA_FIELDS) if (!excludeFields.includes(field) && field in error && errorRecord[field] !== void 0) serialized[field] = errorRecord[field];
236
- const skip = /* @__PURE__ */ new Set([
237
- "name",
238
- "message",
239
- "stack",
240
- "cause",
241
- "errors",
242
- ...EXTRA_FIELDS,
243
- ...excludeFields
244
- ]);
243
+ for (const field of EXTRA_FIELDS) if (!excludeFields.includes(field) && errorRecord[field] !== void 0) serialized[field] = errorRecord[field];
244
+ const skip = excludeFields.length === 0 ? SKIPPED_FIELDS : /* @__PURE__ */ new Set([...SKIPPED_FIELDS, ...excludeFields]);
245
245
  for (const key of Object.getOwnPropertyNames(error)) {
246
246
  if (skip.has(key)) continue;
247
247
  try {
@@ -1034,23 +1034,6 @@ function warnOnReservedLevelNames(levels) {
1034
1034
  * - Feature 4: Cause-chain error serialization (handled in error.utils)
1035
1035
  * - Feature 5: Adaptive log level based on NODE_ENV / CI detection
1036
1036
  */
1037
- const _fastStringifyEntry = (0, fast_json_stringify.default)({
1038
- type: "object",
1039
- properties: {
1040
- timestamp: { type: "string" },
1041
- level: { type: "string" },
1042
- appName: { type: "string" },
1043
- environment: { type: "string" },
1044
- message: { type: "string" },
1045
- context: { type: "string" },
1046
- traceId: { type: "string" },
1047
- payload: {
1048
- type: "object",
1049
- additionalProperties: true
1050
- }
1051
- },
1052
- additionalProperties: true
1053
- });
1054
1037
  let _tsCacheMs = 0;
1055
1038
  let _tsCacheStr = "";
1056
1039
  function nowIso() {
@@ -1061,6 +1044,43 @@ function nowIso() {
1061
1044
  }
1062
1045
  return _tsCacheStr;
1063
1046
  }
1047
+ const RESOLVED = Promise.resolve();
1048
+ const JSON_STRING_FIELDS = [
1049
+ "timestamp",
1050
+ "level",
1051
+ "appName",
1052
+ "environment",
1053
+ "message",
1054
+ "context",
1055
+ "traceId"
1056
+ ];
1057
+ function toJsonString(value) {
1058
+ if (value === null) return "";
1059
+ if (value instanceof Date) return value.toISOString();
1060
+ if (value instanceof RegExp) return value.source;
1061
+ return String(value);
1062
+ }
1063
+ function toJsonEntry(entry) {
1064
+ const record = entry;
1065
+ let copy;
1066
+ for (const field of JSON_STRING_FIELDS) {
1067
+ const value = record[field];
1068
+ if (value !== void 0 && typeof value !== "string") {
1069
+ copy ??= { ...record };
1070
+ copy[field] = toJsonString(value);
1071
+ }
1072
+ }
1073
+ const payload = entry.payload;
1074
+ if (payload !== void 0 && (payload === null || typeof payload !== "object" || Array.isArray(payload))) {
1075
+ copy ??= { ...record };
1076
+ copy["payload"] = Object.assign({}, payload);
1077
+ }
1078
+ return copy ?? entry;
1079
+ }
1080
+ function toContextLabel(context) {
1081
+ if (context === void 0 || context === null) return "";
1082
+ return typeof context === "string" ? context : require_coerce_utils.safeToString(context);
1083
+ }
1064
1084
  function namespacePatternToRegex(pattern) {
1065
1085
  const escaped = pattern.split(".").map((s) => s === "*" ? "[^.]+" : s.replace(/[$()*+.?[\\\]^{|}]/g, "\\$&")).join("\\.");
1066
1086
  return new RegExp(`^${escaped}$`);
@@ -1142,6 +1162,11 @@ var LogixiaLogger = class LogixiaLogger {
1142
1162
  this._hasContextData = false;
1143
1163
  this._formattedLevels = /* @__PURE__ */ new Map();
1144
1164
  this._formattedAppName = "";
1165
+ this._jsonHeads = /* @__PURE__ */ new Map();
1166
+ this._jsonHeadsApp = "";
1167
+ this._jsonHeadsEnv = "";
1168
+ this._jsonContextKey = void 0;
1169
+ this._jsonContext = "";
1145
1170
  this._hasRedact = false;
1146
1171
  this._nsSeenVersion = 0;
1147
1172
  this._parent = parent;
@@ -1199,7 +1224,7 @@ var LogixiaLogger = class LogixiaLogger {
1199
1224
  payload: "[payload]",
1200
1225
  timeTaken: "[time_taken_MS]"
1201
1226
  };
1202
- this.context = context ?? "";
1227
+ this.context = toContextLabel(context);
1203
1228
  require_secret_config.protectSecrets(this, ["config"]);
1204
1229
  if (parent) {
1205
1230
  this.transportManager = parent.transportManager;
@@ -1242,9 +1267,7 @@ var LogixiaLogger = class LogixiaLogger {
1242
1267
  var _this$config$levelOpt3, _this$config$levelOpt4;
1243
1268
  warnOnReservedLevelNames((_this$config$levelOpt3 = this.config.levelOptions) === null || _this$config$levelOpt3 === void 0 ? void 0 : _this$config$levelOpt3.levels);
1244
1269
  if ((_this$config$levelOpt4 = this.config.levelOptions) === null || _this$config$levelOpt4 === void 0 ? void 0 : _this$config$levelOpt4.levels) {
1245
- for (const levelName of Object.keys(this.config.levelOptions.levels)) if (!this[levelName.toLowerCase()]) this[levelName.toLowerCase()] = async (message, data) => {
1246
- await this.logLevel(levelName.toLowerCase(), message, data);
1247
- };
1270
+ for (const levelName of Object.keys(this.config.levelOptions.levels)) if (!this[levelName.toLowerCase()]) this[levelName.toLowerCase()] = (message, data) => this.logLevel(levelName.toLowerCase(), message, data);
1248
1271
  }
1249
1272
  }
1250
1273
  /**
@@ -1346,40 +1369,53 @@ var LogixiaLogger = class LogixiaLogger {
1346
1369
  * (name, message, stack) under `data.error`; a string is logged as-is.
1347
1370
  * `data` is merged into the entry payload.
1348
1371
  */
1349
- async error(messageOrError, data) {
1350
- if (isError(messageOrError)) await this.log("error", messageOrError.message, {
1351
- ...data,
1352
- error: serializeError(messageOrError)
1353
- });
1354
- else await this.log("error", messageOrError, data);
1372
+ error(messageOrError, data) {
1373
+ try {
1374
+ return isError(messageOrError) ? this._run("error", messageOrError.message, {
1375
+ ...data,
1376
+ error: serializeError(messageOrError)
1377
+ }) : this._run("error", messageOrError, data);
1378
+ } catch (error) {
1379
+ return Promise.reject(error);
1380
+ }
1355
1381
  }
1356
1382
  /** Log `message` at `warn` level; `data` is merged into the entry payload. */
1357
- async warn(message, data) {
1358
- await this.log("warn", message, data);
1383
+ warn(message, data) {
1384
+ return this._run("warn", message, data);
1359
1385
  }
1360
1386
  /** Log `message` at `info` level; `data` is merged into the entry payload. */
1361
- async info(message, data) {
1362
- await this.log("info", message, data);
1387
+ info(message, data) {
1388
+ return this._run("info", message, data);
1363
1389
  }
1364
1390
  /** Log `message` at `debug` level; `data` is merged into the entry payload. */
1365
- async debug(message, data) {
1366
- await this.log("debug", message, data);
1391
+ debug(message, data) {
1392
+ return this._run("debug", message, data);
1367
1393
  }
1368
1394
  /** Log `message` at `trace` level; `data` is merged into the entry payload. */
1369
- async trace(message, data) {
1370
- await this.log("trace", message, data);
1395
+ trace(message, data) {
1396
+ return this._run("trace", message, data);
1371
1397
  }
1372
1398
  /** Log `message` at `verbose` level; `data` is merged into the entry payload. */
1373
- async verbose(message, data) {
1374
- await this.log("verbose", message, data);
1399
+ verbose(message, data) {
1400
+ return this._run("verbose", message, data);
1375
1401
  }
1376
1402
  /**
1377
1403
  * Log at an arbitrary level name, including custom levels. Levels below the
1378
1404
  * active threshold are dropped, as are level names that are not registered
1379
1405
  * in `levelOptions.levels` (and are not built-in).
1380
1406
  */
1381
- async logLevel(level, message, data) {
1382
- await this.log(level, message, data);
1407
+ logLevel(level, message, data) {
1408
+ return this._run(level, message, data);
1409
+ }
1410
+ _run(level, message, data) {
1411
+ try {
1412
+ return this._settle(this.log(level, message, data));
1413
+ } catch (error) {
1414
+ return Promise.reject(error);
1415
+ }
1416
+ }
1417
+ _settle(out) {
1418
+ return out ?? RESOLVED;
1383
1419
  }
1384
1420
  /** Start a named timer; finish it with {@link timeEnd}. Reusing a label restarts it. */
1385
1421
  time(label) {
@@ -1685,13 +1721,15 @@ var LogixiaLogger = class LogixiaLogger {
1685
1721
  await this._pluginRegistry.runOnShutdown();
1686
1722
  deregisterFromShutdown(this);
1687
1723
  }
1688
- async log(level, message, rawData) {
1689
- if (this.config.silent) return;
1724
+ /** Returns a Promise only when a plugin or a transport is asynchronous. */
1725
+ log(level, message, rawData) {
1726
+ const config = this.config;
1727
+ if (config.silent) return;
1690
1728
  if (!this.shouldLog(level)) return;
1691
1729
  const data = rawData instanceof Error ? { error: serializeError(rawData) } : rawData;
1692
1730
  const alsContext = require_async_context.LogixiaContext.get();
1693
1731
  let activeTraceId;
1694
- if (this.config.traceId) {
1732
+ if (config.traceId) {
1695
1733
  const ctxTraceId = alsContext === null || alsContext === void 0 ? void 0 : alsContext.traceId;
1696
1734
  activeTraceId = require_request_trace.TraceContext.instance.getCurrentTraceId() ?? (typeof ctxTraceId === "string" ? ctxTraceId : void 0);
1697
1735
  }
@@ -1699,7 +1737,7 @@ var LogixiaLogger = class LogixiaLogger {
1699
1737
  const hasAls = alsContext !== void 0 && Object.keys(alsContext).length > 0;
1700
1738
  const otelFields = require_otel._isOtelBridgeEnabled() ? require_otel._getOtelPayloadIfEnabled() : void 0;
1701
1739
  const hasOtel = otelFields !== void 0 && Object.keys(otelFields).length > 0;
1702
- const traceId = this.config.traceId ? activeTraceId ?? this.fallbackTraceId : void 0;
1740
+ const traceId = config.traceId ? activeTraceId ?? this.fallbackTraceId : void 0;
1703
1741
  let mergedData;
1704
1742
  if (hasAls) {
1705
1743
  const als = { ...alsContext };
@@ -1726,7 +1764,7 @@ var LogixiaLogger = class LogixiaLogger {
1726
1764
  let payload;
1727
1765
  if (rawPayload !== void 0 && rawPayload !== null) {
1728
1766
  if (this._hasRedact) try {
1729
- payload = applyRedaction(rawPayload, this.config.redact) ?? rawPayload;
1767
+ payload = applyRedaction(rawPayload, config.redact) ?? rawPayload;
1730
1768
  } catch (error) {
1731
1769
  require_internal_log.internalError("Redaction failed", error);
1732
1770
  payload = { redaction: REDACTION_FAILED };
@@ -1735,7 +1773,7 @@ var LogixiaLogger = class LogixiaLogger {
1735
1773
  }
1736
1774
  let safeMessage = message;
1737
1775
  if (this._hasRedact) try {
1738
- safeMessage = applyRedactionToString(message, this.config.redact);
1776
+ safeMessage = applyRedactionToString(message, config.redact);
1739
1777
  } catch (error) {
1740
1778
  require_internal_log.internalError("Redaction failed", error);
1741
1779
  safeMessage = REDACTION_FAILED;
@@ -1743,20 +1781,20 @@ var LogixiaLogger = class LogixiaLogger {
1743
1781
  const entry = {
1744
1782
  timestamp: nowIso(),
1745
1783
  level,
1746
- appName: this.config.appName ?? "App",
1747
- environment: this.config.environment ?? "development",
1784
+ appName: config.appName ?? "App",
1785
+ environment: config.environment ?? "development",
1748
1786
  message: safeMessage
1749
1787
  };
1750
1788
  if (this.context) entry.context = this.context;
1751
- if (payload !== void 0) entry.payload = payload;
1752
1789
  if (traceId !== void 0) entry.traceId = traceId;
1753
- let finalEntry = entry;
1754
- if (this._pluginRegistry.size > 0) {
1755
- finalEntry = await this._pluginRegistry.runOnLog(entry);
1756
- if (finalEntry === null) return;
1757
- }
1758
- const out = this.output(finalEntry, level);
1759
- if (out !== void 0) await out;
1790
+ if (payload !== void 0) entry.payload = payload;
1791
+ if (this._pluginRegistry.size > 0) return this._logThroughPlugins(entry, level);
1792
+ return this.output(entry, level);
1793
+ }
1794
+ async _logThroughPlugins(entry, level) {
1795
+ const finalEntry = await this._pluginRegistry.runOnLog(entry);
1796
+ if (finalEntry === null) return;
1797
+ await this.output(finalEntry, level);
1760
1798
  }
1761
1799
  /**
1762
1800
  * Hot-path level check: a single Map lookup + integer compare.
@@ -1798,19 +1836,27 @@ var LogixiaLogger = class LogixiaLogger {
1798
1836
  return this.getLevel();
1799
1837
  }
1800
1838
  formatLog(entry) {
1801
- var _this$config$format2, _this$config$format3, _this$config$format4;
1802
- if ((_this$config$format2 = this.config.format) === null || _this$config$format2 === void 0 ? void 0 : _this$config$format2.json) try {
1803
- return _fastStringifyEntry(entry);
1804
- } catch {
1805
- return require_safe_stringify.stringifyForLog(entry);
1839
+ const format = this.config.format;
1840
+ if (format === null || format === void 0 ? void 0 : format.json) {
1841
+ if (this._pluginRegistry.size === 0) try {
1842
+ const line = this._buildJsonLine(entry);
1843
+ if (line !== void 0) return line;
1844
+ } catch {}
1845
+ let jsonEntry = entry;
1846
+ try {
1847
+ jsonEntry = toJsonEntry(entry);
1848
+ return JSON.stringify(jsonEntry);
1849
+ } catch {
1850
+ return require_safe_stringify.stringifyForLog(jsonEntry);
1851
+ }
1806
1852
  }
1807
1853
  let formatted = "";
1808
- const doColorize = ((_this$config$format3 = this.config.format) === null || _this$config$format3 === void 0 ? void 0 : _this$config$format3.colorize) ?? true;
1854
+ const doColorize = (format === null || format === void 0 ? void 0 : format.colorize) ?? true;
1809
1855
  const gray = doColorize ? this._colorMap.get("gray") : "";
1810
1856
  const cyan = doColorize ? this._colorMap.get("cyan") : "";
1811
1857
  const yellow = doColorize ? this._colorMap.get("yellow") : "";
1812
1858
  const reset = doColorize ? this._colorMap.get("reset") : "";
1813
- if (((_this$config$format4 = this.config.format) === null || _this$config$format4 === void 0 ? void 0 : _this$config$format4.timestamp) !== false && this._fieldCache.get("timestamp") !== false) formatted += `${gray}[${entry.timestamp}]${reset} `;
1859
+ if ((format === null || format === void 0 ? void 0 : format.timestamp) !== false && this._fieldCache.get("timestamp") !== false) formatted += `${gray}[${entry.timestamp}]${reset} `;
1814
1860
  if (this._fieldCache.get("level") !== false) formatted += this._formattedLevels.get(entry.level) ?? `[${entry.level.toUpperCase()}] `;
1815
1861
  formatted += this._formattedAppName;
1816
1862
  if (entry.traceId && this._fieldCache.get("traceId") !== false) formatted += `${cyan}[${require_otel.stripControlChars(String(entry.traceId))}]${reset} `;
@@ -1819,9 +1865,46 @@ var LogixiaLogger = class LogixiaLogger {
1819
1865
  if (entry.payload !== void 0 && this._fieldCache.get("payload") !== false) formatted += ` ${require_safe_stringify.stringifyForLog(entry.payload)}`;
1820
1866
  return formatted;
1821
1867
  }
1868
+ /**
1869
+ * The same bytes JSON.stringify(entry) gives for an entry log() built, without
1870
+ * walking the fixed fields. Returns undefined when a field has an unexpected type.
1871
+ */
1872
+ _buildJsonLine(entry) {
1873
+ const { timestamp, level, appName, environment, message, context, traceId, payload } = entry;
1874
+ if (typeof timestamp !== "string" || typeof message !== "string" || typeof appName !== "string" || typeof environment !== "string") return;
1875
+ if (appName !== this._jsonHeadsApp || environment !== this._jsonHeadsEnv) {
1876
+ this._jsonHeads.clear();
1877
+ this._jsonHeadsApp = appName;
1878
+ this._jsonHeadsEnv = environment;
1879
+ }
1880
+ let head = this._jsonHeads.get(level);
1881
+ if (head === void 0) {
1882
+ if (typeof level !== "string") return void 0;
1883
+ head = `,"level":${JSON.stringify(level)},"appName":${JSON.stringify(appName)},"environment":${JSON.stringify(environment)},"message":`;
1884
+ this._jsonHeads.set(level, head);
1885
+ }
1886
+ let line = `{"timestamp":"${timestamp}"${head}${JSON.stringify(message)}`;
1887
+ if (context !== void 0) {
1888
+ if (typeof context !== "string") return void 0;
1889
+ if (context !== this._jsonContextKey) {
1890
+ this._jsonContextKey = context;
1891
+ this._jsonContext = `,"context":${JSON.stringify(context)}`;
1892
+ }
1893
+ line += this._jsonContext;
1894
+ }
1895
+ if (traceId !== void 0) {
1896
+ if (typeof traceId !== "string") return void 0;
1897
+ line += `,"traceId":${JSON.stringify(traceId)}`;
1898
+ }
1899
+ if (payload !== void 0) {
1900
+ if (payload === null || typeof payload !== "object" || Array.isArray(payload) || typeof payload.toJSON === "function") return;
1901
+ line += `,"payload":${JSON.stringify(payload)}`;
1902
+ }
1903
+ return `${line}}`;
1904
+ }
1822
1905
  colorize(text, color) {
1823
- var _this$config$format5;
1824
- if (!((_this$config$format5 = this.config.format) === null || _this$config$format5 === void 0 ? void 0 : _this$config$format5.colorize)) return text;
1906
+ var _this$config$format2;
1907
+ if (!((_this$config$format2 = this.config.format) === null || _this$config$format2 === void 0 ? void 0 : _this$config$format2.colorize)) return text;
1825
1908
  return `${this._colorMap.get(color.toLowerCase()) ?? this._colorMap.get("white")}${text}${this._colorMap.get("reset")}`;
1826
1909
  }
1827
1910
  /**
@@ -1873,9 +1956,7 @@ function createLogger(config, context) {
1873
1956
  const logger = new LogixiaLogger(config, context);
1874
1957
  const mutableLogger = logger;
1875
1958
  if ((_config$levelOptions3 = config.levelOptions) === null || _config$levelOptions3 === void 0 ? void 0 : _config$levelOptions3.levels) {
1876
- for (const levelName of Object.keys(config.levelOptions.levels)) if (!mutableLogger[levelName]) mutableLogger[levelName] = async (message, data) => {
1877
- await logger.logLevel(levelName, message, data);
1878
- };
1959
+ for (const levelName of Object.keys(config.levelOptions.levels)) if (!mutableLogger[levelName]) mutableLogger[levelName] = (message, data) => logger.logLevel(levelName, message, data);
1879
1960
  }
1880
1961
  return logger;
1881
1962
  }
@@ -2253,4 +2334,4 @@ Object.defineProperty(exports, "usePlugin", {
2253
2334
  }
2254
2335
  });
2255
2336
 
2256
- //# sourceMappingURL=builder-BTzvPGHN.js.map
2337
+ //# sourceMappingURL=builder-BLIStsCK.js.map