{"_id":"@al-masry/audit-core","_rev":"2-93dc3ca5047b9c35fc094328e1d04dd4","name":"@al-masry/audit-core","dist-tags":{"latest":"1.0.1"},"versions":{"1.0.0":{"name":"@al-masry/audit-core","version":"1.0.0","keywords":["logging","enterprise"],"author":{"name":"Abdel Moumen Abdel Raouf"},"license":"MIT","_id":"@al-masry/audit-core@1.0.0","maintainers":[{"name":"al-masry","email":"abdo.me.inc@gmail.com"}],"homepage":"https://github.com/abdel-moumen-abdel-raouf/es6-audit-core#readme","bugs":{"url":"https://github.com/abdel-moumen-abdel-raouf/es6-audit-core/issues"},"dist":{"shasum":"42bad91b11609ca9fc95e363d83a0466e26adcf0","tarball":"https://registry.npmjs.org/@al-masry/audit-core/-/audit-core-1.0.0.tgz","fileCount":51,"integrity":"sha512-5nzA9opb03yWf5FXYwsFqA6b1T+uEIsuhcHDyWJt9fl00hKYaL11UKOO4OGQ4vaZycLcLedyrGVvvc4wbBDwug==","signatures":[{"sig":"MEUCIDLsEgkPwkyFQqWZKhYYNEWhPmxwMQhPxogvXqGv7bpWAiEAiWwlWekrymSsuGqgRr6y5v9VPwG12QurEu7KhU85EpQ=","keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"}],"unpackedSize":386807},"main":"./index.js","type":"module","engines":{"node":">=18.0.0"},"exports":{".":{"import":"./index.js","default":"./index.js"}},"gitHead":"b5ae601eb8429744e73ffde2145ab709598149aa","scripts":{"lint":"eslint index.js core/**/*.js config/**/*.js context/**/*.js error-handling/**/*.js rate-limiting/**/*.js sanitizer/**/*.js sync/**/*.js transports/**/*.js utils/**/*.js tests/**/*.js scripts/**/*.js eslint.config.js","test":"node ./tests/run-all-tests.js","format":"prettier --write .","lint:ci":"npm run lint --silent -- --max-warnings=0","lint:md":"npx markdownlint-cli2 \"**/*.md\" \"!coverage/**\" \"!node_modules/**\" --config .markdownlint.json","coverage":"c8 --reporter=lcov --reporter=text-summary --reports-dir=coverage node ./tests/run-all-tests.js","test:core":"node ./tests/core.test.js","test:basic":"node ./tests/basic.test.js","lint:md:fix":"npx markdownlint-cli2-fix \"**/*.md\" \"!coverage/**\" \"!node_modules/**\" --config .markdownlint.json","prepublishOnly":"npm run lint:ci && npm test"},"_npmUser":{"name":"al-masry","email":"abdo.me.inc@gmail.com"},"repository":{"url":"git+https://github.com/abdel-moumen-abdel-raouf/es6-audit-core.git","type":"git"},"_npmVersion":"10.9.3","description":"Enterprise-grade audit and logging core - ES6 modules","directories":{},"sideEffects":false,"_nodeVersion":"22.20.0","_hasShrinkwrap":false,"devDependencies":{"c8":"^10.1.2","eslint":"^9.12.0","prettier":"^3.3.3"},"_npmOperationalInternal":{"tmp":"tmp/audit-core_1.0.0_1761057730096_0.22526736129119973","host":"s3://npm-registry-packages-npm-production"}},"1.0.1":{"name":"@al-masry/audit-core","version":"1.0.1","description":"Enterprise-grade audit and logging core - ES6 modules","type":"module","main":"./index.js","exports":{".":{"import":"./index.js","default":"./index.js"}},"keywords":["logging","enterprise"],"license":"MIT","repository":{"type":"git","url":"git+https://github.com/abdel-moumen-abdel-raouf/es6-audit-core.git"},"bugs":{"url":"https://github.com/abdel-moumen-abdel-raouf/es6-audit-core/issues"},"homepage":"https://github.com/abdel-moumen-abdel-raouf/es6-audit-core#readme","author":{"name":"Abdel Moumen Abdel Raouf"},"sideEffects":false,"scripts":{"test":"node ./tests/run-all-tests.js","test:basic":"node ./tests/basic.test.js","test:core":"node ./tests/core.test.js","lint":"eslint index.js core/**/*.js config/**/*.js context/**/*.js error-handling/**/*.js rate-limiting/**/*.js sanitizer/**/*.js sync/**/*.js transports/**/*.js utils/**/*.js tests/**/*.js scripts/**/*.js eslint.config.js","lint:ci":"npm run lint --silent -- --max-warnings=0","lint:md":"npx markdownlint-cli2 \"**/*.md\" \"!coverage/**\" \"!node_modules/**\" --config .markdownlint.json","lint:md:fix":"npx markdownlint-cli2-fix \"**/*.md\" \"!coverage/**\" \"!node_modules/**\" --config .markdownlint.json","format":"prettier --write .","coverage":"c8 --reporter=lcov --reporter=text-summary --reports-dir=coverage node ./tests/run-all-tests.js","prepublishOnly":"npm run lint:ci && npm test"},"engines":{"node":">=18.0.0"},"devDependencies":{"eslint":"^9.12.0","prettier":"^3.3.3","c8":"^10.1.2"},"_id":"@al-masry/audit-core@1.0.1","gitHead":"08d8dd1d32cb8d1919241694e9a34d1c4f7898bb","_nodeVersion":"22.20.0","_npmVersion":"10.9.3","dist":{"integrity":"sha512-FQ7dM/YTp+UYbwWh1c4JDtJu+dGn9C1oZ/Bf3QU+vrGYP8tXjb5p9D7+A2ggwHcueLd4aBkblTs764BnpQp6qA==","shasum":"e05b449369e068590a62d4c7fc453d7f7b8a71b6","tarball":"https://registry.npmjs.org/@al-masry/audit-core/-/audit-core-1.0.1.tgz","fileCount":51,"unpackedSize":390142,"signatures":[{"keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U","sig":"MEUCIQCDezcTIv+wuBAYfXvzMON/p8z/2eGG3G2gZ1RorXGN/wIgSUfcyR9Ybf+1icmxFgwI4q7i4t/wEm0yqm0nqa9gsBY="}]},"_npmUser":{"name":"al-masry","email":"abdo.me.inc@gmail.com"},"directories":{},"maintainers":[{"name":"al-masry","email":"abdo.me.inc@gmail.com"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages-npm-production","tmp":"tmp/audit-core_1.0.1_1761077984326_0.4099652599665753"},"_hasShrinkwrap":false}},"time":{"created":"2025-10-21T14:42:10.027Z","modified":"2025-10-21T20:19:44.722Z","1.0.0":"2025-10-21T14:42:10.299Z","1.0.1":"2025-10-21T20:19:44.520Z"},"bugs":{"url":"https://github.com/abdel-moumen-abdel-raouf/es6-audit-core/issues"},"author":{"name":"Abdel Moumen Abdel Raouf"},"license":"MIT","homepage":"https://github.com/abdel-moumen-abdel-raouf/es6-audit-core#readme","keywords":["logging","enterprise"],"repository":{"type":"git","url":"git+https://github.com/abdel-moumen-abdel-raouf/es6-audit-core.git"},"description":"Enterprise-grade audit and logging core - ES6 modules","maintainers":[{"name":"al-masry","email":"abdo.me.inc@gmail.com"}],"readme":"# AuditCore — Enterprise-Grade ES6 Logging & Audit System\r\n\r\n![Build](https://github.com/abdel-moumen-abdel-raouf/es6-audit-core/actions/workflows/ci.yml/badge.svg)\r\n![npm](https://img.shields.io/npm/v/@al-masry/audit-core)\r\n![Coverage](https://img.shields.io/badge/coverage-c8-green)\r\n![Node](https://img.shields.io/badge/node-%3E%3D18.0.0-brightgreen)\r\n\r\nA high-performance, security-conscious logging and audit core for modern Node.js applications. Built as native ES Modules with production features including adaptive buffering with backpressure, rate limiting, sanitization/redaction, resilient transport chains, dynamic configuration, health checks, metrics, and distributed tracing.\r\n\r\nPublished version: 1.0.1 (scoped as @al-masry/audit-core)\r\n\r\n## Overview / Introduction\r\n\r\nAuditCore provides a modular, enterprise-ready logging and audit foundation designed for services that need reliable, scalable, and secure log delivery. It supports multiple transports (console, file, HTTP, custom), protects sensitive data through robust sanitization, and maintains performance via adaptive buffering and rate limiting. It also includes health checks, metrics, and tracing utilities for operational visibility.\r\n\r\nTarget users:\r\n\r\n- Backend services and microservices with high-volume logging needs\r\n- Platforms that require consistent sanitization and governance for logs\r\n- Teams operating in production with SLOs who need resilience and observability\r\n\r\n## Key Features\r\n\r\n- Adaptive buffering and backpressure handling to survive high burst rates\r\n- Token-bucket rate limiting per module to prevent log floods\r\n- Sensitive data sanitization (keys and pattern-based, including encoded contents)\r\n- Multiple transports: console, rotating file (Node only), advanced HTTP with retry/backoff and dead-letter queue\r\n- Resilient transport chains with circuit breakers and fallbacks\r\n- Dynamic configuration (runtime updates, rollback, audit log)\r\n- Per-module and pattern-based log level configuration\r\n- Context management: correlation IDs and request context propagation\r\n- Transform/context-aware logging for object hierarchies and state tracking\r\n- Health checks (liveness/readiness/startup) with statistics\r\n- Metrics collection (counter/gauge/histogram) with Prometheus export format\r\n- Synchronization utilities (Mutex) for safe concurrency\r\n- Worker thread integration scaffolding (pool and integrations)\r\n- ES Modules-first; Node.js >= 18\r\n\r\n## Architecture & Design Overview\r\n\r\n- Technologies:\r\n  - Node.js (>= 18), native ES Modules (`\"type\": \"module\"`)\r\n  - Uses Node core modules (fs, path, crypto, async_hooks) where needed\r\n  - No external runtime dependencies in the core\r\n\r\n- Design:\r\n  - Modular packages by domain:\r\n    - Core logging (`core/`), configuration (`config/`), context (`context/`), transports (`transports/`)\r\n    - Rate limiting, sanitization, resilience, tracing, health, metrics, sync (mutex), workers, utilities\r\n  - Strategy pattern for transports (base class and implementations)\r\n  - Token Bucket algorithm for rate limiting\r\n  - Adaptive buffer with high/low watermarks, memory usage estimation, and drain callbacks\r\n  - Circuit Breaker and transport chaining for resilience (avoid cascading failures)\r\n  - AsyncLocalStorage for context/correlation in `LogContext`\r\n  - Security-by-default sanitization/redaction before persistence/egress\r\n\r\n- Data flow (CoreLogger):\r\n  - App calls logger.debug/info/warn/error or log(LogLevel, message, context)\r\n  - RateLimiter checks token bucket per module; rejects when exceeding budget\r\n  - LogEntry created and sanitized\r\n  - Entry is pushed into AdaptiveLogBuffer\r\n  - On flush, batched entries are sent to configured transports (requires a batch-capable transport interface; see “Transports” note below)\r\n  - Statistics updated; backpressure and drain events managed\r\n\r\n## Folder Structure & File Summary\r\n\r\n- `index.js` — Public ES Module exports (preferred entry)\r\n- `jsconfig.json` — Editor/TS tooling options\r\n\r\nKey directories:\r\n\r\n- `core/`\r\n  - `core-logger.js` — Main production logger (buffer + rate limiter + transform/context tracking)\r\n  - `core-logger-config.js` — Validated config for transports and per-module levels (via `ModuleConfig`)\r\n  - `adaptive-logger.js` — Adaptive logger utilities (memory monitor, flush strategy, batcher)\r\n  - `resilient-logger.js` — Circuit breaker transport chain, local fallback queue\r\n  - `structured-logging-schema.js` — Structured logging schema helpers\r\n\r\n- `config/`\r\n  - `logger-config.js` — Immutable basic logger config validation\r\n  - `module-config.js` — Module/pattern-based levels, listeners, JSON import/export\r\n  - `dynamic-config.js` — DynamicConfigurationManager (safe runtime updates, rollback, audit)\r\n  - `dynamic-config-integration.js` — Integration facade for dynamic config operations\r\n  - `log-presets.js` — Preset management (development/production/testing/debugging)\r\n  - `color-config.js` — Color themes for console\r\n\r\n- `context/`\r\n  - `log-context.js` — Correlation IDs with AsyncLocalStorage\r\n  - `request-context.js` — HTTP request context factory and storage\r\n\r\n- `transports/`\r\n  - `base-transport.js` — Strategy base (error-safe)\r\n  - `console-transport.js` — Colored console output\r\n  - `file-transport.js` — Async, batched file writer (Node only)\r\n  - `http-transport.js` — Advanced HTTP transport with permanent/temporary error classification and DLQ\r\n  - `log-buffer.js` — Simple buffer\r\n  - `adaptive-log-buffer.js` — Backpressure-aware buffer used by CoreLogger\r\n  - `batch-queue.js`, `batch-sequencer.js`, `log-rotator.js`, `payload-rotation.js`, `log-archiver.js`, etc. — Batch/rotation utilities\r\n\r\n- `rate-limiting/`\r\n  - `rate-limiter.js` — Token bucket with stats/cleanup\r\n  - `rate-limiter-advanced.js`, `rate-limiter-strict.js` — Additional strategies\r\n\r\n- `sanitizer/`\r\n  - `data-sanitizer.js` — Redaction by keys and patterns (CC, SSN, JWT, keys, etc.), encoding detection\r\n  - `encoding-detector.js` — Base64/URL/Hex detection\r\n  - `sanitizer-advanced.js` — Extensions\r\n\r\n- `error-handling/`\r\n  - `errors.js` — `LoggingError` with codes/context\r\n  - `contextual-log-entry.js`, `error-handler.js` — Contextual error utilities\r\n\r\n- `tracing/`\r\n  - `distributed-tracing.js` — Trace context, OpenTelemetry/W3C/Jaeger formats, propagation helpers\r\n\r\n- `health/`\r\n  - `health-check-manager.js` — Liveness/readiness/startup checks with timeouts, retries, stats\r\n\r\n- `metrics/`\r\n  - `metrics-collector.js` — Counter/gauge/hist/summary; aggregations; Prometheus export\r\n\r\n- `sync/`\r\n  - `mutex.js` — Simple mutex for exclusive sections\r\n\r\n- `utils/`\r\n  - `log-entry.js` — Sanitizing `LogEntry` model\r\n  - `log-formatter.js`, `output-customizer.js` — Formatting/presentation\r\n  - `types.js` — `LogLevel`, `TransportType`\r\n  - Plus helpers: circular refs, stack traces, etc.\r\n\r\n- `workers/`\r\n  - Worker thread integration stubs/pool\r\n\r\n## Installation & Setup\r\n\r\nThis package is ESM-only and requires Node.js 18+.\r\n\r\nRequirements:\r\n\r\n- Node.js >= 18\r\n- Native ES Modules environment (package.json uses `\"type\": \"module\"`)\r\n\r\nInstall (from a local clone or workspace):\r\n\r\n```powershell\r\n# From your project folder\r\nnpm install\r\n```\r\n\r\nUse as a package (npm):\r\n\r\n```powershell\r\nnpm install @al-masry/audit-core\r\n```\r\n\r\nNote: The package is published under the scoped name `@al-masry/audit-core`.\r\n\r\nESM import (recommended):\r\n\r\n```js\r\nimport { CoreLogger, LogLevel } from '@al-masry/audit-core';\r\n```\r\n\r\nCommonJS usage:\r\n\r\n- Node cannot require() native ES Modules directly.\r\n- Prefer dynamic import() in CJS:\r\n\r\n```js\r\n(async () => {\r\n  const { CoreLogger } = await import('@al-masry/audit-core');\r\n  const logger = new CoreLogger({ name: 'app' });\r\n  logger.info('Hello from CJS via dynamic import');\r\n})();\r\n```\r\n\r\n## Quick Start Guide\r\n\r\nImportant async note:\r\n\r\n- `logger.log/debug/info/warn/error` are async and resolve to a boolean. Prefer `await` to handle backpressure outcomes properly.\r\n- `flush()` and `drain()` are async and should be awaited before shutdown.\r\n\r\nTransports and batching: CoreLogger flushes a batch of entries. Built-in `ConsoleTransport` and `HttpTransport` already provide `write(entries)` for batched delivery. If you use a custom transport that only implements per-entry `log(entry)`, either add a `write(entries)` method or wrap it in a small adapter.\r\n\r\n```js\r\nimport { CoreLogger, LogLevel, ConsoleTransport } from '@al-masry/audit-core';\r\n\r\nconst logger = new CoreLogger({\r\n  name: 'app',\r\n  transports: [new ConsoleTransport()],\r\n  buffer: {\r\n    maxSize: 1000,\r\n    flushInterval: 1000,\r\n    highWaterMark: 0.8,\r\n    lowWaterMark: 0.5,\r\n  },\r\n  rateLimiter: { tokensPerSecond: 1000, burstCapacity: 2000 },\r\n  // Optional unified error hook for internal logging errors\r\n  errorHandler: (err) => {\r\n    // You can forward to your monitoring here\r\n    // console.warn('Logger internal error:', err);\r\n  },\r\n});\r\n\r\nawait logger.info('Application started', { env: process.env.NODE_ENV });\r\nawait logger.debug('Debug details will be buffered/sanitized');\r\nawait logger.drain(); // optional: wait for backpressure to clear (e.g., before shutdown)\r\nawait logger.close(); // gracefully close transports\r\n```\r\n\r\n## Example usage\r\n\r\nA minimal usage snippet inspired by `utils/example-logger-usage.js`:\r\n\r\n```js\r\nimport { CoreLogger } from '@al-masry/audit-core';\r\nimport { ConsoleTransport } from '@al-masry/audit-core';\r\n\r\nconst transport = new ConsoleTransport();\r\nconst logger = new CoreLogger({ name: 'app', transports: [transport] });\r\n\r\nawait logger.info('Application started');\r\nawait logger.debug('Vector calculation (debug)', { precision: 0.001, algorithm: 'Bresenham' });\r\n```\r\n\r\nTo try locally, save the snippet as `quick-start.mjs` and run:\r\n\r\n```powershell\r\nnode .\\quick-start.mjs\r\n```\r\n\r\n## Configuration\r\n\r\n- CoreLogger (constructor options in `core/core-logger.js`):\r\n  - `name` string (default: 'Logger')\r\n  - `buffer` object for `AdaptiveLogBuffer`:\r\n    - `maxSize`, `maxMemory`, `flushInterval`, `highWaterMark`, `lowWaterMark`\r\n  - `rateLimiter` object for `RateLimiter`:\r\n    - `tokensPerSecond`, `burstCapacity`\r\n  - `transports` array (each should implement `write(entries)`; see adapter note)\r\n  - `enableTransformLogging` boolean (default true)\r\n  - `transformContext` Map (optional, to reuse an existing context)\r\n\r\n- CoreLoggerConfig (`core/core-logger-config.js`):\r\n  - Validates transports (must extend `BaseTransport` if using `CoreLoggerConfig` instance)\r\n  - Manages module-level log configuration via `ModuleConfig`\r\n  - Methods: `getLogLevelForModule`, `setModuleLevel`, `setPatternLevel`, `onChange`, `getInfo`\r\n\r\n- ModuleConfig (`config/module-config.js`):\r\n  - Per-module and pattern-based levels with listeners and JSON import/export\r\n  - `setModuleLevel('math-lib', LogLevel.DEBUG)`, `setPatternLevel('*-lib', LogLevel.WARN)`\r\n\r\n- DynamicConfigurationManager (`config/dynamic-config.js`):\r\n  - Safe runtime updates with validators, audit log, rollback\r\n  - `updateConfig(key, value)`, `updateMultiple(updates)`, `rollback(stepsBack)`, `getConfig()`\r\n\r\n- DynamicConfigIntegration (`config/dynamic-config-integration.js`):\r\n  - Facade to enable dynamic config and set global/module levels and rate limits during runtime\r\n\r\n- Log Presets (`config/log-presets.js`):\r\n  - Built-in: development, production, testing, debugging\r\n  - `LogPresets.setPreset('production')`\r\n\r\n- Sanitizer (`sanitizer/data-sanitizer.js`):\r\n  - Redacts sensitive keys and patterns; supports encoding detection\r\n  - Config options: `sensitiveKeys`, `patterns`, `maskEmails`, `maskIPs`, `maskPhones`, etc.\r\n\r\n- Context (`context/log-context.js`, `context/request-context.js`):\r\n  - `LogContext.initialize()`, `.setCorrelationId()`, `.getContext()`\r\n  - `RequestContextFactory.fromExpressRequest(req)` and similar factories\r\n\r\n- Transports:\r\n  - `ConsoleTransport` — supports single-entry `log(entry)` and batch `write(entries)`\r\n  - `FileTransport` — Node-only; directory required; batched write queue\r\n  - `HttpTransport` — advanced HTTP transport (alias of `AdvancedHttpTransport`) with retry/backoff and DLQ; supports `log(entry)` and `write(entries)`\r\n  - For custom transports that lack `write(entries)`, add it or wrap them with a simple adapter\r\n\r\n## Usage Examples\r\n\r\n- File transport (Node-only) with adapter:\r\n\r\n```js\r\nimport { CoreLogger, FileTransport, LogLevel } from '@al-masry/audit-core';\r\n\r\nclass FileBatchAdapter {\r\n  constructor(logDirectory) {\r\n    this.file = new FileTransport({ logDirectory, maxQueueSize: 100, flushInterval: 1000 });\r\n  }\r\n  async write(entries) {\r\n    for (const e of entries) {\r\n      await this.file.log(e);\r\n    }\r\n  }\r\n}\r\n\r\nconst logger = new CoreLogger({\r\n  name: 'billing',\r\n  transports: [new FileBatchAdapter('./logs')],\r\n});\r\n\r\nlogger.warn('High latency on payment gateway', { provider: 'stripe', latencyMs: 450 });\r\n```\r\n\r\n- HTTP transport with exponential backoff and dead-letter queue:\r\n\r\n```js\r\nimport { CoreLogger, HttpTransport } from '@al-masry/audit-core';\r\n\r\nclass HttpBatchAdapter {\r\n  constructor(url, options) {\r\n    this.http = new HttpTransport(url, options);\r\n  }\r\n  async write(entries) {\r\n    for (const e of entries) {\r\n      await this.http.send(e);\r\n    }\r\n  }\r\n}\r\n\r\nconst logger = new CoreLogger({\r\n  name: 'api',\r\n  transports: [new HttpBatchAdapter('https://logs.example.com/ingest', { maxRetries: 5 })],\r\n});\r\n\r\nlogger.error('Upstream service returned 503', { service: 'inventory', attempt: 3 });\r\n```\r\n\r\n- Context and correlation:\r\n\r\n```js\r\nimport { LogContext } from '@al-masry/audit-core';\r\n\r\nconst correlationId = LogContext.initialize();\r\nlogger.info('Start request', { correlationId });\r\n\r\nLogContext.runWithContext(() => {\r\n  logger.info('Processing within async context', LogContext.getContext());\r\n});\r\n```\r\n\r\n- Dynamic configuration at runtime:\r\n\r\n```js\r\nimport { DynamicConfigIntegration } from '@al-masry/audit-core';\r\n\r\nDynamicConfigIntegration.enable({ defaultLogLevel: 'INFO' });\r\nDynamicConfigIntegration.setModuleLogLevel('api', 'WARN');\r\n```\r\n\r\n- Health checks (internal module):\r\n\r\n```js\r\n// When using the source directly:\r\nimport { HealthCheckManager } from './health/health-check-manager.js';\r\n\r\nconst health = new HealthCheckManager({ serviceName: 'user-service' });\r\nhealth.registerCheck('db', async () => true, { type: health.CheckTypes.READINESS });\r\nconsole.log(await health.getFullStatus());\r\n```\r\n\r\n- Metrics (internal module):\r\n\r\n```js\r\n// When using the source directly:\r\nimport { MetricsCollector } from './metrics/metrics-collector.js';\r\n\r\nconst metrics = new MetricsCollector({ serviceName: 'api', environment: 'prod' });\r\nconst requests = metrics.createCounter('http_requests_total');\r\nrequests.increment();\r\nconsole.log(metrics.exportAsPrometheus());\r\n```\r\n\r\nNote: Health and Metrics are present in the repository but are not exported via the root `index.js`. If you consume this as a published package, these modules are not part of the public API unless exported.\r\n\r\n## API Reference\r\n\r\nThis library is primarily a set of ES classes. Highlights only:\r\n\r\n- `CoreLogger` (core/core-logger.js)\r\n  - `new CoreLogger({ name, buffer, rateLimiter, transports, errorHandler, enableTransformLogging, transformContext })`\r\n  - `log(level, message, metadata?)`, `debug/info/warn/error(message, metadata?)` — all async, resolve to `boolean`\r\n  - `logWithContext(level, objectId, message, additionalData?)`, `debugWithContext/infoWithContext/warnWithContext/errorWithContext`\r\n  - Transform/context management: `registerObject`, `updateTransform`, `setObjectParent`, `getTransform`, `getHierarchyInfo`\r\n  - State mgmt: `setObjectState`, `getObjectState`, `snapshotContext`, `restoreFromSnapshot`, `cleanupOldSnapshots`, `clearAll`\r\n  - Transports/flow: `addTransport`, `removeTransport`, `flush()`, `drain()`, `close()` — all async\r\n  - Observability: `getStatistics`, `getReport`, `resetStats`, `destroy`\r\n\r\n- `AdaptiveLogBuffer` (transports/adaptive-log-buffer.js)\r\n  - `push(entry)` -> boolean; `onFlush(cb)`, `flush()`, `onDrain(cb)`, `getStatistics()`\r\n\r\n- `RateLimiter` (rate-limiting/rate-limiter.js)\r\n  - `canLog(key?)`, `waitAndLog(key, fn)`, `getStatus(key)`, `getStatistics()`, `cleanup(maxAge)`\r\n\r\n- `ConsoleTransport` (transports/console-transport.js)\r\n  - `log(entry)` — prints with colors\r\n\r\n- `FileTransport` (transports/file-transport.js)\r\n  - Node-only; `new FileTransport({ logDirectory, maxQueueSize?, flushInterval? })`\r\n  - `log(entry)`, `write(entries)`, `close()` (alias: `shutdown()`)\r\n\r\n- `HttpTransport` (transports/http-transport.js)\r\n  - `new HttpTransport(url, options)` — retry/backoff, dead-letter queue\r\n  - `send(entry)`, `getDeadLetterEntries()`, `getStats()`, `clearDeadLetterQueue()`\r\n\r\n- `LoggerConfig` (config/logger-config.js), `CoreLoggerConfig` (core/core-logger-config.js)\r\n  - Validates/holds transports; integrates with `ModuleConfig`\r\n\r\n- `ModuleConfig` (config/module-config.js)\r\n  - `setModuleLevel()`, `setPatternLevel()`, `getLogLevelForModule()`, `onChange()`, `getAll()`, `fromJSON()`\r\n\r\n- `LogContext` (context/log-context.js), `RequestContext` (context/request-context.js)\r\n  - Correlation and request context utilities\r\n\r\n- `DataSanitizer` (sanitizer/data-sanitizer.js)\r\n  - `sanitize()`, `sanitizeWithEncoding()`, `addSensitiveKey()`, `addCustomPattern()`, `getStatistics()`\r\n\r\n- `MetricsCollector` (metrics/metrics-collector.js) — internal module\r\n- `HealthCheckManager` (health/health-check-manager.js) — internal module\r\n\r\n### API stability status\r\n\r\nThe following summarizes the public exports and their stability. Items marked Experimental may change without notice in a minor release; prefer Stable APIs for production.\r\n\r\n- Stable\r\n  - Core: `CoreLogger`\r\n  - Transports: `ConsoleTransport`, `FileTransport`, `HttpTransport`, `AdaptiveLogBuffer`, `LogBuffer`\r\n  - Config: `LoggerConfig`, `ModuleConfig`, `LogPresets`, `CoreLoggerConfig`, `DynamicConfigIntegration`\r\n  - Context & Error: `LogContext`, `RequestContext`, `LoggingError`\r\n  - Rate limiting: `RateLimiter`\r\n  - Utilities: `LogLevel`, `LogEntry`\r\n\r\n- Experimental\r\n  - Aliases: `EnhancedLogger`, `EnhancedLoggerV2`, `EnhancedLoggerV3`\r\n  - Specialized loggers: `AdaptiveLogger`, `ResilientLogger`\r\n  - Transport helpers: `BatchQueue`, `BatchSequencer`, `LogArchiver`, `LogRotator`, `LogCleanupPolicy`, `PayloadOptimizer`\r\n  - Rate limiting: `RateLimiterAdvanced`, `StrictBurstLimiter`, `MultiLayerRateLimiter`\r\n  - Sanitizer: `AdvancedSanitizer`, `EncodingDetector`\r\n  - Workers & Tracing: `WorkerThreadPool`, `WorkerThreadIntegration`, `LoggerWorkerIntegration`, `DistributedTracing`, `DistributedTracingIntegration`\r\n  - Utilities: `StackTrace`, `LogFormatter`, `ModulePatternMatcher`, `OutputCustomizer`, `MemorySafeContext`, `SupportSystems`\r\n\r\nTesting & Development\r\n\r\n- Tests: see `tests/basic.test.js`. Run them with `npm test` (package.json defines the script).\r\n- CI: GitHub Actions workflow is included at `.github/workflows/ci.yml` to run tests on push/PR.\r\n- Build: source is plain ES Modules JavaScript; no build step is required for Node.\r\n- Editor/Tooling: see `jsconfig.json` for ES2020 target and module resolution.\r\n- Local verification:\r\n  - Create a small script using the Quick Start example and run with Node.\r\n  - Validate transports by checking console output and/or created log files.\r\n- Lint/Typecheck: not configured; you can add ESLint/TypeScript as needed for your environment.\r\n\r\n## Deployment\r\n\r\n- Runtime:\r\n  - Node.js >= 18 recommended; ES Modules (`\"type\": \"module\"`)\r\n  - For file transport: ensure the log directory exists and the process has write permissions\r\n- Graceful shutdown:\r\n  - Call `await logger.flush()` or `await logger.drain()` before exiting\r\n  - Then call `await logger.close()` to close transports (FileTransport: `close()`)\r\n- Docker (example):\r\n  - Mount persistent volume for file logs\r\n  - Set environment variables like `NODE_ENV=production`\r\n- Production tips:\r\n  - Consider setting log levels via `ModuleConfig` or dynamic config at runtime\r\n  - Route logs to HTTP/centralized sinks using `HttpTransport` with backoff\r\n  - Keep sanitization enabled on untrusted inputs\r\n  - Monitor health and metrics by exposing outputs from `HealthCheckManager` and `MetricsCollector` where applicable\r\n\r\n## Contributing\r\n\r\n- Use ES Modules and keep modules cohesive within their domain folder\r\n- Add unit tests under `tests/` for new features and bug fixes\r\n- Follow existing naming and code style conventions\r\n- For public APIs, update this README and add inline JSDoc\r\n- Submit pull requests with a clear description and reproduction steps when fixing bugs\r\n\r\n## CommonJS Compatibility\r\n\r\nThis package is **ESM-only** and requires **Node.js 18+**.\r\nThe previous CommonJS compatibility shim (`index.cjs`) has been removed.\r\nIf you need to use this library from a CommonJS project, load it via:\r\n\r\n```js\r\n(async () => {\r\n  const mod = await import('@al-masry/audit-core');\r\n})();\r\n```\r\n\r\n## License\r\n\r\nMIT License. See the `LICENSE` file for details.\r\n\r\n## Contact & Support\r\n\r\nFor issues and feature requests, please open a GitHub issue in this repository. Include:\r\n\r\n- Node.js version and environment\r\n- Minimal reproduction (code snippets)\r\n- Logs or error messages (sanitized)\r\n\r\n## Changelog / Version Info\r\n\r\n- 1.0.0 — Stable production release with adaptive buffering, structured logging, and rate limiting.\r\n\r\nNotes:\r\n\r\n- Public exports are defined in `index.js` and `package.json#exports`.\r\n\r\n## API Manifest (v1.0 Freeze)\r\n\r\nThe following table freezes the stable public API surface at version 1.0. Any additions must be explicitly approved and reflected in `api-manifest.json`.\r\n\r\n| Name              | Kind  | Stability | Source Path                         |\r\n| ----------------- | ----- | --------- | ----------------------------------- |\r\n| CoreLogger        | class | stable    | ./core/core-logger.js               |\r\n| Logger            | class | stable    | ./core/core-logger.js               |\r\n| CoreLoggerConfig  | class | stable    | ./core/core-logger-config.js        |\r\n| LoggerConfig      | class | stable    | ./config/logger-config.js           |\r\n| ModuleConfig      | class | stable    | ./config/module-config.js           |\r\n| DynamicConfig     | class | stable    | ./config/dynamic-config.js          |\r\n| LogContext        | class | stable    | ./context/log-context.js            |\r\n| RequestContext    | class | stable    | ./context/request-context.js        |\r\n| ConsoleTransport  | class | stable    | ./transports/console-transport.js   |\r\n| FileTransport     | class | stable    | ./transports/file-transport.js      |\r\n| HttpTransport     | class | stable    | ./transports/http-transport.js      |\r\n| LogBuffer         | class | stable    | ./transports/log-buffer.js          |\r\n| AdaptiveLogBuffer | class | stable    | ./transports/adaptive-log-buffer.js |\r\n| RateLimiter       | class | stable    | ./rate-limiting/rate-limiter.js     |\r\n| LoggingError      | class | stable    | ./error-handling/errors.js          |\r\n| DataSanitizer     | class | stable    | ./sanitizer/data-sanitizer.js       |\r\n| EncodingDetector  | class | stable    | ./sanitizer/encoding-detector.js    |\r\n| Mutex             | class | stable    | ./sync/mutex.js                     |\r\n| LogLevel          | const | stable    | ./utils/types.js                    |\r\n| LogEntry          | class | stable    | ./utils/log-entry.js                |\r\n","readmeFilename":"README.md"}