23 Commits
Author SHA1 Message Date
mifi 64b63e1c52 fix:prettier and some type updates
ci/woodpecker/push/ci Pipeline was successful
ci/woodpecker/push/publish Pipeline was successful
2026-08-21 12:33:03 -03:00
mifi 6651b713db fix(docs):Docs and Exports
ci/woodpecker/push/ci Pipeline was successful
ci/woodpecker/push/publish Pipeline was successful
- Add documentation for recently released changes
- Update some exports to include enums
2026-08-21 11:47:07 -03:00
mifi f464fa5017 fix(docs):Docs and Exports
ci/woodpecker/push/ci Pipeline failed
ci/woodpecker/push/publish unknown status
- Add documentation for recently released changes
- Update some exports to include enums
2026-08-21 11:45:56 -03:00
semantic-release-bot 2134ba58b8 chore(release): 1.1.0 [skip ci]
# [1.1.0](https://git.mifi.dev/mifi/logger/compare/v1.0.1...v1.1.0) (2026-08-21)

### Features

* now supports `async` functions for logging data ([c2bcc6c](c2bcc6c82c))
* now supports `async` functions for logging data ([16550ec](16550ec8bb))
2026-08-21 14:36:17 +00:00
mifi c2bcc6c82c feat: now supports async functions for logging data
ci/woodpecker/push/ci Pipeline was successful
ci/woodpecker/push/publish Pipeline was successful
- `logger.debug('message', async () => ({ asyncReturn: await asyncFn() }))` is now supported
- NOTE: this may result in logging occurring out of band for these calls if other events fire befor they settle

Update CI labels to direct jobs to correct servers
2026-08-21 11:34:33 -03:00
mifi 16550ec8bb feat: now supports async functions for logging data
ci/woodpecker/push/ci Pipeline failed
ci/woodpecker/push/publish unknown status
- `logger.debug('message', async () => ({ asyncReturn: await asyncFn() }))` is now supported
- NOTE: this may result in logging occurring out of band for these calls if other events fire befor they settle

Update CI labels to direct jobs to correct servers
2026-08-21 11:24:34 -03:00
semantic-release-bot 292f44821d chore(release): 1.0.1 [skip ci]
## [1.0.1](https://git.mifi.dev/mifi/logger/compare/v1.0.0...v1.0.1) (2026-08-07)

### Bug Fixes

* **sentry:** widen SentryLike so official SDKs assign without adapters ([9f6f6e4](9f6f6e4df5))
* **sentry:** widen SentryLike so official SDKs assign without adapters ([3c468db](3c468dbf44))
2026-08-07 19:08:20 +00:00
mifi 9f6f6e4df5 fix(sentry): widen SentryLike so official SDKs assign without adapters
ci/woodpecker/push/ci Pipeline was successful
ci/woodpecker/push/publish Pipeline was successful
2026-08-07 16:06:22 -03:00
mifi 3c468dbf44 fix(sentry): widen SentryLike so official SDKs assign without adapters
ci/woodpecker/push/ci Pipeline failed
ci/woodpecker/push/publish unknown status
2026-08-07 16:05:09 -03:00
semantic-release-bot 19de8db119 chore(release): 1.0.0 [skip ci]
# [1.0.0](https://git.mifi.dev/mifi/logger/compare/v0.10.0...v1.0.0) (2026-08-07)

### Features

* API options object support to control sentry handling; removal of `logger.sentry.` ([234226e](234226e2bb))
* API options object support to control sentry handling; removal of `logger.sentry.` ([6bee3a8](6bee3a801d))

### BREAKING CHANGES

* API options object support to control sentry handling; removal of `logger.sentry.`
* API options object support to control sentry handling; removal of `logger.sentry.`
2026-08-07 15:22:51 +00:00
mifi 9bcf28c9dc Semvar fixes
ci/woodpecker/push/ci Pipeline was successful
ci/woodpecker/push/publish Pipeline was successful
2026-08-07 12:20:52 -03:00
mifi 234226e2bb feat!: API options object support to control sentry handling; removal of logger.sentry.
ci/woodpecker/push/ci Pipeline was successful
ci/woodpecker/push/publish Pipeline was successful
# Conflicts:
#	README.md
#	src/logger.ts
#	src/sinks/sentry.ts
#	test/logger.test.ts
2026-08-07 12:10:38 -03:00
mifi 6bee3a801d feat!: API options object support to control sentry handling; removal of logger.sentry.
ci/woodpecker/push/ci Pipeline failed
ci/woodpecker/push/publish unknown status
2026-08-07 12:07:29 -03:00
semantic-release-bot 9f18e0855e chore(release): 0.10.0 [skip ci]
# [0.10.0](https://git.mifi.dev/mifi/logger/compare/v0.9.3...v0.10.0) (2026-08-05)

### Features

* **logger:** add explicit Sentry event channel ([44f4716](44f471653e))
2026-08-05 16:06:59 +00:00
mifi 44f471653e feat(logger): add explicit Sentry event channel
ci/woodpecker/push/ci Pipeline was successful
ci/woodpecker/push/publish Pipeline was successful
2026-08-05 13:05:06 -03:00
semantic-release-bot 0ccb7f911d chore(release): 0.9.3 [skip ci]
## [0.9.3](https://git.mifi.dev/mifi/logger/compare/v0.9.2...v0.9.3) (2026-08-05)

### Bug Fixes

* **release:** build package before publishing ([e0b4501](e0b450157d))
* **release:** build package before publishing ([cebe107](cebe107034))
2026-08-05 12:34:44 +00:00
mifi e0b450157d fix(release): build package before publishing
ci/woodpecker/push/ci Pipeline was successful
ci/woodpecker/push/publish Pipeline was successful
2026-08-05 09:32:51 -03:00
mifi cebe107034 fix(release): build package before publishing
ci/woodpecker/push/ci Pipeline failed
ci/woodpecker/push/publish unknown status
2026-08-05 09:27:19 -03:00
semantic-release-bot 47e3930b4b chore(release): 0.9.2 [skip ci]
## [0.9.2](https://git.mifi.dev/mifi/logger/compare/v0.9.1...v0.9.2) (2026-08-05)

### Bug Fixes

