@rawnodes/logger 2.0.1 → 2.2.0

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/index.mjs CHANGED
@@ -6,6 +6,7 @@ import { createStream } from 'rotating-file-stream';
6
6
  import { EventEmitter } from 'events';
7
7
  import { CloudWatchLogsClient, PutLogEventsCommand, CreateLogGroupCommand, CreateLogStreamCommand, DescribeLogStreamsCommand } from '@aws-sdk/client-cloudwatch-logs';
8
8
  import { z } from 'zod';
9
+ import { relative, basename } from 'path';
9
10
  import { randomUUID } from 'crypto';
10
11
 
11
12
  // src/state.ts
@@ -658,6 +659,9 @@ function createStreams(config, store) {
658
659
  const fileConfig = config.file;
659
660
  mkdir(fileConfig.dirname, { recursive: true }).catch(() => {
660
661
  });
662
+ const normalizeSize = (size) => {
663
+ return size.replace(/([kmg])$/i, (match) => match.toUpperCase());
664
+ };
661
665
  const rotatingStream = createStream(
662
666
  (time, index) => {
663
667
  const date = time instanceof Date ? time : /* @__PURE__ */ new Date();
@@ -667,7 +671,7 @@ function createStreams(config, store) {
667
671
  },
668
672
  {
669
673
  path: fileConfig.dirname,
670
- size: fileConfig.maxSize || "20M",
674
+ size: normalizeSize(fileConfig.maxSize || "20M"),
671
675
  interval: fileConfig.datePattern === "YYYY-MM-DD-HH" ? "1h" : "1d",
672
676
  compress: fileConfig.zippedArchive ? "gzip" : false,
673
677
  maxFiles: parseInt(fileConfig.maxFiles?.replace("d", "") || "14")
@@ -803,13 +807,20 @@ function createState(config, store) {
803
807
  // Disable pid and hostname
804
808
  };
805
809
  const pinoLogger = pino(options, streams);
810
+ let callerConfig;
811
+ if (config.caller === true) {
812
+ callerConfig = {};
813
+ } else if (config.caller && typeof config.caller === "object") {
814
+ callerConfig = config.caller;
815
+ }
806
816
  return {
807
817
  pino: pinoLogger,
808
818
  store: loggerStore,
809
819
  defaultLevel,
810
820
  levelOverrides,
811
821
  contextIndex,
812
- complexRules
822
+ complexRules,
823
+ callerConfig
813
824
  };
814
825
  }
815
826
  function rebuildIndexes(state) {
@@ -932,13 +943,18 @@ var LevelConfigSchema = z.union([
932
943
  LogLevelSchema,
933
944
  LevelConfigObjectSchema
934
945
  ]);
946
+ var CallerConfigSchema = z.object({
947
+ depth: z.number().int().nonnegative().optional(),
948
+ fullPath: z.boolean().optional()
949
+ });
935
950
  var LoggerConfigSchema = z.object({
936
951
  level: LevelConfigSchema,
937
952
  console: ConsoleConfigSchema,
938
953
  file: FileConfigSchema.optional(),
939
954
  discord: z.union([DiscordConfigSchema, z.array(DiscordConfigSchema)]).optional(),
940
955
  telegram: z.union([TelegramConfigSchema, z.array(TelegramConfigSchema)]).optional(),
941
- cloudwatch: z.union([CloudWatchConfigSchema, z.array(CloudWatchConfigSchema)]).optional()
956
+ cloudwatch: z.union([CloudWatchConfigSchema, z.array(CloudWatchConfigSchema)]).optional(),
957
+ caller: z.union([z.boolean(), CallerConfigSchema]).optional()
942
958
  });
943
959
  function validateConfig(config) {
944
960
  return LoggerConfigSchema.parse(config);
@@ -946,6 +962,66 @@ function validateConfig(config) {
946
962
  function safeValidateConfig(config) {
947
963
  return LoggerConfigSchema.safeParse(config);
948
964
  }
965
+ var BASE_STACK_OFFSET = 4;
966
+ var STACK_LINE_REGEX = /^\s*at\s+(?:(.+?)\s+\()?(.+):(\d+):(\d+)\)?$/;
967
+ function getCallerInfo(config, additionalOffset = 0) {
968
+ const depth = config.depth ?? 0;
969
+ const targetFrame = BASE_STACK_OFFSET + depth + additionalOffset;
970
+ const originalPrepare = Error.prepareStackTrace;
971
+ const originalLimit = Error.stackTraceLimit;
972
+ try {
973
+ Error.stackTraceLimit = targetFrame + 5;
974
+ const err = new Error();
975
+ const stack = err.stack;
976
+ if (!stack) {
977
+ return void 0;
978
+ }
979
+ const lines = stack.split("\n");
980
+ const targetLine = lines[targetFrame];
981
+ if (!targetLine) {
982
+ return void 0;
983
+ }
984
+ const match = targetLine.match(STACK_LINE_REGEX);
985
+ if (!match) {
986
+ return void 0;
987
+ }
988
+ const [, fnName, filePath, lineStr, colStr] = match;
989
+ const line = parseInt(lineStr, 10);
990
+ const column = parseInt(colStr, 10);
991
+ let file = filePath;
992
+ if (file.startsWith("file://")) {
993
+ file = file.slice(7);
994
+ }
995
+ if (!config.fullPath) {
996
+ try {
997
+ const relativePath = relative(process.cwd(), file);
998
+ if (relativePath.startsWith("..") && relativePath.split("/").filter((p) => p === "..").length > 2) {
999
+ file = basename(file);
1000
+ } else {
1001
+ file = relativePath;
1002
+ }
1003
+ } catch {
1004
+ file = basename(file);
1005
+ }
1006
+ }
1007
+ return {
1008
+ file,
1009
+ line,
1010
+ column: isNaN(column) ? void 0 : column,
1011
+ function: fnName && fnName !== "<anonymous>" ? fnName : void 0
1012
+ };
1013
+ } finally {
1014
+ Error.prepareStackTrace = originalPrepare;
1015
+ Error.stackTraceLimit = originalLimit;
1016
+ }
1017
+ }
1018
+ function formatCallerInfo(info) {
1019
+ const location = `${info.file}:${info.line}`;
1020
+ if (info.function) {
1021
+ return `${info.function} (${location})`;
1022
+ }
1023
+ return location;
1024
+ }
949
1025
 
950
1026
  // src/logger.ts
951
1027
  var Logger = class _Logger {
@@ -1048,13 +1124,19 @@ var Logger = class _Logger {
1048
1124
  this.log("silly", message, meta);
1049
1125
  }
1050
1126
  // Private
1051
- log(level, message, meta, error) {
1127
+ log(level, message, meta, error, callerOffset = 0) {
1052
1128
  const resolved = typeof meta === "function" ? meta() : meta;
1053
1129
  const logMeta = { context: this.context, ...resolved };
1054
1130
  const storeContext = this.state.store.getStore();
1055
1131
  if (storeContext) {
1056
1132
  Object.assign(logMeta, storeContext);
1057
1133
  }
1134
+ if (this.state.callerConfig) {
1135
+ const callerInfo = getCallerInfo(this.state.callerConfig, callerOffset);
1136
+ if (callerInfo) {
1137
+ logMeta.caller = formatCallerInfo(callerInfo);
1138
+ }
1139
+ }
1058
1140
  if (error instanceof Error) {
1059
1141
  logMeta.errorMessage = error.message;
1060
1142
  logMeta.stack = error.stack;
@@ -1297,6 +1379,6 @@ function formatLogfmt(data) {
1297
1379
  return Object.entries(flattened).filter(([, value]) => value !== void 0 && value !== null).map(([key, value]) => `${key}=${formatLogfmtValue(value)}`).join(" ");
1298
1380
  }
1299
1381
 
1300
- export { BaseHttpTransport, CloudWatchConfigSchema, CloudWatchTransport, ConsoleConfigSchema, DiscordConfigSchema, DiscordTransport, FileConfigSchema, HttpTransportBaseConfigSchema, LOG_LEVELS, LevelConfigObjectSchema, LevelConfigSchema, LevelRuleSchema, LogFormatSchema, LogLevelSchema, Logger, LoggerConfigSchema, LoggerStore, MessageBuffer, TelegramConfigSchema, TelegramTransport, assertLogLevel, createMasker, createSingletonLogger, extractRequestId, flattenObject, formatLogfmt, formatLogfmtValue, generateRequestId, getOrGenerateRequestId, isValidLogLevel, maskSecrets, matchesContext, measureAsync, measureSync, safeValidateConfig, validateConfig };
1382
+ export { BaseHttpTransport, CallerConfigSchema, CloudWatchConfigSchema, CloudWatchTransport, ConsoleConfigSchema, DiscordConfigSchema, DiscordTransport, FileConfigSchema, HttpTransportBaseConfigSchema, LOG_LEVELS, LevelConfigObjectSchema, LevelConfigSchema, LevelRuleSchema, LogFormatSchema, LogLevelSchema, Logger, LoggerConfigSchema, LoggerStore, MessageBuffer, TelegramConfigSchema, TelegramTransport, assertLogLevel, createMasker, createSingletonLogger, extractRequestId, flattenObject, formatCallerInfo, formatLogfmt, formatLogfmtValue, generateRequestId, getCallerInfo, getOrGenerateRequestId, isValidLogLevel, maskSecrets, matchesContext, measureAsync, measureSync, safeValidateConfig, validateConfig };
1301
1383
  //# sourceMappingURL=index.mjs.map
1302
1384
  //# sourceMappingURL=index.mjs.map