* **ci:** authenticate semantic release pushes ([1c63e58](1c63e58809))
* **ci:** install CA certificates for release workflows ([d211d9f](d211d9f8bc))
* **ci:** install git for release workflows ([afd2ca1](afd2ca1978))
2026-08-05 04:40:55 +00:00
mifi 1c63e58809 fix(ci): authenticate semantic release pushes
ci/woodpecker/push/ci Pipeline was successful
ci/woodpecker/push/publish Pipeline was successful
2026-08-05 01:38:41 -03:00
mifi d211d9f8bc fix(ci): install CA certificates for release workflows
ci/woodpecker/push/ci Pipeline was successful
ci/woodpecker/push/publish Pipeline failed
2026-08-05 01:35:07 -03:00
mifi afd2ca1978 fix(ci): install git for release workflows
ci/woodpecker/push/ci Pipeline was successful
ci/woodpecker/push/publish Pipeline failed
2026-08-05 01:31:39 -03:00
mifi 934367d695 chore(ci): configure release automation
ci/woodpecker/push/ci Pipeline was successful
ci/woodpecker/push/publish Pipeline failed
2026-08-05 01:29:07 -03:00
23 changed files with 3005 additions and 1116 deletions
+1 -1
View File
@@ -1 +1 @@
{ "singleQuote": false, "tabWidth": 4, "trailingComma": "all", "printWidth": 100 }
{ "singleQuote": true, "tabWidth": 4, "trailingComma": "all", "printWidth": 100, "semi": true }
+3
View File
@@ -3,6 +3,9 @@ when:
- event: push
branch: main
labels:
performance: high
steps:
verify:
image: node:24-bookworm-slim
+12 -2
View File
@@ -6,14 +6,22 @@ when:
depends_on:
- ci
labels:
performance: high
clone:
git:
image: woodpeckerci/plugin-git
settings:
depth: 0
partial: false
tags: true
steps:
release:
image: node:24-bookworm-slim
environment:
GITEA_PACKAGE_TOKEN:
NPM_TOKEN:
from_secret: gitea_package_token
GITEA_REGISTRY_USERNAME:
from_secret: gitea_registry_username
@@ -22,12 +30,14 @@ steps:
commands:
- corepack enable
- corepack prepare pnpm@11.0.0 --activate
- apt-get update && apt-get install --yes --no-install-recommends ca-certificates git
- pnpm install --frozen-lockfile
- git config user.name "Woodpecker CI"
- git config user.email "woodpecker-ci@mifi.dev"
- git remote set-url origin "https://${GITEA_REGISTRY_USERNAME}:${GITEA_RELEASE_TOKEN}@git.mifi.dev/mifi/logger.git"
- npm config set @mifi:registry https://git.mifi.dev/api/packages/mifi/npm/
- npm config set -- //git.mifi.dev/api/packages/mifi/npm/:_authToken "$GITEA_PACKAGE_TOKEN"
- npm config set -- //git.mifi.dev/api/packages/mifi/npm/:_authToken "$NPM_TOKEN"
- pnpm build
- pnpm release
notify-release-failure:
+46
View File
@@ -0,0 +1,46 @@
# [1.1.0](https://git.mifi.dev/mifi/logger/compare/v1.0.1...v1.1.0) (2026-08-21)
### Features
- now supports `async` functions for logging data ([c2bcc6c](https://git.mifi.dev/mifi/logger/commit/c2bcc6c82c675640b85e97f1d78dd7c6e627d8f0))
- now supports `async` functions for logging data ([16550ec](https://git.mifi.dev/mifi/logger/commit/16550ec8bb7810ccc36c36cbaab5542e4ad66dae))
## [1.0.1](https://git.mifi.dev/mifi/logger/compare/v1.0.0...v1.0.1) (2026-08-07)
### Bug Fixes
- **sentry:** widen SentryLike so official SDKs assign without adapters ([9f6f6e4](https://git.mifi.dev/mifi/logger/commit/9f6f6e4df52449a84111656a939fda5f59816ea5))
- **sentry:** widen SentryLike so official SDKs assign without adapters ([3c468db](https://git.mifi.dev/mifi/logger/commit/3c468dbf44caf119b4ff769cbc158a4c3d9f6c54))
# [1.0.0](https://git.mifi.dev/mifi/logger/compare/v0.10.0...v1.0.0) (2026-08-07)
### Features
- API options object support to control sentry handling; removal of `logger.sentry.` ([234226e](https://git.mifi.dev/mifi/logger/commit/234226e2bbb79acf3b2686890677bd7326c6a0e0))
- API options object support to control sentry handling; removal of `logger.sentry.` ([6bee3a8](https://git.mifi.dev/mifi/logger/commit/6bee3a801da054a613e84d7985050e7e4e367194))
### BREAKING CHANGES
- API options object support to control sentry handling; removal of `logger.sentry.`
- API options object support to control sentry handling; removal of `logger.sentry.`
# [0.10.0](https://git.mifi.dev/mifi/logger/compare/v0.9.3...v0.10.0) (2026-08-05)
### Features
- **logger:** add explicit Sentry event channel ([44f4716](https://git.mifi.dev/mifi/logger/commit/44f471653e8d4045e87886da1e1bbe04edbd60af))
## [0.9.3](https://git.mifi.dev/mifi/logger/compare/v0.9.2...v0.9.3) (2026-08-05)
### Bug Fixes
- **release:** build package before publishing ([e0b4501](https://git.mifi.dev/mifi/logger/commit/e0b450157df7a8aa1ff8bf5299140b0e7b52a7f7))
- **release:** build package before publishing ([cebe107](https://git.mifi.dev/mifi/logger/commit/cebe107034a15e9fd1517d872037e97337426b29))
## [0.9.2](https://git.mifi.dev/mifi/logger/compare/v0.9.1...v0.9.2) (2026-08-05)
### Bug Fixes
- **ci:** authenticate semantic release pushes ([1c63e58](https://git.mifi.dev/mifi/logger/commit/1c63e58809049e8a3a4da00601b09e60a5482ff1))
- **ci:** install CA certificates for release workflows ([d211d9f](https://git.mifi.dev/mifi/logger/commit/d211d9f8bc205ae6b952e35603773e44bca5ee37))
- **ci:** install git for release workflows ([afd2ca1](https://git.mifi.dev/mifi/logger/commit/afd2ca1978d7373daa4b6ffa9067122586ba5f86))
+218 -14
View File
@@ -3,39 +3,243 @@
Intentional, namespaced logging for TypeScript browser and Node.js applications.
```ts
import { createLogger } from "@mifi/logger";
import { createLogger } from '@mifi/logger';
const logger = createLogger({ environment: "production" });
logger.child("WIDGET").debug("Rendered", () => ({ expensive: "only evaluated when shown" }));
const logger = createLogger({ environment: 'production', namespace: 'WIDGET' });
logger.child('Button').debug('Rendered', () => ({ expensive: 'only evaluated when shown' }));
logger.debug('response', async () => ({ data: await fetchBody() })); // settled before sinks
```
## Install
```bash
pnpm add @mifi/logger
```
Requires Node.js `>=24`. Published to the private `@mifi` registry.
## Quick start
```ts
import { createLogger } from '@mifi/logger';
const logger = createLogger({
environment: 'development', // "development" | "staging" | "production"
namespace: 'API', // optional; string or string[] joined with ":"
});
logger.trace('very detailed');
logger.debug('diagnostic', () => ({ snapshot: heavyWork() }));
logger.debug('response', async () => ({ data: await res.json(), url: res.url }));
logger.info('ready');
logger.warn('slow response', { ms: 1200 });
logger.error('request failed', error);
logger.assert(userId, 'missing user id');
const auth = logger.child('auth'); // namespace → "API:auth"
auth.info('token refreshed');
```
Console utility methods (`group`, `groupCollapsed`, `table`, `time`, `count`, `dir`, …) are available and gated by the same level policy as `info`.
## Runtime policy
Development shows every level, staging shows `warn` and `error`, and production shows `error` only. Browser sessions can override the policy with `sessionStorage.showLoggingFor`:
Default levels by environment:
```text
debug
debug:WIDGET,API
| Environment | Default level | Console shows |
| ------------- | ------------- | --------------- |
| `development` | `trace` | all levels |
| `staging` | `warn` | `warn`, `error` |
| `production` | `error` | `error` only |
Levels in order (most → least verbose): `trace``debug``info``warn``error``silent`.
### Override precedence
Highest wins:
1. Explicit `level` option on `createLogger`
2. Browser `sessionStorage.showLoggingFor`
3. Env vars `MIFI_LOG_LEVEL` / `MIFI_LOG_NAMESPACES`
4. Environment default (table above)
### Browser session override
```js
sessionStorage.setItem('showLoggingFor', 'debug');
// or restrict to namespaces (exact or descendants):
sessionStorage.setItem('showLoggingFor', 'debug:WIDGET,API');
```
Containers can use `MIFI_LOG_LEVEL` and `MIFI_LOG_NAMESPACES`. Explicit `level` options take precedence.
`WIDGET` matches `WIDGET` and `WIDGET:Button`.
### Container / Node env overrides
See [Environment variables](#environment-variables) and [`env.example`](./env.example).
```bash
MIFI_LOG_LEVEL=debug
MIFI_LOG_NAMESPACES=WIDGET,API
```
## Environment variables
These are read from `process.env` (or from `options.env` when testing/injecting):
| Variable | Description |
| --------------------- | --------------------------------------------------------------------------- |
| `MIFI_LOG_LEVEL` | Override level: `trace`, `debug`, `info`, `warn`, `error`, or `silent`. |
| `MIFI_LOG_NAMESPACES` | Optional comma-separated namespace filters applied with the level override. |
When only `MIFI_LOG_LEVEL` is set, all namespaces are enabled at that level. When `MIFI_LOG_NAMESPACES` is also set, only matching namespaces (and their children) emit at that level.
Copy [`env.example`](./env.example) as a starting point for local or container config.
## Sentry
The Sentry adapter has no SDK dependency. Provide the SDK that your application already uses. In a production browser, errors go to Sentry without also appearing in the console. In Node, they go to both Sentry and stderr.
The Sentry adapter has **no SDK dependency**. Pass your official `@sentry/node`, `@sentry/browser`, or `@sentry/nextjs` module directly to `createSentrySink` — no consumer adapter or cast is required.
**Development never sends to Sentry.** Staging and production attach the sink when `sentry` is configured.
Destination policy when `sentry` is configured and `sinks` is not:
| Runtime + environment | Console | Sentry |
| ---------------------- | ---------------------- | -------------------------------- |
| Production **browser** | Off | Issues for errors; optional Logs |
| Production **Node** | On (stderr for errors) | Issues for errors; optional Logs |
| Staging | On (default `warn`+) | Issues for errors; optional Logs |
| Development | On | Nothing |
### Issues vs Logs
- **Errors** → Sentry Issues (`captureException` / `captureMessage`). Not also written to Logs.
- **Warnings and lower** → Sentry Logs (`sentry.logger.*`) only when `{ logs: true }` on the sink (or forced per call).
Default Sentry Logs thresholds when `logs` is enabled:
| Environment | Logs threshold |
| ----------- | -------------- |
| Staging | `info` |
| Production | `warn` |
Override with `logLevel` on `createSentrySink`. Console policy stays independent — production browsers can stay quiet while warnings still appear in Sentry Logs.
### Per-call options
`trace` / `debug` / `log` / `info` / `warn` / `error` (and `assert`) accept a trailing options object. Console utilities (`group`, `time`, …) do not.
```ts
import * as Sentry from "@sentry/nextjs";
import { createLogger } from "@mifi/logger";
import { createSentrySink } from "@mifi/logger/sentry";
import * as Sentry from '@sentry/nextjs';
import { createLogger } from '@mifi/logger';
import { createSentrySink } from '@mifi/logger/sentry';
const logger = createLogger({ environment: "production", sentry: createSentrySink(Sentry) });
const logger = createLogger({
environment: 'production',
namespace: 'API',
sentry: createSentrySink(Sentry, { logs: true }),
});
logger.error('Request failed', error, { requestId: 'req_1' });
logger.warn('slow', { ms: 1200 }); // → Sentry Logs in production
logger.info('investigating', { orderId }, { sentry: true }); // force Logs
logger.error('expected', err, { suppressSentry: true }); // console only (when enabled)
```
| Option | Effect |
| ---------------------- | ------------------------------------------------------------------------ |
| `sentry: true` | Force this event to Sentry Logs (ignores Logs threshold; not for errors) |
| `suppressSentry: true` | Skip creating a Sentry Issue for an error |
A last argument is treated as options only when every key is `sentry` or `suppressSentry`. Prefer the third-argument form when you also pass data.
Logs payload: string message + flat primitive attributes (including `logger.namespace`). Nested objects are not unfurled. When emit was deferred for thenables, the payload also includes `async: true`.
Issue severities use Sentrys union (`warning`, not logger `warn`). The sink maps `warn``warning` and `trace``debug` for Issues only; Logs keep logger level names (`sentry.logger.warn`).
## Custom sinks
Replace the default destinations entirely with `sinks`:
```ts
import { createLogger, createConsoleSink, type LogSink } from '@mifi/logger';
const analyticsSink: LogSink = {
emit(event) {
if (event.sendToConsole) analytics.track('log', event);
// event.async === true when args were settled asynchronously
},
};
const logger = createLogger({
environment: 'production',
sinks: [createConsoleSink(), analyticsSink],
});
```
When `sinks` is provided, the `sentry` option is not used for default sink selection.
## API overview
| Export | From | Purpose |
| ---------------------- | --------------------- | ------------------------------------------------ |
| `createLogger` | `@mifi/logger` | Build a namespaced, Console-shaped logger |
| `createConsoleSink` | `@mifi/logger` | Default styled console destination |
| `parseLoggingOverride` | `@mifi/logger` | Parse `debug` / `debug:NS1,NS2` override strings |
| `createSentrySink` | `@mifi/logger/sentry` | Adapter for any Sentry-like SDK |
Types: `Logger`, `LoggerOptions`, `LogLevel`, `LoggerEnvironment`, `LogEvent`, `LogSink`, `LogData`, `LogCallOptions`, and (from `/sentry`) `SentryLike`, `SentryScopeLike`, `SentrySeverityLevel`, `SentrySink`, `SentrySinkOptions`.
Optional destinations live under `src/sinks/` (console, Sentry today; New Relic / Datadog-style adapters can land beside them later). Public import paths stay `@mifi/logger` and `@mifi/logger/sentry`.
All public APIs include JSDoc with parameter and example documentation in the TypeScript sources.
## Lazy arguments
Any function passed **after** the first argument is invoked only if the event will actually be emitted (console and/or Sentry). That keeps expensive snapshots cheap when the level is suppressed.
```ts
logger.debug('state', () => buildHugeSnapshot()); // skipped when debug is suppressed
logger.error('failed', error, () => ({ body: pendingBody }));
```
### Async factories and Promises
Factories may be `async`, or you may pass a top-level `Promise` as an argument. Thenables are **settled before sinks run**; the log method stays fire-and-forget (`void`).
```ts
logger.debug('response', async () => ({
data: await res.json(),
url: res.url,
}));
logger.error('failed', { id }, responsePromise);
```
| Behavior | Detail |
| ----------------- | -------------------------------------------------------------------------------------------- |
| Unwrap scope | **Shallow** — only top-level thenables in the argument list |
| Nested promises | Not walked; compose with `await` / `Promise.all` inside the factory |
| Call return type | Still `void` (no `await logger.debug(...)`) |
| Timestamp | Captured at call time (before settle), so async logs correlate with the failure moment |
| `LogEvent.async` | `true` when emit was deferred; omitted for fully sync emits |
| Console | Label gains an `[async]` suffix, e.g. `[API][async]` |
| Sentry Logs | Attribute `async: true` when set |
| Ordering | Async emits may appear after later sync logs |
| Rejections | Rejection `reason` replaces that argument slot; other args still emit (`Promise.allSettled`) |
| Console utilities | `group` / `time` / etc. do not settle thenables (emit path only) |
```ts
// Nested promises — compose inside the factory:
logger.debug('route', async () => {
const [body, next] = await Promise.all([res.json(), nextRoute]);
return { body, next };
});
```
## Releases
Woodpecker verifies pull requests and `main`, reports CI to Mattermost, then automatically releases from Conventional Commits merged to `main`. It updates `package.json` and `CHANGELOG.md`, creates a `vX.Y.Z` tag, and publishes to the private `@mifi` registry.
Use `fix:` for a patch, `feat:` for a minor release, and `!` or a `BREAKING CHANGE:` footer for a major release. Commits such as `docs:`, `test:`, and `chore:` do not release a package. Before enabling the automation, publish and tag the existing `v0.9.1` once as its baseline.
Use `fix:` for a patch, `feat:` for a minor release, and `feat!` / `fix!` (or a `BREAKING CHANGE:` footer) for a major release. Commits such as `docs:`, `test:`, and `chore:` do not release a package.
The release workflow uses the existing global `gitea_package_token`, `gitea_registry_username`, `gitea_release_token`, `mattermost_bot_access_token`, `mattermost_tests_channel_id`, `mattermost_pushes_channel_id`, and `mattermost_post_api_url` secrets.
+19
View File
@@ -0,0 +1,19 @@
# @mifi/logger — environment variables
#
# Copy this file or set the variables in your container / process environment.
# Explicit `level` on createLogger() always takes precedence over these values.
# In browsers, sessionStorage.showLoggingFor is checked before these env vars.
# Override the log level for this process.
# One of: trace | debug | info | warn | error | silent
# When unset, the level defaults from the logger's `environment` option:
# development → trace
# staging → warn
# production → error
# MIFI_LOG_LEVEL=debug
# Optional comma-separated namespace filters applied together with MIFI_LOG_LEVEL.
# A filter matches the namespace exactly or as a prefix of a child
# (e.g. WIDGET matches WIDGET and WIDGET:Button).
# When unset (and MIFI_LOG_LEVEL is set), all namespaces are enabled at that level.
# MIFI_LOG_NAMESPACES=WIDGET,API
+4 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@mifi/logger",
"version": "0.9.1",
"version": "1.1.0",
"description": "Intentional, namespaced logging for browser and Node.js TypeScript applications.",
"repository": {
"type": "git",
@@ -32,10 +32,12 @@
},
"scripts": {
"build": "tsup",
"prepack": "npm run build",
"check": "tsc --noEmit",
"format": "prettier --write .",
"format:check": "prettier --check .",
"lint": "oxlint src test",
"lint:fix": "oxlint src test --fix",
"test": "vitest run",
"test:watch": "vitest",
"pack:check": "pnpm pack --pack-destination .artifacts",
@@ -44,6 +46,7 @@
"devDependencies": {
"@semantic-release/changelog": "^7.0.0",
"@semantic-release/git": "^11.0.1",
"@sentry/node": "^10.69.0",
"@types/node": "^24.0.0",
"@vitest/coverage-v8": "^3.0.0",
"oxlint": "^1.0.0",
+1217 -849
View File
File diff suppressed because it is too large Load Diff
+27 -9
View File
@@ -1,16 +1,34 @@
const releaseUsername = process.env.GITEA_REGISTRY_USERNAME;
const releaseToken = process.env.GITEA_RELEASE_TOKEN;
const repositoryUrl =
releaseUsername && releaseToken
? `https://${encodeURIComponent(releaseUsername)}:${encodeURIComponent(releaseToken)}@git.mifi.dev/mifi/logger.git`
: 'https://git.mifi.dev/mifi/logger.git';
/**
* Default Angular preset rejects `feat!` / `fix!` headers entirely (no release).
* These parser options match Conventional Commits so `!` becomes a BREAKING CHANGE note.
*/
const conventionalCommitParserOpts = {
headerPattern: /^(\w*)(?:\((.*)\))?!?: (.*)$/,
breakingHeaderPattern: /^(\w*)(?:\((.*)\))?!: (.*)$/,
noteKeywords: ['BREAKING CHANGE', 'BREAKING-CHANGE'],
};
module.exports = {
branches: ["main"],
tagFormat: "v${version}",
branches: ['main'],
repositoryUrl,
tagFormat: 'v${version}',
plugins: [
"@semantic-release/commit-analyzer",
"@semantic-release/release-notes-generator",
["@semantic-release/changelog", { changelogFile: "CHANGELOG.md" }],
"@semantic-release/npm",
['@semantic-release/commit-analyzer', { parserOpts: conventionalCommitParserOpts }],
['@semantic-release/release-notes-generator', { parserOpts: conventionalCommitParserOpts }],
['@semantic-release/changelog', { changelogFile: 'CHANGELOG.md' }],
'@semantic-release/npm',
[
"@semantic-release/git",
'@semantic-release/git',
{
assets: ["CHANGELOG.md", "package.json", "pnpm-lock.yaml"],
message: "chore(release): ${nextRelease.version} [skip ci]\n\n${nextRelease.notes}",
assets: ['CHANGELOG.md', 'package.json', 'pnpm-lock.yaml'],
message: 'chore(release): ${nextRelease.version} [skip ci]\n\n${nextRelease.notes}',
},
],
],
+36
View File
@@ -0,0 +1,36 @@
/**
* Severity threshold for log filtering, ordered from most to least verbose.
*
* | Level | Meaning |
* |-----------|----------------------------------------------|
* | `trace` | Extremely detailed diagnostics |
* | `debug` | Development diagnostics |
* | `info` | Routine operational messages |
* | `warn` | Unexpected but recoverable conditions |
* | `error` | Failures that need attention |
* | `silent` | Suppresses all console-bound output |
*
* A logger emits events at or above its configured threshold (e.g. `warn`
* allows `warn` and `error`).
*/
export enum LogLevel {
TRACE = 'trace',
DEBUG = 'debug',
FATAL = 'fatal',
INFO = 'info',
LOG = 'log',
WARN = 'warn',
WARNING = 'warning',
ERROR = 'error',
SILENT = 'silent',
}
/**
* Deployment stage used to pick a default log level when none is configured
* explicitly or via runtime overrides.
*/
export enum LoggerEnvironment {
DEVELOPMENT = 'development',
STAGING = 'staging',
PRODUCTION = 'production',
}
+26 -2
View File
@@ -1,2 +1,26 @@
export * from "./logger.js";
export * from "./types.js";
/**
* @mifi/logger — intentional, namespaced logging for browser and Node.js.
*
* @packageDocumentation
*
* @example
* ```ts
* import { createLogger } from "@mifi/logger";
*
* const logger = createLogger({ environment: "development", namespace: "APP" });
* logger.info("started");
* ```
*/
export * from './constants';
export * from './logger';
export * from './sinks/console';
export type {
LogLevel,
LoggerEnvironment,
LoggerOptions,
Logger,
LogData,
LogCallOptions,
LogEvent,
LogSink,
} from './types';
+288 -101
View File
@@ -1,37 +1,125 @@
import { createConsoleSink } from './sinks/console';
import type {
LogData,
LogCallOptions,
LogEvent,
Logger,
LoggerEnvironment,
LoggerOptions,
LogLevel,
LogSink,
} from "./types.js";
} from './types';
const LEVELS: readonly Exclude<LogLevel, "silent">[] = ["trace", "debug", "info", "warn", "error"];
/** Duck-type for sinks created by `createSentrySink` (avoids importing the sentry entry). */
type SentrySinkLike = LogSink & {
kind: 'sentry';
options: { logs?: boolean; logLevel?: LogLevel };
};
function isSentrySinkLike(sink: LogSink): sink is SentrySinkLike {
return 'kind' in sink && (sink as { kind?: unknown }).kind === 'sentry';
}
const LEVELS: readonly Exclude<LogLevel, 'silent'>[] = ['trace', 'debug', 'info', 'warn', 'error'];
const LOG_CALL_OPTION_KEYS = new Set(['sentry', 'suppressSentry']);
/** Numeric rank for comparing levels; `silent` is above every emit level. */
const levelRank = (level: LogLevel): number =>
level === "silent" ? Infinity : LEVELS.indexOf(level);
const defaultLevel = (environment: LoggerEnvironment): LogLevel =>
environment === "development" ? "trace" : environment === "staging" ? "warn" : "error";
level === 'silent' ? Infinity : LEVELS.indexOf(level);
/** Parses `debug` or `debug:WIDGET,API`, used by browser and container overrides. */
/**
* Default {@link LogLevel} for a {@link LoggerEnvironment} when no override is set.
*
* @param environment - Deployment stage.
* @returns `trace` (development), `warn` (staging), or `error` (production).
*/
const defaultLevel = (environment: LoggerEnvironment): LogLevel =>
environment === 'development' ? 'trace' : environment === 'staging' ? 'warn' : 'error';
/**
* Default Sentry Logs threshold when `createSentrySink(..., { logs: true })` is
* used without an explicit `logLevel`.
*
* @param environment - Deployment stage.
* @returns `info` (staging) or `warn` (production). Development never sends.
*/
export const defaultSentryLogLevel = (environment: LoggerEnvironment): LogLevel =>
environment === 'staging' ? 'info' : 'warn';
/**
* Parses a runtime logging override string used by browser session storage and
* container env composition.
*
* Accepted forms:
* - `"debug"` — set level only (all namespaces)
* - `"debug:WIDGET,API"` — set level and restrict to matching namespaces
* (exact match or descendant, e.g. `WIDGET` matches `WIDGET:Button`)
*
* @param value - Raw override string, or `null`/`undefined` when unset.
* @returns Parsed level and namespace filters, or `undefined` if invalid/empty.
*
* @example
* ```ts
* parseLoggingOverride("debug");
* // → { level: "debug", namespaces: [] }
*
* parseLoggingOverride("warn:WIDGET, API");
* // → { level: "warn", namespaces: ["WIDGET", "API"] }
*
* parseLoggingOverride("verbose");
* // → undefined
* ```
*/
export function parseLoggingOverride(
value: string | null | undefined,
): { level: LogLevel; namespaces: readonly string[] } | undefined {
if (!value) return undefined;
const [rawLevel, rawNamespaces = ""] = value.trim().split(":", 2);
if (!(["trace", "debug", "info", "warn", "error", "silent"] as string[]).includes(rawLevel))
const [rawLevel, rawNamespaces = ''] = value.trim().split(':', 2);
if (!(['trace', 'debug', 'info', 'warn', 'error', 'silent'] as string[]).includes(rawLevel))
return undefined;
return {
level: rawLevel as LogLevel,
namespaces: rawNamespaces
.split(",")
.split(',')
.map((item) => item.trim())
.filter(Boolean),
};
}
function resolveStorage(provided?: Pick<Storage, "getItem">): Pick<Storage, "getItem"> | undefined {
/**
* Whether a value is a trailing {@link LogCallOptions} object (only known keys).
*
* @param value - Candidate last argument from a log call.
*/
export function isLogCallOptions(value: unknown): value is LogCallOptions {
if (!value || typeof value !== 'object' || Array.isArray(value) || value instanceof Error)
return false;
const keys = Object.keys(value);
return keys.length > 0 && keys.every((key) => LOG_CALL_OPTION_KEYS.has(key));
}
/**
* Splits trailing {@link LogCallOptions} from log arguments.
*
* @param arguments_ - Raw call arguments.
* @returns Remaining arguments and parsed options (defaults to `{}`).
*/
function splitLogCallArguments(arguments_: readonly unknown[]): {
arguments: readonly unknown[];
options: LogCallOptions;
} {
if (arguments_.length === 0) return { arguments: arguments_, options: {} };
const last = arguments_[arguments_.length - 1];
if (!isLogCallOptions(last)) return { arguments: arguments_, options: {} };
return { arguments: arguments_.slice(0, -1), options: last };
}
/**
* Resolves session storage for browser overrides.
*
* @param provided - Optional storage; when omitted, uses `globalThis.sessionStorage`.
* @returns A `getItem`-compatible storage, or `undefined` if unavailable.
*/
function resolveStorage(provided?: Pick<Storage, 'getItem'>): Pick<Storage, 'getItem'> | undefined {
if (provided) return provided;
try {
return globalThis.sessionStorage;
@@ -40,6 +128,12 @@ function resolveStorage(provided?: Pick<Storage, "getItem">): Pick<Storage, "get
}
}
/**
* Resolves the environment variable map for Node/container overrides.
*
* @param provided - Optional map; when omitted, uses `process.env` if present.
* @returns A string-keyed env map (may be empty).
*/
function resolveEnv(
provided?: Record<string, string | undefined>,
): Record<string, string | undefined> {
@@ -50,11 +144,26 @@ function resolveEnv(
);
}
function resolveRuntime(provided?: "browser" | "node"): "browser" | "node" {
/**
* Resolves whether the logger is running in a browser or Node-like runtime.
*
* @param provided - Explicit runtime; when omitted, inferred from `globalThis.window`.
* @returns `"browser"` if `window` is defined, otherwise `"node"`.
*/
function resolveRuntime(provided?: 'browser' | 'node'): 'browser' | 'node' {
if (provided) return provided;
return typeof (globalThis as { window?: unknown }).window === "undefined" ? "node" : "browser";
return typeof (globalThis as { window?: unknown }).window === 'undefined' ? 'node' : 'browser';
}
/**
* Whether a logger namespace matches any of the configured filters.
*
* Empty `filters` means “match all”. Otherwise the namespace must equal a
* filter or start with `filter:`.
*
* @param namespace - Logger namespace, if any.
* @param filters - Namespace prefixes from a runtime override.
*/
function namespaceMatches(namespace: string | undefined, filters: readonly string[]): boolean {
return (
filters.length === 0 ||
@@ -65,57 +174,173 @@ function namespaceMatches(namespace: string | undefined, filters: readonly strin
);
}
/**
* Evaluates lazy log arguments: every argument after the first that is a
* zero-arg function is invoked; earlier arguments and non-functions are kept.
* Returned thenables are left as-is for {@link settleArguments}.
*
* @param arguments_ - Raw call arguments (message first, then optional data).
* @returns Arguments with lazy factories invoked (may still contain thenables).
*/
function evaluate(arguments_: readonly unknown[]): readonly unknown[] {
return arguments_.map((argument, index) =>
index > 0 && typeof argument === "function" ? (argument as () => LogData)() : argument,
index > 0 && typeof argument === 'function' ? (argument as () => unknown)() : argument,
);
}
/** Creates an intentional, Console-shaped logger. Functions passed after the message are evaluated lazily. */
/** Duck-type check for Promise-like values. */
function isThenable(value: unknown): value is PromiseLike<unknown> {
return (
value !== null &&
(typeof value === 'object' || typeof value === 'function') &&
typeof (value as { then?: unknown }).then === 'function'
);
}
/**
* Settles top-level thenables in evaluated arguments.
* Fulfilled values replace the thenable; rejection reasons replace rejected ones.
*/
async function settleArguments(arguments_: readonly unknown[]): Promise<readonly unknown[]> {
const settled = await Promise.allSettled(
arguments_.map((argument) => (isThenable(argument) ? argument : Promise.resolve(argument))),
);
return settled.map((result) => (result.status === 'fulfilled' ? result.value : result.reason));
}
function hasThenable(arguments_: readonly unknown[]): boolean {
return arguments_.some(isThenable);
}
/**
* Resolves Sentry sink options from `options.sentry` or a Sentry sink in `sinks`.
* Development always yields `undefined` (nothing is sent to Sentry).
*/
function resolveSentrySinkOptions(
options: LoggerOptions,
): { logs: boolean; logLevel: LogLevel } | undefined {
if (options.environment === 'development') return undefined;
const candidate = options.sentry ? options.sentry : options.sinks?.find(isSentrySinkLike);
if (!candidate) return undefined;
if (isSentrySinkLike(candidate)) {
return {
logs: Boolean(candidate.options.logs),
logLevel: candidate.options.logLevel ?? defaultSentryLogLevel(options.environment),
};
}
return { logs: false, logLevel: defaultSentryLogLevel(options.environment) };
}
/**
* Creates an intentional, Console-shaped logger with namespacing, lazy
* arguments, environment-aware defaults, and optional Sentry integration.
*
* **Console level precedence** (highest wins):
* 1. `options.level`
* 2. `sessionStorage.showLoggingFor` (browser)
* 3. `MIFI_LOG_LEVEL` + optional `MIFI_LOG_NAMESPACES` (Node/containers)
* 4. Default for `options.environment`
*
* **Default sinks** (when `options.sinks` is omitted):
* - Always include a console sink except production **browser** with Sentry.
* - In staging/production with `options.sentry`, include that sink.
* - Development never attaches or sends to Sentry.
*
* Functions passed after the first argument are evaluated lazily — only when
* the event is emitted — so expensive snapshots stay cheap when suppressed.
* Async factories and top-level Promises are settled before sinks run
* (fire-and-forget); such events set {@link LogEvent.async}.
*
* @param options - Logger configuration. See {@link LoggerOptions}.
* @returns A {@link Logger} instance.
*
* @example
* ```ts
* import { createLogger } from "@mifi/logger";
*
* const logger = createLogger({
* environment: "production",
* namespace: "API",
* });
*
* logger.error("Request failed", error);
* logger.debug("skipped in production", () => hugeObject());
* logger.debug("response", async () => ({ data: await res.json() }));
* logger.warn("investigate", { id: 1 }, { sentry: true });
* ```
*/
export function createLogger(options: LoggerOptions): Logger {
const namespace =
typeof options.namespace === "string"
typeof options.namespace === 'string'
? options.namespace
: options.namespace?.filter(Boolean).join(":");
: options.namespace?.filter(Boolean).join(':');
const env = resolveEnv(options.env);
const runtimeOverride =
parseLoggingOverride(resolveStorage(options.sessionStorage)?.getItem("showLoggingFor")) ??
parseLoggingOverride(resolveStorage(options.sessionStorage)?.getItem('showLoggingFor')) ??
parseLoggingOverride(
env.MIFI_LOG_LEVEL
? `${env.MIFI_LOG_LEVEL}${env.MIFI_LOG_NAMESPACES ? `:${env.MIFI_LOG_NAMESPACES}` : ""}`
? `${env.MIFI_LOG_LEVEL}${env.MIFI_LOG_NAMESPACES ? `:${env.MIFI_LOG_NAMESPACES}` : ''}`
: undefined,
);
const threshold = options.level ?? runtimeOverride?.level ?? defaultLevel(options.environment);
const runtime = resolveRuntime(options.runtime);
const sentrySinkOptions = resolveSentrySinkOptions(options);
const sentryActive = sentrySinkOptions !== undefined;
const sinks: readonly LogSink[] = options.sinks ?? [
...(runtime === "node" || options.environment !== "production" || !options.sentry
...(runtime === 'node' || options.environment !== 'production' || !options.sentry
? [createConsoleSink()]
: []),
...(options.environment === "production" && options.sentry ? [options.sentry] : []),
...(options.sentry && options.environment !== 'development' ? [options.sentry] : []),
];
const enabled = (level: Exclude<LogLevel, "silent">) =>
const enabled = (level: Exclude<LogLevel, 'silent'>) =>
levelRank(level) >= levelRank(threshold) &&
(!runtimeOverride?.namespaces.length ||
namespaceMatches(namespace, runtimeOverride.namespaces));
const emit = (level: Exclude<LogLevel, "silent">, arguments_: readonly unknown[]) => {
if (!enabled(level)) return;
const event: LogEvent = {
level,
namespace,
arguments: evaluate(arguments_),
timestamp: new Date(),
};
const deliver = (event: LogEvent) => {
sinks.forEach((sink) => sink.emit(event));
};
const emit = (level: Exclude<LogLevel, 'silent'>, arguments_: readonly unknown[]) => {
const split = splitLogCallArguments(arguments_);
const sendToConsole = enabled(level);
const sendToSentryIssue =
sentryActive && level === 'error' && !split.options.suppressSentry;
const sendToSentryLogs =
sentryActive &&
level !== 'error' &&
(Boolean(split.options.sentry) ||
(Boolean(sentrySinkOptions?.logs) &&
levelRank(level) >= levelRank(sentrySinkOptions.logLevel)));
if (!sendToConsole && !sendToSentryIssue && !sendToSentryLogs) return;
const timestamp = new Date();
const evaluated = evaluate(split.arguments);
const base = {
level,
namespace,
timestamp,
environment: options.environment,
sendToSentryLogs,
sendToSentryIssue,
sendToConsole,
};
if (!hasThenable(evaluated)) {
deliver({ ...base, arguments: evaluated });
return;
}
void settleArguments(evaluated)
.then((settled) => deliver({ ...base, arguments: settled, async: true }))
.catch(() => {
/* allSettled absorbs rejections; defensive against unexpected throw */
});
};
const consoleMethod = (
method: keyof Console | "profile" | "profileEnd",
level: Exclude<LogLevel, "silent">,
method: keyof Console | 'profile' | 'profileEnd',
level: Exclude<LogLevel, 'silent'>,
arguments_: readonly unknown[],
) => {
if (!enabled(level)) return;
const console_ = globalThis.console as Console & Record<string, unknown>;
const fn = console_[method];
if (typeof fn === "function")
if (typeof fn !== 'function') return;
(fn as (...items: unknown[]) => void).apply(
console_,
Array.from(prefix(namespace, evaluate(arguments_))),
@@ -125,79 +350,41 @@ export function createLogger(options: LoggerOptions): Logger {
namespace,
child: (child) =>
createLogger({ ...options, namespace: [namespace, child].filter(Boolean) as string[] }),
trace: (...items) => emit("trace", items),
debug: (...items) => emit("debug", items),
log: (...items) => emit("info", items),
info: (...items) => emit("info", items),
warn: (...items) => emit("warn", items),
error: (...items) => emit("error", items),
trace: (...items) => emit('trace', items),
debug: (...items) => emit('debug', items),
log: (...items) => emit('info', items),
info: (...items) => emit('info', items),
warn: (...items) => emit('warn', items),
error: (...items) => emit('error', items),
assert: (condition, ...items) => {
if (!condition) emit("error", ["Assertion failed", ...items]);
if (!condition) emit('error', ['Assertion failed', ...items]);
},
group: (...items) => consoleMethod("group", "info", items),
groupCollapsed: (...items) => consoleMethod("groupCollapsed", "info", items),
groupEnd: () => consoleMethod("groupEnd", "info", []),
dir: (item, options_) => consoleMethod("dir", "info", [item, options_]),
dirxml: (...items) => consoleMethod("dirxml", "info", items),
table: (data, properties) => consoleMethod("table", "info", [data, properties]),
clear: () => consoleMethod("clear", "info", []),
count: (label) => consoleMethod("count", "info", [label]),
countReset: (label) => consoleMethod("countReset", "info", [label]),
time: (label) => consoleMethod("time", "info", [label]),
timeLog: (label, ...items) => consoleMethod("timeLog", "info", [label, ...items]),
timeEnd: (label) => consoleMethod("timeEnd", "info", [label]),
timeStamp: (label) => consoleMethod("timeStamp", "info", [label]),
profile: (label) => consoleMethod("profile", "info", [label]),
profileEnd: (label) => consoleMethod("profileEnd", "info", [label]),
group: (...items) => consoleMethod('group', 'info', items),
groupCollapsed: (...items) => consoleMethod('groupCollapsed', 'info', items),
groupEnd: () => consoleMethod('groupEnd', 'info', []),
dir: (item, options_) => consoleMethod('dir', 'info', [item, options_]),
dirxml: (...items) => consoleMethod('dirxml', 'info', items),
table: (data, properties) => consoleMethod('table', 'info', [data, properties]),
clear: () => consoleMethod('clear', 'info', []),
count: (label) => consoleMethod('count', 'info', [label]),
countReset: (label) => consoleMethod('countReset', 'info', [label]),
time: (label) => consoleMethod('time', 'info', [label]),
timeLog: (label, ...items) => consoleMethod('timeLog', 'info', [label, ...items]),
timeEnd: (label) => consoleMethod('timeEnd', 'info', [label]),
timeStamp: (label) => consoleMethod('timeStamp', 'info', [label]),
profile: (label) => consoleMethod('profile', 'info', [label]),
profileEnd: (label) => consoleMethod('profileEnd', 'info', [label]),
};
return api;
}
/**
* Prepends a bracketed namespace label to console utility method arguments.
*
* @param namespace - Colon-joined namespace, if any.
* @param arguments_ - Evaluated log arguments.
* @returns Arguments with `[A][B]` prefix when namespaced.
*/
function prefix(namespace: string | undefined, arguments_: readonly unknown[]): readonly unknown[] {
return namespace ? [`[${namespace.split(":").join("][")}]`, ...arguments_] : arguments_;
}
const ANSI_RESET = "\u001B[0m";
const ANSI_BY_LEVEL: Record<Exclude<LogLevel, "silent">, string> = {
trace: "\u001B[90m",
debug: "\u001B[36m",
info: "\u001B[32m",
warn: "\u001B[33m",
error: "\u001B[31m",
};
const BROWSER_STYLE_BY_LEVEL: Record<Exclude<LogLevel, "silent">, string> = {
trace: "color: #6b7280; font-weight: 600",
debug: "color: #0891b2; font-weight: 600",
info: "color: #15803d; font-weight: 600",
warn: "color: #a16207; font-weight: 700",
error: "color: #dc2626; font-weight: 700",
};
function isBrowser(): boolean {
return typeof (globalThis as { window?: unknown }).window !== "undefined";
}
function supportsAnsi(): boolean {
return Boolean(
(globalThis as { process?: { stdout?: { isTTY?: boolean } } }).process?.stdout?.isTTY,
);
}
/** Default readable console destination. Node's `console.error` writes to stderr. */
export function createConsoleSink(): LogSink {
return {
emit: (event) => {
const method = event.level === "trace" ? "debug" : event.level;
const console_ = globalThis.console as Console & Record<string, unknown>;
const fn = console_[method];
if (typeof fn !== "function") return;
const label = event.namespace ? `[${event.namespace.split(":").join("][")}]` : "[LOG]";
const arguments_ = isBrowser()
? [`%c${label}`, BROWSER_STYLE_BY_LEVEL[event.level], ...event.arguments]
: supportsAnsi()
? [`${ANSI_BY_LEVEL[event.level]}${label}${ANSI_RESET}`, ...event.arguments]
: [label, ...event.arguments];
(fn as (...items: unknown[]) => void).apply(console_, arguments_);
},
};
return namespace ? [`[${namespace.split(':').join('][')}]`, ...arguments_] : arguments_;
}
+2 -37
View File
@@ -1,37 +1,2 @@
import type { LogEvent, LogSink } from "./types.js";
export interface SentryScopeLike {
setLevel(level: string): void;
setTag(key: string, value: string): void;
setExtras(extras: Record<string, unknown>): void;
}
export interface SentryLike {
withScope(callback: (scope: SentryScopeLike) => void): void;
captureException(error: Error): void;
captureMessage(message: string, level: string): void;
}
/** Creates an optional Sentry adapter without adding a Sentry SDK dependency to this package. */
export function createSentrySink(sentry: SentryLike): LogSink {
return {
emit(event: LogEvent) {
if (event.level !== "error") return;
const error = event.arguments.find((item): item is Error => item instanceof Error);
const extras = Object.fromEntries(
event.arguments
.filter((item) => item && typeof item === "object" && !(item instanceof Error))
.map((item, index) => [`context_${index}`, item]),
);
const message =
event.arguments.filter((item) => typeof item === "string").join(" ") ||
"Logger error";
sentry.withScope((scope) => {
scope.setLevel("error");
if (event.namespace) scope.setTag("logger.namespace", event.namespace);
scope.setExtras(extras);
if (error) sentry.captureException(error);
else sentry.captureMessage(message, "error");
});
},
};
}
/** Public entry for `@mifi/logger/sentry`. Implementation: `src/sinks/sentry.ts`. */
export * from './sinks/sentry';
+75
View File
@@ -0,0 +1,75 @@
import { LogLevel } from '../constants';
import type { LogSink } from '../types';
type ConsoleLogLevel =
`${Exclude<LogLevel, LogLevel.FATAL | LogLevel.LOG | LogLevel.SILENT | LogLevel.WARNING>}`;
const ANSI_RESET = '\u001B[0m';
const ANSI_BY_LEVEL: Record<ConsoleLogLevel, string> = {
trace: '\u001B[90m',
debug: '\u001B[36m',
info: '\u001B[32m',
warn: '\u001B[33m',
error: '\u001B[31m',
};
const BROWSER_STYLE_BY_LEVEL: Record<ConsoleLogLevel, string> = {
trace: 'color: #6b7280; font-weight: 600',
debug: 'color: #0891b2; font-weight: 600',
info: 'color: #15803d; font-weight: 600',
warn: 'color: #a16207; font-weight: 700',
error: 'color: #dc2626; font-weight: 700',
};
/** Whether the current global looks like a browser (`window` is defined). */
function isBrowser(): boolean {
return typeof (globalThis as { window?: unknown }).window !== 'undefined';
}
/** Whether Node stdout is a TTY that can display ANSI colors. */
function supportsAnsi(): boolean {
return Boolean(
(globalThis as { process?: { stdout?: { isTTY?: boolean } } }).process?.stdout?.isTTY,
);
}
/**
* Default readable console {@link LogSink}.
*
* - Skips events where `sendToConsole` is `false`.
* - Maps `trace` to `console.debug`.
* - Prefixes a styled namespace label (`[A][B]` or `[LOG]`), plus `[async]`
* when {@link LogEvent.async} is set.
* - Uses CSS `%c` styling in browsers and ANSI colors on Node TTYs.
* - Node `error` level uses `console.error` (stderr).
*
* @returns A sink suitable as the default destination or for custom sink lists.
*
* @example
* ```ts
* const logger = createLogger({
* environment: "development",
* sinks: [createConsoleSink(), customSink],
* });
* ```
*/
export function createConsoleSink(): LogSink {
return {
emit: (event) => {
if (!event.sendToConsole || event.level === LogLevel.SILENT) return;
const method = event.level === 'trace' ? 'debug' : event.level;
const console_ = globalThis.console as Console & Record<string, unknown>;
const fn = console_[method];
if (typeof fn !== 'function') return;
const labelBase = event.namespace
? `[${event.namespace.split(':').join('][')}]`
: '[LOG]';
const label = event.async ? `${labelBase}[async]` : labelBase;
const arguments_ = isBrowser()
? [`%c${label}`, BROWSER_STYLE_BY_LEVEL[event.level], ...event.arguments]
: supportsAnsi()
? [`${ANSI_BY_LEVEL[event.level]}${label}${ANSI_RESET}`, ...event.arguments]
: [label, ...event.arguments];
(fn as (...items: unknown[]) => void).apply(console_, arguments_);
},
};
}
+231
View File
@@ -0,0 +1,231 @@
import type { LogEvent, LogSink } from '../types';
import { LogLevel } from '../constants';
/**
* Sentry Issue severity levels (`@sentry/core` `SeverityLevel`).
* Note: Issues use `"warning"`; Logs use `"warn"`.
*/
export type SentrySeverityLevel =
`${Exclude<LogLevel, LogLevel.SILENT | LogLevel.TRACE | LogLevel.WARN>}`;
/**
* Options for {@link createSentrySink}.
*
* Sentry Logs are independent of the console level. Defaults when `logs` is
* enabled and `logLevel` is omitted: staging → `info`, production → `warn`.
* Development never sends (enforced by the logger).
*/
export interface SentrySinkOptions {
/**
* When `true`, non-error events at or above {@link SentrySinkOptions.logLevel}
* are written to `sentry.logger.*`. Errors still become Issues only.
*/
logs?: boolean;
/**
* Minimum level for automatic Sentry Logs delivery when {@link SentrySinkOptions.logs}
* is enabled. Per-call `{ sentry: true }` bypasses this threshold.
*/
logLevel?: Exclude<LogLevel, LogLevel.SILENT>;
}
/**
* Minimal Sentry scope surface required by {@link createSentrySink}.
* Satisfied by `@sentry/browser`, `@sentry/node`, `@sentry/nextjs`, etc.
*
* Method parameter types are intentionally aligned with Sentry's public API
* (contravariance) so `typeof Sentry` assigns to {@link SentryLike} without adapters.
*/
export interface SentryScopeLike {
/**
* Sets the severity for the event about to be captured.
* @param level - Sentry Issue severity (`"warning"`, not logger `"warn"`).
*/
setLevel(level: SentrySeverityLevel): void;
/**
* Attaches a string tag to the event.
* @param key - Tag name (this package uses `"logger.namespace"`).
* @param value - Tag value.
*/
setTag(key: string, value: string): void;
/**
* Attaches structured extras derived from non-Error object arguments.
* @param extras - Key/value map of searchable context.
*/
setExtras(extras: Record<string, unknown>): void;
}
/**
* Minimal `sentry.logger` surface for Sentry Logs.
* Optional on {@link SentryLike}; Logs are skipped when absent.
*/
export interface SentryLoggerApiLike {
trace(message: string, attributes?: Record<string, string | number | boolean>): void;
debug(message: string, attributes?: Record<string, string | number | boolean>): void;
info(message: string, attributes?: Record<string, string | number | boolean>): void;
warn(message: string, attributes?: Record<string, string | number | boolean>): void;
error(message: string, attributes?: Record<string, string | number | boolean>): void;
}
/**
* Minimal Sentry client surface required by {@link createSentrySink}.
* Pass your app's Sentry SDK module; this package does not depend on Sentry.
*
* Structural typing matches official `@sentry/*` exports — no consumer adapter needed.
*
* @example
* ```ts
* import * as Sentry from "@sentry/nextjs";
* import { createSentrySink } from "@mifi/logger/sentry";
*
* const sink = createSentrySink(Sentry, { logs: true });
* ```
*/
export interface SentryLike {
/**
* Runs `callback` with an isolated scope for tagging/extras.
* @param callback - Receives a {@link SentryScopeLike} to configure.
*/
withScope(callback: (scope: SentryScopeLike) => void): void;
/**
* Captures an `Error` instance as an exception event.
* @param error - The first `Error` found in the log arguments, if any.
*/
captureException(error: Error): void;
/**
* Captures a string message when no `Error` is present in the arguments.
* Second argument matches Sentry's optional severity / capture-context slot.
* @param message - Joined string arguments, or a fallback.
* @param captureContext - Issue severity (use {@link toSentrySeverity} mapping).
*/
captureMessage(message: string, captureContext?: SentrySeverityLevel): void | string;
/** Structured Logs API. Required when using `{ logs: true }` or `{ sentry: true }`. */
logger?: SentryLoggerApiLike;
}
/** Sink returned by {@link createSentrySink}. */
export interface SentrySink extends LogSink {
readonly kind: 'sentry';
readonly options: SentrySinkOptions;
}
/**
* Type guard for sinks created by {@link createSentrySink}.
*
* @param sink - Any {@link LogSink}.
*/
export function isSentrySink(sink: LogSink): sink is SentrySink {
return 'kind' in sink && (sink as { kind?: unknown }).kind === 'sentry';
}
/**
* Maps a logger level to a Sentry **Issue** {@link SentrySeverityLevel}.
*
* - `"warn"` → `"warning"` (Issues API; Logs keep `"warn"`)
* - `"trace"` → `"debug"` (closest Issue severity)
* - other levels map by name (`error`, `info`, `debug`)
*
* @param level - Logger emit level (never `silent`).
*/
export function toSentrySeverity(
level: `${Exclude<LogLevel, LogLevel.SILENT>}`,
): SentrySeverityLevel {
if (level === LogLevel.WARN) return LogLevel.WARNING;
if (level === LogLevel.TRACE) return LogLevel.DEBUG;
return level;
}
function isAttributeValue(value: unknown): value is string | number | boolean {
return typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean';
}
/**
* Builds a Sentry Logs message and flat primitive attributes from a log event.
*
* @param event - Emitted log event (call options already stripped from arguments).
*/
export function toSentryLogPayload(event: LogEvent): {
message: string;
attributes: Record<string, string | number | boolean>;
} {
const message =
event.arguments.filter((item) => typeof item === 'string').join(' ') || 'Log event';
const attributes: Record<string, string | number | boolean> = {};
if (event.namespace) attributes['logger.namespace'] = event.namespace;
if (event.async) attributes.async = true;
for (const item of event.arguments) {
if (!item || typeof item !== 'object' || item instanceof Error || Array.isArray(item))
continue;
for (const [key, value] of Object.entries(item as Record<string, unknown>)) {
if (isAttributeValue(value)) attributes[key] = value;
}
}
return { message, attributes };
}
/**
* Creates a {@link LogSink} that forwards events to a Sentry-compatible SDK
* without adding a Sentry dependency to `@mifi/logger`.
*
* Capture rules (flags are set by {@link createLogger}):
* - `sendToSentryIssue` → `captureException` / `captureMessage` (errors only).
* - `sendToSentryLogs` → `sentry.logger[level]` (non-errors; never doubles an Issue).
*
* Enable automatic Logs with `{ logs: true }`. Override the threshold with
* `logLevel` (defaults: staging `info`, production `warn`). Force a single
* event with `{ sentry: true }` on the log call. Suppress an Issue with
* `{ suppressSentry: true }`.
*
* Official `@sentry/node`, `@sentry/browser`, and `@sentry/nextjs` modules are
* assignable to {@link SentryLike} directly — no adapter object required.
*
* @param sentry - Any object implementing {@link SentryLike} (typically the Sentry SDK).
* @param options - Optional Logs configuration.
* @returns A sink to pass as `sentry` or inside `sinks` on {@link createLogger}.
*
* @example
* ```ts
* import * as Sentry from "@sentry/node";
* import { createLogger } from "@mifi/logger";
* import { createSentrySink } from "@mifi/logger/sentry";
*
* const logger = createLogger({
* environment: "production",
* namespace: "API",
* sentry: createSentrySink(Sentry, { logs: true }),
* });
*
* logger.error("Request failed", new Error("offline"), { requestId: "req_1" });
* logger.warn("slow", { ms: 1200 }); // → Sentry Logs in production when logs enabled
* logger.info("probe", { id: 1 }, { sentry: true }); // forced Logs
* logger.error("expected", err, { suppressSentry: true });
* ```
*/
export function createSentrySink(sentry: SentryLike, options: SentrySinkOptions = {}): SentrySink {
return {
kind: 'sentry',
options,
emit(event: LogEvent) {
if (event.environment === 'development') return;
if (event.level === LogLevel.SILENT) return;
if (event.sendToSentryIssue) {
const error = event.arguments.find((item): item is Error => item instanceof Error);
const { message, attributes } = toSentryLogPayload(event);
const severity = toSentrySeverity(event.level);
sentry.withScope((scope) => {
scope.setLevel(severity);
if (event.namespace) scope.setTag('logger.namespace', event.namespace);
scope.setExtras(attributes);
if (error) sentry.captureException(error);
else sentry.captureMessage(message, severity);
});
return;
}
if (!event.sendToSentryLogs || !sentry.logger) return;
const method = event.level === 'trace' ? 'trace' : event.level;
const log = sentry.logger[method as keyof SentryLoggerApiLike];
if (typeof log !== 'function') return;
const { message, attributes } = toSentryLogPayload(event);
log.call(sentry.logger, message, attributes);
},
};
}
+261 -19
View File
@@ -1,61 +1,303 @@
/** A severity threshold, ordered from most to least verbose. */
export type LogLevel = "trace" | "debug" | "info" | "warn" | "error" | "silent";
export type LoggerEnvironment = "development" | "staging" | "production";
export type LogData = unknown | (() => unknown);
import { LogLevel as LogLevelEnum, LoggerEnvironment as LoggerEnvironmentEnum } from './constants';
/** A structured event after its level policy has allowed it to be emitted. */
export interface LogEvent {
level: Exclude<LogLevel, "silent">;
namespace?: string;
arguments: readonly unknown[];
timestamp: Date;
/**
* Severity threshold for log filtering, ordered from most to least verbose.
*
* | Level | Meaning |
* |-----------|----------------------------------------------|
* | `trace` | Extremely detailed diagnostics |
* | `debug` | Development diagnostics |
* | `info` | Routine operational messages |
* | `warn` | Unexpected but recoverable conditions |
* | `error` | Failures that need attention |
* | `silent` | Suppresses all console-bound output |
*
* A logger emits events at or above its configured threshold (e.g. `warn`
* allows `warn` and `error`).
*/
export type LogLevel =
`${Exclude<LogLevelEnum, LogLevelEnum.FATAL | LogLevelEnum.LOG | LogLevelEnum.WARNING>}`;
/**
* Deployment stage used to pick a default log level when none is configured
* explicitly or via runtime overrides.
*
* Defaults:
* - `development` → `trace`
* - `staging` → `warn`
* - `production` → `error`
*/
export type LoggerEnvironment = `${LoggerEnvironmentEnum}`;
/**
* A value passed as a log argument after the message.
*
* Prefer a zero-argument function for expensive payloads: it is only invoked
* when the event is actually emitted, so suppressed logs avoid the work.
* The factory may be `async` or otherwise return a `Promise`; top-level
* thenables are settled before sinks see the event (fire-and-forget).
*
* @example
* ```ts
* logger.debug("state", () => expensiveSnapshot());
* logger.debug("response", async () => ({ data: await res.json() }));
* ```
*/
export type LogData = unknown | (() => unknown | Promise<unknown>);
/**
* Per-call options for `trace` / `debug` / `log` / `info` / `warn` / `error`
* (and `assert`). Not supported on console utilities such as `group`.
*
* When the last argument is a plain object whose keys are only these option
* names, it is treated as options rather than log data.
*/
export interface LogCallOptions {
/**
* Force this event to Sentry Logs, ignoring the Sentry Logs threshold.
* No-op for `error` (errors become Issues, not Logs) and in development.
*/
sentry?: boolean;
/**
* Skip creating a Sentry Issue for an `error`-level event.
* No-op at lower levels.
*/
suppressSentry?: boolean;
}
/** A destination for enabled log events. */
/**
* A structured log event after level and namespace policy have allowed it
* (or after it was selected for Sentry delivery).
*/
export interface LogEvent {
/** Severity of this event. Never `silent`. */
level: Exclude<LogLevel, LogLevelEnum.SILENT>;
/**
* Colon-joined namespace for this logger (e.g. `"WIDGET:Button"`).
* Omitted when the logger was created without a namespace.
*/
namespace?: string;
/**
* Evaluated arguments for the event (call options already stripped).
* Lazy factories have been invoked and top-level thenables settled;
* rejection reasons appear in place of rejected thenables.
*/
arguments: readonly unknown[];
/**
* Wall-clock time when the log call was made (before awaiting thenables).
*/
timestamp: Date;
/** Deployment stage from {@link LoggerOptions.environment}. */
environment: LoggerEnvironment;
/**
* `true` when the event should be written to Sentry Logs
* (`sentry.logger.*`), not as an Issue.
*/
sendToSentryLogs: boolean;
/**
* `true` when the event should be captured as a Sentry Issue
* (`captureException` / `captureMessage`).
*/
sendToSentryIssue: boolean;
/**
* `true` when the event passed the logger's level/namespace policy and
* should be rendered by console-oriented sinks.
*/
sendToConsole: boolean;
/**
* `true` when emit was deferred to settle top-level thenables.
* Omitted for fully synchronous emits. Console sinks render `[async]`.
*/
async?: boolean;
}
/**
* Destination that receives enabled {@link LogEvent}s.
*
* Provide custom sinks via {@link LoggerOptions.sinks}, or use
* {@link createConsoleSink} / `createSentrySink` from `@mifi/logger/sentry`.
*
* @example
* ```ts
* const sink: LogSink = {
* emit(event) {
* if (event.sendToConsole) analytics.track("log", event);
* },
* };
* ```
*/
export interface LogSink {
/**
* Handle a single log event.
* Implementations should respect `sendToConsole` / `sendToSentryLogs` /
* `sendToSentryIssue` as needed.
*/
emit(event: LogEvent): void;
}
/**
* Options for {@link createLogger}.
*
* Precedence for the effective console level (highest wins):
* 1. Explicit {@link LoggerOptions.level}
* 2. Browser `sessionStorage.showLoggingFor` (or {@link LoggerOptions.sessionStorage})
* 3. `MIFI_LOG_LEVEL` / `MIFI_LOG_NAMESPACES` from {@link LoggerOptions.env} or `process.env`
* 4. Default for {@link LoggerOptions.environment}
*/
export interface LoggerOptions {
/**
* Deployment stage. Selects the default log level when no override applies.
* @see LoggerEnvironment
*/
environment: LoggerEnvironment;
/**
* Optional namespace label(s). A string is used as-is; an array is joined
* with `:` (empty segments dropped). Shown in console output as
* `[A][B]` for `"A:B"`.
*
* @example
* ```ts
* createLogger({ environment: "development", namespace: "API" });
* createLogger({ environment: "development", namespace: ["WIDGET", "Button"] });
* ```
*/
namespace?: string | readonly string[];
/** Runtime used for the default destination policy. It is inferred when omitted. */
runtime?: "browser" | "node";
/** Hard override. It takes precedence over runtime environment defaults. */
/**
* Runtime used for the default destination policy (console vs Sentry-only
* in production browsers). Inferred from `globalThis.window` when omitted.
*/
runtime?: 'browser' | 'node';
/**
* Hard level override. Takes precedence over session storage, env vars,
* and environment defaults.
*/
level?: LogLevel;
/** Browser-only session override source; defaults to global sessionStorage when available. */
sessionStorage?: Pick<Storage, "getItem">;
/** Node/container environment source; defaults to process.env when available. */
/**
* Browser-only source for the `showLoggingFor` override key.
* Defaults to `globalThis.sessionStorage` when available.
*
* Expected value format matches {@link parseLoggingOverride}:
* `debug` or `debug:WIDGET,API`.
*/
sessionStorage?: Pick<Storage, 'getItem'>;
/**
* Node/container environment variable map. Defaults to `process.env`
* when available.
*
* Recognized keys:
* - `MIFI_LOG_LEVEL` — one of the {@link LogLevel} values
* - `MIFI_LOG_NAMESPACES` — optional comma-separated namespace filters
*/
env?: Record<string, string | undefined>;
/** Production error destination. Browser errors go only here; Node errors also go to stderr. */
/**
* Staging/production Sentry destination (typically from `createSentrySink`).
* Ignored in development (nothing is sent to Sentry).
*
* - Production **browser**: default sinks are Sentry only (no console).
* - Production **Node**: console (stderr for errors) and Sentry.
* - Staging: console and Sentry.
*
* Ignored when {@link LoggerOptions.sinks} is provided.
*/
sentry?: LogSink | false;
/** Complete destination override. When provided, `sentry` and default console behavior are not used. */
/**
* Complete destination list. When set, replaces the default console/Sentry
* policy entirely — {@link LoggerOptions.sentry} is not used.
*/
sinks?: readonly LogSink[];
}
/**
* Console-shaped logger with namespaces, lazy arguments, child loggers,
* and optional Sentry Issues / Logs delivery.
*
* Standard methods (`trace` … `error`) accept an optional trailing
* {@link LogCallOptions} object. Console utility methods (`group`, `time`,
* `table`, …) are gated by the same console policy and call through to
* `globalThis.console` when enabled — they do not accept {@link LogCallOptions}.
*
* @example
* ```ts
* const logger = createLogger({ environment: "development", namespace: "WIDGET" });
* logger.info("ready");
* logger.child("Button").debug("clicked", { id: 1 });
* logger.warn("investigate", { orderId }, { sentry: true });
* logger.error("expected", err, { suppressSentry: true });
* ```
*/
export interface Logger {
/**
* Colon-joined namespace for this instance, if any.
* Immutable; use {@link Logger.child} to nest further segments.
*/
readonly namespace?: string;
/**
* Returns a new logger that appends `namespace` to this logger's namespace.
*
* @param namespace - Segment to append (e.g. `"Button"` → `"WIDGET:Button"`).
* @returns A new {@link Logger} sharing the same options and sinks.
*
* @example
* ```ts
* const widget = createLogger({ environment: "development", namespace: "WIDGET" });
* const button = widget.child("Button"); // namespace === "WIDGET:Button"
* ```
*/
child(namespace: string): Logger;
/** Emit a `trace` event when the level policy allows it. */
trace(message?: unknown, data?: LogData, options?: LogCallOptions): void;
trace(...arguments_: readonly unknown[]): void;
/** Emit a `debug` event when the level policy allows it. */
debug(message?: unknown, data?: LogData, options?: LogCallOptions): void;
debug(...arguments_: readonly unknown[]): void;
/** Alias of {@link Logger.info}. */
log(message?: unknown, data?: LogData, options?: LogCallOptions): void;
log(...arguments_: readonly unknown[]): void;
/** Emit an `info` event when the level policy allows it. */
info(message?: unknown, data?: LogData, options?: LogCallOptions): void;
info(...arguments_: readonly unknown[]): void;
/** Emit a `warn` event when the level policy allows it. */
warn(message?: unknown, data?: LogData, options?: LogCallOptions): void;
warn(...arguments_: readonly unknown[]): void;
/** Emit an `error` event when the level policy allows it. */
error(message?: unknown, data?: LogData, options?: LogCallOptions): void;
error(...arguments_: readonly unknown[]): void;
/**
* When `condition` is falsy, emits an `error` with `"Assertion failed"`
* followed by any extra arguments (optional trailing {@link LogCallOptions}).
*
* @param condition - Truthy values pass silently.
* @param arguments_ - Extra context included with the failure event.
*/
assert(condition: unknown, ...arguments_: readonly unknown[]): void;
/** Starts a console group when the level policy allows `info`. */
group(...arguments_: readonly unknown[]): void;
/** Starts a collapsed console group when the level policy allows `info`. */
groupCollapsed(...arguments_: readonly unknown[]): void;
/** Ends the current console group when the level policy allows `info`. */
groupEnd(): void;
/** Logs an object with interactive inspection when the level policy allows `info`. */
dir(item?: unknown, options?: unknown): void;
/** Logs XML/HTML as an interactive tree when the level policy allows `info`. */
dirxml(...arguments_: readonly unknown[]): void;
/** Renders tabular data when the level policy allows `info`. */
table(tabularData?: unknown, properties?: readonly string[]): void;
/** Clears the console when the level policy allows `info`. */
clear(): void;
/** Increments a named counter when the level policy allows `info`. */
count(label?: string): void;
/** Resets a named counter when the level policy allows `info`. */
countReset(label?: string): void;
/** Starts a named timer when the level policy allows `info`. */
time(label?: string): void;
/** Logs elapsed time for a named timer when the level policy allows `info`. */
timeLog(label?: string, ...arguments_: readonly unknown[]): void;
/** Stops a named timer and logs elapsed time when the level policy allows `info`. */
timeEnd(label?: string): void;
/** Adds a timestamp marker to the performance timeline when allowed. */
timeStamp(label?: string): void;
/** Starts a CPU profile (where supported) when the level policy allows `info`. */
profile(label?: string): void;
/** Ends a CPU profile (where supported) when the level policy allows `info`. */
profileEnd(label?: string): void;
}
+40
View File
@@ -0,0 +1,40 @@
import { afterEach, describe, expect, it, vi } from 'vitest';
import { createConsoleSink } from '../src/index';
import type { LogEvent } from '../src/index';
function event(overrides: Partial<LogEvent> = {}): LogEvent {
return {
level: 'debug',
namespace: 'API',
arguments: ['hello'],
timestamp: new Date(),
environment: 'development',
sendToSentryLogs: false,
sendToSentryIssue: false,
sendToConsole: true,
...overrides,
};
}
describe('createConsoleSink', () => {
afterEach(() => {
vi.restoreAllMocks();
});
it('appends [async] to the namespace label when event.async is set', () => {
const debug = vi.spyOn(console, 'debug').mockImplementation(() => undefined);
createConsoleSink().emit(event({ async: true }));
expect(debug).toHaveBeenCalled();
const first = debug.mock.calls[0]?.[0];
expect(String(first)).toContain('[API][async]');
});
it('omits [async] for synchronous events', () => {
const debug = vi.spyOn(console, 'debug').mockImplementation(() => undefined);
createConsoleSink().emit(event());
expect(debug).toHaveBeenCalled();
const first = debug.mock.calls[0]?.[0];
expect(String(first)).toContain('[API]');
expect(String(first)).not.toContain('[async]');
});
});
+264 -50
View File
@@ -1,94 +1,308 @@
import { describe, expect, it, vi } from "vitest";
import { createLogger, parseLoggingOverride } from "../src/index.js";
import type { LogEvent, LogSink } from "../src/index.js";
import { describe, expect, it, vi } from 'vitest';
import { createLogger, isLogCallOptions, parseLoggingOverride } from '../src/index';
import type { LogEvent, LogSink } from '../src/index';
import { createSentrySink } from '../src/sentry';
function sink(): { sink: LogSink; events: LogEvent[] } {
const events: LogEvent[] = [];
return { events, sink: { emit: (event) => events.push(event) } };
}
describe("parseLoggingOverride", () => {
it("accepts a global level and a namespace-filtered level", () => {
expect(parseLoggingOverride("debug")).toEqual({ level: "debug", namespaces: [] });
expect(parseLoggingOverride("debug:WIDGET, API")).toEqual({
level: "debug",
namespaces: ["WIDGET", "API"],
describe('parseLoggingOverride', () => {
it('accepts a global level and a namespace-filtered level', () => {
expect(parseLoggingOverride('debug')).toEqual({ level: 'debug', namespaces: [] });
expect(parseLoggingOverride('debug:WIDGET, API')).toEqual({
level: 'debug',
namespaces: ['WIDGET', 'API'],
});
expect(parseLoggingOverride("verbose")).toBeUndefined();
expect(parseLoggingOverride('verbose')).toBeUndefined();
});
});
describe("createLogger", () => {
it("uses environment defaults and never evaluates suppressed lazy data", () => {
describe('isLogCallOptions', () => {
it('accepts only known option keys', () => {
expect(isLogCallOptions({ sentry: true })).toBe(true);
expect(isLogCallOptions({ suppressSentry: true })).toBe(true);
expect(isLogCallOptions({ sentry: true, suppressSentry: false })).toBe(true);
expect(isLogCallOptions({ requestId: 'req_1' })).toBe(false);
expect(isLogCallOptions({ sentry: true, requestId: 'req_1' })).toBe(false);
expect(isLogCallOptions({})).toBe(false);
});
});
describe('createLogger', () => {
it('uses environment defaults and never evaluates suppressed lazy data', () => {
const destination = sink();
const expensive = vi.fn(() => ({ huge: "snapshot" }));
const logger = createLogger({ environment: "production", sinks: [destination.sink] });
logger.debug("ignored", expensive);
logger.error("kept", expensive);
const expensive = vi.fn(() => ({ huge: 'snapshot' }));
const logger = createLogger({ environment: 'production', sinks: [destination.sink] });
logger.debug('ignored', expensive);
logger.error('kept', expensive);
expect(expensive).toHaveBeenCalledTimes(1);
expect(destination.events).toHaveLength(1);
expect(destination.events[0]?.arguments).toEqual(["kept", { huge: "snapshot" }]);
expect(destination.events[0]?.arguments).toEqual(['kept', { huge: 'snapshot' }]);
expect(destination.events[0]?.async).toBeUndefined();
});
it("applies session namespace filtering to namespace descendants", () => {
it('never starts suppressed async lazy factories', () => {
const destination = sink();
const storage = { getItem: () => "debug:WIDGET" };
createLogger({
environment: "production",
namespace: "WIDGET:Button",
sessionStorage: storage,
sinks: [destination.sink],
}).debug("shown");
createLogger({
environment: "production",
namespace: "API",
sessionStorage: storage,
sinks: [destination.sink],
}).debug("hidden");
expect(destination.events.map((event) => event.arguments[0])).toEqual(["shown"]);
const expensive = vi.fn(async () => ({ huge: 'snapshot' }));
const logger = createLogger({ environment: 'production', sinks: [destination.sink] });
logger.debug('ignored', expensive);
expect(expensive).not.toHaveBeenCalled();
expect(destination.events).toHaveLength(0);
});
it("builds immutable child namespaces and reports failed assertions as errors", () => {
it('settles async lazy factories before emitting and sets async', async () => {
const destination = sink();
const factory = vi.fn(async () => ({ data: 1 }));
const logger = createLogger({ environment: 'development', sinks: [destination.sink] });
logger.debug('response', factory);
expect(factory).toHaveBeenCalledTimes(1);
expect(destination.events).toHaveLength(0);
await vi.waitFor(() => expect(destination.events).toHaveLength(1));
expect(destination.events[0]).toMatchObject({
arguments: ['response', { data: 1 }],
async: true,
});
});
it('unwraps direct Promise arguments and keeps rejection reasons', async () => {
const destination = sink();
const reason = new Error('boom');
const logger = createLogger({ environment: 'development', sinks: [destination.sink] });
logger.error('failed', { id: 1 }, Promise.reject(reason));
expect(destination.events).toHaveLength(0);
await vi.waitFor(() => expect(destination.events).toHaveLength(1));
expect(destination.events[0]).toMatchObject({
arguments: ['failed', { id: 1 }, reason],
async: true,
});
});
it('applies session namespace filtering to namespace descendants', () => {
const destination = sink();
const storage = { getItem: () => 'debug:WIDGET' };
createLogger({
environment: 'production',
namespace: 'WIDGET:Button',
sessionStorage: storage,
sinks: [destination.sink],
}).debug('shown');
createLogger({
environment: 'production',
namespace: 'API',
sessionStorage: storage,
sinks: [destination.sink],
}).debug('hidden');
expect(destination.events.map((event) => event.arguments[0])).toEqual(['shown']);
});
it('builds immutable child namespaces and reports failed assertions as errors', () => {
const destination = sink();
const root = createLogger({
environment: "development",
namespace: "WIDGET",
environment: 'development',
namespace: 'WIDGET',
sinks: [destination.sink],
});
root.child("Button").assert(false, "missing label");
expect(root.namespace).toBe("WIDGET");
root.child('Button').assert(false, 'missing label');
expect(root.namespace).toBe('WIDGET');
expect(destination.events[0]).toMatchObject({
level: "error",
namespace: "WIDGET:Button",
arguments: ["Assertion failed", "missing label"],
level: 'error',
namespace: 'WIDGET:Button',
arguments: ['Assertion failed', 'missing label'],
});
});
it("sends production browser errors to Sentry without writing to the console", () => {
it('sends production browser errors to Sentry without writing to the console', () => {
const destination = sink();
const consoleError = vi.spyOn(console, "error").mockImplementation(() => undefined);
const consoleError = vi.spyOn(console, 'error').mockImplementation(() => undefined);
const logger = createLogger({
environment: "production",
runtime: "browser",
environment: 'production',
runtime: 'browser',
sentry: destination.sink,
});
logger.error("captured");
logger.error('captured');
expect(destination.events).toHaveLength(1);
expect(destination.events[0]).toMatchObject({
sendToSentryIssue: true,
sendToSentryLogs: false,
sendToConsole: true,
});
expect(consoleError).not.toHaveBeenCalled();
consoleError.mockRestore();
});
it("keeps production Node errors on stderr as well as sending them to Sentry", () => {
it('forces selected events to Sentry Logs without writing them to the console', () => {
const destination = sink();
const consoleError = vi.spyOn(console, "error").mockImplementation(() => undefined);
const consoleInfo = vi.spyOn(console, 'info').mockImplementation(() => undefined);
const logger = createLogger({
environment: "production",
runtime: "node",
environment: 'production',
runtime: 'browser',
sentry: destination.sink,
});
logger.error("captured");
logger.info('Cache warmed', { sentry: true });
expect(destination.events).toHaveLength(1);
expect(destination.events[0]).toMatchObject({
level: 'info',
arguments: ['Cache warmed'],
sendToSentryLogs: true,
sendToSentryIssue: false,
sendToConsole: false,
});
expect(consoleInfo).not.toHaveBeenCalled();
consoleInfo.mockRestore();
});
it('strips trailing call options from event arguments and supports data plus options', () => {
const destination = sink();
const logger = createLogger({
environment: 'production',
runtime: 'browser',
sentry: destination.sink,
});
logger.warn('slow', { ms: 1200 }, { sentry: true });
expect(destination.events[0]).toMatchObject({
level: 'warn',
arguments: ['slow', { ms: 1200 }],
sendToSentryLogs: true,
sendToConsole: false,
});
});
it('suppresses Sentry Issues when suppressSentry is set', () => {
const destination = sink();
const logger = createLogger({
environment: 'production',
runtime: 'browser',
sentry: destination.sink,
});
logger.error('expected', new Error('nope'), { suppressSentry: true });
expect(destination.events).toHaveLength(1);
expect(destination.events[0]).toMatchObject({
sendToSentryIssue: false,
sendToSentryLogs: false,
arguments: ['expected', expect.any(Error)],
});
});
it('never marks events for Sentry in development', () => {
const destination = sink();
const logger = createLogger({
environment: 'development',
sinks: [
destination.sink,
createSentrySink(
{
withScope: (callback) =>
callback({
setLevel: () => undefined,
setTag: () => undefined,
setExtras: () => undefined,
}),
captureException: vi.fn(),
captureMessage: vi.fn(),
logger: {
trace: vi.fn(),
debug: vi.fn(),
info: vi.fn(),
warn: vi.fn(),
error: vi.fn(),
},
},
{ logs: true },
),
],
});
logger.error('local only');
logger.info('probe', { sentry: true });
expect(destination.events).toHaveLength(2);
expect(
destination.events.every(
(event) => !event.sendToSentryIssue && !event.sendToSentryLogs,
),
).toBe(true);
});
it('keeps production Node errors on stderr as well as sending them to Sentry', () => {
const destination = sink();
const consoleError = vi.spyOn(console, 'error').mockImplementation(() => undefined);
const logger = createLogger({
environment: 'production',
runtime: 'node',
sentry: destination.sink,
});
logger.error('captured');
expect(destination.events).toHaveLength(1);
expect(consoleError).toHaveBeenCalledTimes(1);
consoleError.mockRestore();
});
it('mirrors warn to Sentry Logs in production when logs are enabled on the sink', () => {
const destination = sink();
const logger = createLogger({
environment: 'production',
runtime: 'browser',
sinks: [
destination.sink,
createSentrySink(
{
withScope: () => undefined,
captureException: vi.fn(),
captureMessage: vi.fn(),
logger: {
trace: vi.fn(),
debug: vi.fn(),
info: vi.fn(),
warn: vi.fn(),
error: vi.fn(),
},
},
{ logs: true },
),
],
});
logger.warn('noisy');
logger.info('below default production logs threshold');
expect(destination.events).toHaveLength(1);
expect(destination.events[0]).toMatchObject({
level: 'warn',
sendToSentryLogs: true,
sendToConsole: false,
});
});
it('mirrors info to Sentry Logs in staging when logs are enabled', () => {
const destination = sink();
const logger = createLogger({
environment: 'staging',
runtime: 'browser',
sinks: [
destination.sink,
createSentrySink(
{
withScope: () => undefined,
captureException: vi.fn(),
captureMessage: vi.fn(),
logger: {
trace: vi.fn(),
debug: vi.fn(),
info: vi.fn(),
warn: vi.fn(),
error: vi.fn(),
},
},
{ logs: true },
),
],
});
logger.info('visible in staging logs');
logger.debug('still below staging logs threshold');
expect(destination.events.map((event) => event.arguments[0])).toEqual([
'visible in staging logs',
]);
expect(destination.events[0]).toMatchObject({
sendToSentryLogs: true,
sendToConsole: false,
});
});
});
+30
View File
@@ -0,0 +1,30 @@
/**
* Compile-time regression: official Sentry SDKs must assign to {@link SentryLike}
* without casts or consumer adapters. Checked by `pnpm check` (`tsc --noEmit`).
*/
import * as Sentry from '@sentry/node';
import { createSentrySink, type SentryLike } from '../src/sentry';
const _sdk: SentryLike = Sentry;
createSentrySink(Sentry);
createSentrySink(Sentry, { logs: true });
const stub: SentryLike = {
withScope: (callback) =>
callback({
setLevel: () => undefined,
setTag: () => undefined,
setExtras: () => undefined,
}),
captureException: () => undefined,
captureMessage: () => undefined,
logger: {
trace: () => undefined,
debug: () => undefined,
info: () => undefined,
warn: () => undefined,
error: () => undefined,
},
};
createSentrySink(stub);
createSentrySink(stub, { logs: true });
+182 -13
View File
@@ -1,25 +1,194 @@
import { describe, expect, it, vi } from "vitest";
import { createLogger } from "../src/index.js";
import { createSentrySink } from "../src/sentry.js";
import { describe, expect, it, vi } from 'vitest';
import { createLogger, type LogEvent } from '../src/index';
import { createSentrySink, toSentryLogPayload, toSentrySeverity } from '../src/sentry';
describe("createSentrySink", () => {
it("captures errors with namespace and structured context, but ignores warnings", () => {
function createFakeSentry() {
const scope = { setLevel: vi.fn(), setTag: vi.fn(), setExtras: vi.fn() };
const sentry = {
return {
scope,
sentry: {
withScope: (callback: (value: typeof scope) => void) => callback(scope),
captureException: vi.fn(),
captureMessage: vi.fn(),
logger: {
trace: vi.fn(),
debug: vi.fn(),
info: vi.fn(),
warn: vi.fn(),
error: vi.fn(),
},
},
};
}
function issueEvent(overrides: Partial<LogEvent> = {}): LogEvent {
return {
level: 'error',
arguments: ['message'],
timestamp: new Date(),
environment: 'production',
sendToSentryLogs: false,
sendToSentryIssue: true,
sendToConsole: false,
...overrides,
};
}
describe('toSentrySeverity', () => {
it('maps logger levels to Sentry Issue severities', () => {
expect(toSentrySeverity('warn')).toBe('warning');
expect(toSentrySeverity('trace')).toBe('debug');
expect(toSentrySeverity('error')).toBe('error');
expect(toSentrySeverity('info')).toBe('info');
expect(toSentrySeverity('debug')).toBe('debug');
});
});
describe('toSentryLogPayload', () => {
it('joins string messages and flattens primitive object attributes', () => {
expect(
toSentryLogPayload({
level: 'info',
namespace: 'API',
arguments: ['Cache warmed', { entries: 42, ok: true, nested: { a: 1 } }],
timestamp: new Date(),
environment: 'production',
sendToSentryLogs: true,
sendToSentryIssue: false,
sendToConsole: false,
}),
).toEqual({
message: 'Cache warmed',
attributes: {
'logger.namespace': 'API',
entries: 42,
ok: true,
},
});
});
it('includes async when the event was deferred for thenables', () => {
expect(
toSentryLogPayload({
level: 'debug',
arguments: ['response'],
timestamp: new Date(),
environment: 'development',
sendToSentryLogs: true,
sendToSentryIssue: false,
sendToConsole: true,
async: true,
}).attributes,
).toEqual({ async: true });
});
});
describe('createSentrySink', () => {
it('captures errors as Issues with namespace and structured attributes', () => {
const { scope, sentry } = createFakeSentry();
const logger = createLogger({
environment: "production",
namespace: "API",
environment: 'production',
namespace: 'API',
sinks: [createSentrySink(sentry)],
});
const error = new Error("offline");
logger.warn("ignored");
logger.error("Request failed", error, { requestId: "req_1" });
const error = new Error('offline');
logger.warn('ignored without logs');
logger.error('Request failed', error, { requestId: 'req_1' });
expect(sentry.captureException).toHaveBeenCalledWith(error);
expect(scope.setTag).toHaveBeenCalledWith("logger.namespace", "API");
expect(scope.setExtras).toHaveBeenCalledWith({ context_0: { requestId: "req_1" } });
expect(sentry.captureMessage).not.toHaveBeenCalled();
expect(sentry.logger.info).not.toHaveBeenCalled();
expect(scope.setLevel).toHaveBeenCalledWith('error');
expect(scope.setTag).toHaveBeenCalledWith('logger.namespace', 'API');
expect(scope.setExtras).toHaveBeenCalledWith({
'logger.namespace': 'API',
requestId: 'req_1',
});
});
it('writes non-error events to Sentry Logs when enabled, not as Issues', () => {
const { sentry } = createFakeSentry();
const logger = createLogger({
environment: 'production',
namespace: 'API',
sinks: [createSentrySink(sentry, { logs: true })],
});
logger.warn('slow', { ms: 1200 });
logger.info('forced', { id: 1 }, { sentry: true });
expect(sentry.captureMessage).not.toHaveBeenCalled();
expect(sentry.captureException).not.toHaveBeenCalled();
expect(sentry.logger.warn).toHaveBeenCalledWith('slow', {
'logger.namespace': 'API',
ms: 1200,
});
expect(sentry.logger.info).toHaveBeenCalledWith('forced', {
'logger.namespace': 'API',
id: 1,
});
});
it('does not create an Issue when suppressSentry is set', () => {
const { sentry } = createFakeSentry();
const logger = createLogger({
environment: 'production',
runtime: 'node',
sinks: [createSentrySink(sentry, { logs: true })],
});
logger.error('expected', new Error('nope'), { suppressSentry: true });
expect(sentry.captureException).not.toHaveBeenCalled();
expect(sentry.logger.error).not.toHaveBeenCalled();
});
it('never sends in development', () => {
const { sentry } = createFakeSentry();
const logger = createLogger({
environment: 'development',
sinks: [createSentrySink(sentry, { logs: true })],
});
logger.error('local', new Error('x'));
logger.warn('local warn', { sentry: true });
expect(sentry.captureException).not.toHaveBeenCalled();
expect(sentry.logger.warn).not.toHaveBeenCalled();
});
it('maps warn → warning on the Issues path and keeps warn on the Logs path', () => {
const { scope, sentry } = createFakeSentry();
const sink = createSentrySink(sentry, { logs: true });
sink.emit(
issueEvent({
level: 'warn',
arguments: ['degraded'],
}),
);
expect(scope.setLevel).toHaveBeenCalledWith('warning');
expect(sentry.captureMessage).toHaveBeenCalledWith('degraded', 'warning');
expect(sentry.logger.warn).not.toHaveBeenCalled();
sink.emit({
level: 'warn',
namespace: 'API',
arguments: ['slow', { ms: 10 }],
timestamp: new Date(),
environment: 'production',
sendToSentryLogs: true,
sendToSentryIssue: false,
sendToConsole: false,
});
expect(sentry.logger.warn).toHaveBeenCalledWith('slow', {
'logger.namespace': 'API',
ms: 10,
});
});
it('maps error Issue severity as error', () => {
const { scope, sentry } = createFakeSentry();
createSentrySink(sentry).emit(
issueEvent({
level: 'error',
arguments: ['failed'],
}),
);
expect(scope.setLevel).toHaveBeenCalledWith('error');
expect(sentry.captureMessage).toHaveBeenCalledWith('failed', 'error');
});
});
+3 -4
View File
@@ -1,13 +1,12 @@
{
"compilerOptions": {
"target": "ES2024",
"module": "NodeNext",
"moduleResolution": "NodeNext",
"module": "ESNext",
"moduleResolution": "bundler",
"strict": true,
"declaration": true,
"verbatimModuleSyntax": true,
"skipLibCheck": true,
"ignoreDeprecations": "6.0"
"skipLibCheck": true
},
"include": ["src", "test", "tsup.config.ts", "vitest.config.ts"]
}
+11 -5
View File
@@ -1,10 +1,16 @@
import { defineConfig } from "tsup";
import { defineConfig } from 'tsup';
export default defineConfig({
entry: { index: "src/index.ts", sentry: "src/sentry.ts" },
format: ["esm", "cjs"],
dts: true,
entry: { index: 'src/index.ts', sentry: 'src/sentry.ts' },
format: ['esm', 'cjs'],
// tsup injects baseUrl for DTS; TS 6 treats that as an error until tsup stops
// (https://github.com/egoist/tsup/issues/1388)
dts: {
compilerOptions: {
ignoreDeprecations: '6.0',
},
},
clean: true,
target: "es2022",
target: 'es2022',
sourcemap: true,
});
+2 -2
View File
@@ -1,5 +1,5 @@
import { defineConfig } from "vitest/config";
import { defineConfig } from 'vitest/config';
export default defineConfig({
test: { environment: "node", coverage: { provider: "v8", reporter: ["text", "html"] } },
test: { environment: 'node', coverage: { provider: 'v8', reporter: ['text', 'html'] } },
});