Skip to content

🐸 Rybbit - open-source and privacy-friendly alternative to Google Analytics that is 10x more intuitive.

Refactor logging implementation and update dependencies

Bill Yangc497d780fe13
diff --git a/server/package-lock.json b/server/package-lock.json
index 13a84b359..beb73370d 100644
--- a/server/package-lock.json
+++ b/server/package-lock.json
@@ -9,13 +9,11 @@
"version": "2.7.0",
"dependencies": {
"@aws-sdk/client-s3": "^3.842.0",
- "@axiomhq/pino": "^1.3.1",
"@better-auth/api-key": "^1.6.23",
"@better-auth/infra": "^0.1.12",
"@better-auth/sso": "^1.6.23",
"@clickhouse/client": "1.11.1",
"@fastify/cors": "11.2.0",
- "@fastify/one-line-logger": "2.1.0",
"@fastify/rate-limit": "^10.3.0",
"@fastify/static": "9.1.3",
"@maxmind/geoip2-node": "6.1.0",
@@ -37,6 +35,7 @@
"node-cache": "^5.1.2",
"node-cron": "4.0.6",
"pg": "8.16.0",
+ "pino": "^9.14.0",
"postgres": "3.4.5",
"psl": "^1.15.0",
"puppeteer": "^24.34.0",
@@ -1004,32 +1003,6 @@
"node": ">=18.0.0"
}
},
- "node_modules/@axiomhq/js": {
- "version": "1.3.1",
- "resolved": "https://registry.npmjs.org/@axiomhq/js/-/js-1.3.1.tgz",
- "integrity": "sha512-Ytf5V3wKz8FKNiqJxnqZmUhjgJ7TItKUoyHVNE/H2V9dN1ozD6NNnsueenOjKdA48cm2sGRyP432nworst18aA==",
- "license": "MIT",
- "dependencies": {
- "fetch-retry": "^6.0.0",
- "uuid": "^11.0.2"
- },
- "engines": {
- "node": ">=16"
- }
- },
- "node_modules/@axiomhq/pino": {
- "version": "1.3.1",
- "resolved": "https://registry.npmjs.org/@axiomhq/pino/-/pino-1.3.1.tgz",
- "integrity": "sha512-zf6p2rU+b5XAk8Nj6EdjqdXTCuWQlf+C8UGdumD9xbtDWBYvk/EYkxXKMqK8mo2Gp+Fi+p5eHgjuOtbeop2XBQ==",
- "license": "MIT",
- "dependencies": {
- "@axiomhq/js": "1.3.1",
- "pino-abstract-transport": "^1.2.0"
- },
- "engines": {
- "node": ">=16"
- }
- },
"node_modules/@babel/code-frame": {
"version": "7.27.1",
"resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.27.1.tgz",
@@ -2481,25 +2454,6 @@
"dequal": "^2.0.3"
}
},
- "node_modules/@fastify/one-line-logger": {
- "version": "2.1.0",
- "resolved": "https://registry.npmjs.org/@fastify/one-line-logger/-/one-line-logger-2.1.0.tgz",
- "integrity": "sha512-4ERTaeuF9lSv0FNPc2HDs+69ybdhieJQXiVtcRpGMArRRei9plTy2Ifxjv2a2OcI1EGhSaQtUJwYvzOBVnZr5A==",
- "funding": [
- {
- "type": "github",
- "url": "https://github.com/sponsors/fastify"
- },
- {
- "type": "opencollective",
- "url": "https://opencollective.com/fastify"
- }
- ],
- "license": "MIT",
- "dependencies": {
- "pino-pretty": "^13.0.0"
- }
- },
"node_modules/@fastify/proxy-addr": {
"version": "5.1.0",
"resolved": "https://registry.npmjs.org/@fastify/proxy-addr/-/proxy-addr-5.1.0.tgz",
@@ -4943,18 +4897,6 @@
"integrity": "sha512-b5o1I6aLNeYlU/3CPlj/Z91ybk1gUsKT+5NAJI+2W4UjvS5KLG28K9v5UvNoFVjHV8PajVZ00RH3vnjyQO7ZAw==",
"license": "MIT"
},
- "node_modules/abort-controller": {
- "version": "3.0.0",
- "resolved": "https://registry.npmjs.org/abort-controller/-/abort-controller-3.0.0.tgz",
- "integrity": "sha512-h8lQ8tacZYnR3vNQTgibj+tODHI5/+l06Au2Pcriv/Gmet0eaj4TwWH41sO9wnHDiQsEj19q0drzdWdeAHtweg==",
- "license": "MIT",
- "dependencies": {
- "event-target-shim": "^5.0.0"
- },
- "engines": {
- "node": ">=6.5"
- }
- },
"node_modules/abstract-logging": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/abstract-logging/-/abstract-logging-2.0.1.tgz",
@@ -5564,30 +5506,6 @@
"node": ">=8"
}
},
- "node_modules/buffer": {
- "version": "6.0.3",
- "resolved": "https://registry.npmjs.org/buffer/-/buffer-6.0.3.tgz",
- "integrity": "sha512-FTiCpNxtwiZZHEZbcbTIcZjERVICn9yq/pDFkTl95/AxzD1naBctN7YO68riM/gLSDY7sdrMby8hofADYuuqOA==",
- "funding": [
- {
- "type": "github",
- "url": "https://github.com/sponsors/feross"
- },
- {
- "type": "patreon",
- "url": "https://www.patreon.com/feross"
- },
- {
- "type": "consulting",
- "url": "https://feross.org/support"
- }
- ],
- "license": "MIT",
- "dependencies": {
- "base64-js": "^1.3.1",
- "ieee754": "^1.2.1"
- }
- },
"node_modules/buffer-crc32": {
"version": "0.2.13",
"resolved": "https://registry.npmjs.org/buffer-crc32/-/buffer-crc32-0.2.13.tgz",
@@ -5855,6 +5773,7 @@
"version": "2.0.20",
"resolved": "https://registry.npmjs.org/colorette/-/colorette-2.0.20.tgz",
"integrity": "sha512-IfEDxwoWIjkeXL1eXcDiow4UbKjhLdq6/EuSVR9GMN7KVH3r9gQ83e73hsz1Nd1T3ijd5xv1wcWRYO+D6kCI2w==",
+ "dev": true,
"license": "MIT"
},
"node_modules/combined-stream": {
@@ -6037,6 +5956,7 @@
"version": "4.6.3",
"resolved": "https://registry.npmjs.org/dateformat/-/dateformat-4.6.3.tgz",
"integrity": "sha512-2P0p0pFGzHS5EMnhdxQi7aJN+iMheud0UhG4dlE1DLAlvL8JHjJJTX/CSm4JXwV0Ka5nGk3zC5mcb5bUQUxxMA==",
+ "dev": true,
"license": "MIT",
"engines": {
"node": "*"
@@ -6703,24 +6623,6 @@
"node": ">= 0.6"
}
},
- "node_modules/event-target-shim": {
- "version": "5.0.1",
- "resolved": "https://registry.npmjs.org/event-target-shim/-/event-target-shim-5.0.1.tgz",
- "integrity": "sha512-i/2XbnSz/uxRCU6+NdVJgKWDTM427+MqYbkQzD321DuCQJUqOuJKIA0IM2+W2xtYHdKOmZ4dR6fExsd4SXL+WQ==",
- "license": "MIT",
- "engines": {
- "node": ">=6"
- }
- },
- "node_modules/events": {
- "version": "3.3.0",
- "resolved": "https://registry.npmjs.org/events/-/events-3.3.0.tgz",
- "integrity": "sha512-mQw+2fkQbALzQ7V0MY0IqdnXNOeTtP4r0lN9z7AAawCXgqea7bDii20AYrIBrFd/Hx0M2Ocz6S111CaFkUcb0Q==",
- "license": "MIT",
- "engines": {
- "node": ">=0.8.x"
- }
- },
"node_modules/events-universal": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/events-universal/-/events-universal-1.0.1.tgz",
@@ -6889,6 +6791,7 @@
"version": "4.0.1",
"resolved": "https://registry.npmjs.org/fast-copy/-/fast-copy-4.0.1.tgz",
"integrity": "sha512-+uUOQlhsaswsizHFmEFAQhB3lSiQ+lisxl50N6ZP0wywlZeWsIESxSi9ftPEps8UGfiBzyYP7x27zA674WUvXw==",
+ "dev": true,
"license": "MIT"
},
"node_modules/fast-decode-uri-component": {
@@ -6963,6 +6866,7 @@
"version": "2.1.1",
"resolved": "https://registry.npmjs.org/fast-safe-stringify/-/fast-safe-stringify-2.1.1.tgz",
"integrity": "sha512-W+KJc2dmILlPplD/H4K9l9LcAHAfPtP6BY84uVLXQ6Evcz9Lcg33Y2z1IVblT6xdY54PXYVHEv+0Wpq8Io6zkA==",
+ "dev": true,
"license": "MIT"
},
"node_modules/fast-uri": {
@@ -7110,12 +7014,6 @@
}
}
},
- "node_modules/fetch-retry": {
- "version": "6.0.0",
- "resolved": "https://registry.npmjs.org/fetch-retry/-/fetch-retry-6.0.0.tgz",
- "integrity": "sha512-BUFj1aMubgib37I3v4q78fYo63Po7t4HUPTpQ6/QE6yK6cIQrP+W43FYToeTEyg5m2Y7eFUtijUuAv/PDlWuag==",
- "license": "MIT"
- },
"node_modules/fill-range": {
"version": "7.1.1",
"resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.1.1.tgz",
@@ -7443,6 +7341,7 @@
"version": "5.0.0",
"resolved": "https://registry.npmjs.org/help-me/-/help-me-5.0.0.tgz",
"integrity": "sha512-7xgomUX6ADmcYzFik0HzAxh/73YlKR9bmFzf51CZwR+b6YtzU2m0u49hQCqV6SvlqIqsaxovfwdvbnsw3b/zpg==",
+ "dev": true,
"license": "MIT"
},
"node_modules/hono": {
@@ -7797,6 +7696,7 @@
"version": "3.1.1",
"resolved": "https://registry.npmjs.org/joycon/-/joycon-3.1.1.tgz",
"integrity": "sha512-34wB/Y7MW7bzjKRjUKTa46I2Z7eV62Rkhva+KkopW7Qvv/OSWBqvkSY7vusOPrNuZcUG3tApvdVgNB8POj3SPw==",
+ "dev": true,
"license": "MIT",
"engines": {
"node": ">=10"
@@ -8953,20 +8853,11 @@
"pino": "bin.js"
}
},
- "node_modules/pino-abstract-transport": {
- "version": "1.2.0",
- "resolved": "https://registry.npmjs.org/pino-abstract-transport/-/pino-abstract-transport-1.2.0.tgz",
- "integrity": "sha512-Guhh8EZfPCfH+PMXAb6rKOjGQEoy0xlAIn+irODG5kgfYV+BQ0rGYYWTIel3P5mmyXqkYkPmdIkywsn6QKUR1Q==",
- "license": "MIT",
- "dependencies": {
- "readable-stream": "^4.0.0",
- "split2": "^4.0.0"
- }
- },
"node_modules/pino-pretty": {
"version": "13.1.3",
"resolved": "https://registry.npmjs.org/pino-pretty/-/pino-pretty-13.1.3.tgz",
"integrity": "sha512-ttXRkkOz6WWC95KeY9+xxWL6AtImwbyMHrL1mSwqwW9u+vLp/WIElvHvCSDg0xO/Dzrggz1zv3rN5ovTRVowKg==",
+ "dev": true,
"license": "MIT",
"dependencies": {
"colorette": "^2.0.7",
@@ -8991,6 +8882,7 @@
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/pino-abstract-transport/-/pino-abstract-transport-3.0.0.tgz",
"integrity": "sha512-wlfUczU+n7Hy/Ha5j9a/gZNy7We5+cXp8YL+X+PG8S0KXxw7n/JXA3c46Y0zQznIJ83URJiwy7Lh56WLokNuxg==",
+ "dev": true,
"license": "MIT",
"dependencies": {
"split2": "^4.0.0"
@@ -9168,15 +9060,6 @@
"node": ">=6"
}
},
- "node_modules/process": {
- "version": "0.11.10",
- "resolved": "https://registry.npmjs.org/process/-/process-0.11.10.tgz",
- "integrity": "sha512-cdGef/drWFoydD1JsMzuFf8100nZl+GT+yacc2bEced5f9Rjk4z+WtFUTBu9PhOi9j/jfmBPu0mMEY4wIdAF8A==",
- "license": "MIT",
- "engines": {
- "node": ">= 0.6.0"
- }
- },
"node_modules/process-warning": {
"version": "5.0.0",
"resolved": "https://registry.npmjs.org/process-warning/-/process-warning-5.0.0.tgz",
@@ -9475,22 +9358,6 @@
"integrity": "sha512-bCK/2Z4zLidyB4ReuIsvALH6w31YfAQDmXMqMx6FyfHqvBxtjC0eRumeSu4Bs3XtXwpyIywtSTrVT99BxY1f9w==",
"license": "MIT"
},
- "node_modules/readable-stream": {
- "version": "4.7.0",
- "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-4.7.0.tgz",
- "integrity": "sha512-oIGGmcpTLwPga8Bn6/Z75SVaH1z5dUut2ibSyAMVhmUggWpmDn2dapB0n7f8nwaSiRtepAsfJyfXIO5DCVAODg==",
- "license": "MIT",
- "dependencies": {
- "abort-controller": "^3.0.0",
- "buffer": "^6.0.3",
- "events": "^3.3.0",
- "process": "^0.11.10",
- "string_decoder": "^1.3.0"
- },
- "engines": {
- "node": "^12.22.0 || ^14.17.0 || >=16.0.0"
- }
- },
"node_modules/real-require": {
"version": "0.2.0",
"resolved": "https://registry.npmjs.org/real-require/-/real-require-0.2.0.tgz",
@@ -10246,6 +10113,7 @@
"version": "5.0.3",
"resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-5.0.3.tgz",
"integrity": "sha512-1tB5mhVo7U+ETBKNf92xT4hrQa3pm0MZ0PQvuDnWgAAGHDsfp4lPSpiS6psrSiet87wyGPh9ft6wmhOMQ0hDiw==",
+ "dev": true,
"license": "MIT",
"engines": {
"node": ">=14.16"
diff --git a/server/package.json b/server/package.json
index 2ffa08f51..91dbabb3c 100644
--- a/server/package.json
+++ b/server/package.json
@@ -30,13 +30,11 @@
},
"dependencies": {
"@aws-sdk/client-s3": "^3.842.0",
- "@axiomhq/pino": "^1.3.1",
"@better-auth/api-key": "^1.6.23",
"@better-auth/infra": "^0.1.12",
"@better-auth/sso": "^1.6.23",
"@clickhouse/client": "1.11.1",
"@fastify/cors": "11.2.0",
- "@fastify/one-line-logger": "2.1.0",
"@fastify/rate-limit": "^10.3.0",
"@fastify/static": "9.1.3",
"@maxmind/geoip2-node": "6.1.0",
@@ -58,6 +56,7 @@
"node-cache": "^5.1.2",
"node-cron": "4.0.6",
"pg": "8.16.0",
+ "pino": "^9.14.0",
"postgres": "3.4.5",
"psl": "^1.15.0",
"puppeteer": "^24.34.0",
diff --git a/server/src/index.ts b/server/src/index.ts
index 9d41827a1..e9bd1a9bf 100644
--- a/server/src/index.ts
+++ b/server/src/index.ts
@@ -174,6 +174,7 @@ import { mcpRoutes } from "./mcp/index.js";
import { oauthWellKnownRoutes } from "./mcp/wellKnown.js";
import { createCorsOptionsDelegate, createRejectUntrustedOriginHook } from "./lib/cors.js";
import { IS_CLOUD } from "./lib/const.js";
+import { logger } from "./lib/logger/logger.js";
import { reengagementService } from "./services/reengagement/reengagementService.js";
import { telemetryService } from "./services/telemetryService.js";
import { handleIdentify } from "./services/tracker/identifyService.js";
@@ -262,35 +263,7 @@ const __dirname = dirname(__filename);
const server = Fastify({
disableRequestLogging: true,
- logger: {
- level: "debug",
- transport: {
- target: "pino-pretty",
- level: process.env.LOG_LEVEL || "debug",
- options: {
- colorize: true,
- singleLine: true,
- translateTime: "HH:MM:ss",
- ignore: "pid,hostname,name",
- destination: 1, // stdout
- },
- },
- serializers: {
- req(request) {
- return {
- method: request.method,
- url: request.url,
- path: request.url,
- parameters: request.params,
- };
- },
- res(reply) {
- return {
- statusCode: reply.statusCode,
- };
- },
- },
- },
+ loggerInstance: logger,
maxParamLength: 1500,
trustProxy: true,
bodyLimit: 10 * 1024 * 1024, // 10MB limit for session replay data
diff --git a/server/src/lib/logger/LOGGING.md b/server/src/lib/logger/LOGGING.md
index 75ae5d8af..46d3d118e 100644
--- a/server/src/lib/logger/LOGGING.md
+++ b/server/src/lib/logger/LOGGING.md
@@ -1,30 +1,26 @@
-# Logging Guide for Frogstats Backend
+# Rybbit Server Logging
-## Overview
+## Runtime
-This Fastify backend uses Pino for structured JSON logging. In production, logs are formatted as single-line JSON for easy parsing. In development, logs are pretty-printed for readability.
+`logger.ts` owns the server's logging policy and constructs one shared Pino root per process. Fastify receives that root through `loggerInstance`; background modules create children from the same root with `createServiceLogger`.
-## Configuration
+| Environment | Default level | Output |
+| ---------------------- | ------------- | ------------------------------------------ |
+| `production` | `info` | newline-delimited JSON on stdout |
+| `development` or unset | `debug` | colorized single-line `pino-pretty` output |
+| `test` | `silent` | disabled unless `LOG_LEVEL` is set |
-Logging is configured in `src/index.ts` when creating the Fastify instance:
+`LOG_LEVEL` overrides the default in every environment. Supported Pino levels are `trace`, `debug`, `info`, `warn`, `error`, `fatal`, and `silent`.
-- **Production**: Uses `@fastify/one-line-logger` for compact JSON logs
-- **Development**: Uses `pino-pretty` for colorized, human-readable output
-- **Log Level**: Set via `LOG_LEVEL` env var (defaults to "debug" in dev, "info" in prod)
+## Fastify Requests
-## Usage Patterns
-
-### 1. Route Handlers
-
-In route handlers, use `request.log`:
+Use `request.log` in route handlers. Fastify binds the request ID to this child logger, which makes related events searchable together.
```typescript
export async function getUsers(request: FastifyRequest, reply: FastifyReply) {
- request.log.info("Fetching users");
-
try {
const users = await fetchUsers();
- request.log.debug({ userCount: users.length }, "Users fetched successfully");
+ request.log.debug({ userCount: users.length }, "Users fetched");
return users;
} catch (error) {
request.log.error(error, "Failed to fetch users");
@@ -33,127 +29,56 @@ export async function getUsers(request: FastifyRequest, reply: FastifyReply) {
}
```
-### 2. Services and Classes
+Automatic Fastify request logging is currently disabled. Do not assume that every request produces a completion or duration event.
-Import the logger utility and create a child logger:
+## Background Modules
+
+Create a named child from the shared root:
```typescript
import { createServiceLogger } from "../../lib/logger/logger.js";
-export class MyService {
- private logger = createServiceLogger("my-service");
+const logger = createServiceLogger("weekly-report");
- async doSomething() {
- this.logger.info("Starting operation");
- // ...
- }
-}
+logger.info({ organizationId }, "Starting weekly report");
```
-### 3. Server-level Logging
-
-Use `server.log` for server-wide events:
-
-```typescript
-server.log.info("Server started on port 3001");
-server.log.error(error, "Shutdown error");
-```
-
-## Log Levels
-
-Use appropriate levels for different scenarios:
-
-- `fatal`: Application is unusable, will exit
-- `error`: Error conditions (exceptions, failures)
-- `warn`: Warning conditions (deprecations, recoverable issues)
-- `info`: Informational messages (startup, shutdown, major operations)
-- `debug`: Debug information (detailed operation info)
-- `trace`: Very detailed trace information
-
-## Best Practices
-
-1. **Structure your logs**: Pass objects as the first parameter for structured data
-
- ```typescript
- logger.info({ userId: 123, action: "login" }, "User logged in");
- ```
-
-2. **Include context**: Add relevant data to help with debugging
-
- ```typescript
- request.log.info({ monitorId, region }, "Running health check");
- ```
-
-3. **Log errors properly**: Pass error as first param for proper stack traces
+The `service` field is included in structured output and remains visible in development output.
- ```typescript
- logger.error(error, "Operation failed");
- ```
+## Process Events
-4. **Avoid sensitive data**: Never log passwords, tokens, or PII
+Use the shared `logger` for process-wide work such as cluster startup. Use `server.log` for Fastify lifecycle work. They share the same root and output policy.
- ```typescript
- logger.info({ userId: user.id }, "User authenticated"); // Good
- logger.info({ user }, "User authenticated"); // Bad - might contain password
- ```
+## Event Shape
-5. **Use child loggers**: Create scoped loggers for services/modules
- ```typescript
- const logger = parentLogger.child({ service: "uptime" });
- ```
+Prefer stable structured fields over interpolation:
-## Migration from console.log
-
-Replace console statements with appropriate logger calls:
-
-- `console.log()` β†’ `logger.info()`
-- `console.error()` β†’ `logger.error()`
-- `console.warn()` β†’ `logger.warn()`
-- `console.debug()` β†’ `logger.debug()`
-
-### Migration Progress
-
-βœ… **Completed Services:**
-
-- All uptime monitoring services (monitorExecutor, monitorScheduler, regionHealthChecker, notificationService)
-- Core services (usageService, telemetryService, sessionsService)
-- Storage service (r2StorageService)
-- Main server file (index.ts)
-
-⏳ **Remaining:**
-
-- API endpoints (stripe webhook, session replay, admin routes)
-- Library files (auth, twilio, etc.)
-- Request validation services
+```typescript
+logger.info({ monitorId, region }, "Running monitor check");
+```
-## Environment Variables
+For exceptions, pass the error directly or use Pino's `err` key:
-- `LOG_LEVEL`: Set the minimum log level (trace, debug, info, warn, error, fatal)
-- `NODE_ENV`: Determines log format (production vs development)
+```typescript
+logger.error(error, "Monitor check failed");
+logger.error({ err: error, monitorId }, "Monitor check failed");
+```
-## Example Service Refactoring
+Do not use `{ error }`: Pino does not apply its Error serializer to that key, so native errors become empty objects.
-Before:
+## Redaction
-```typescript
-console.log("Service starting...");
-console.error("Failed to connect:", error);
-```
+The shared runtime redacts common credentials, authentication headers, cookies, and structured AppSumo license fields. Redaction only applies to structured fields at configured paths; it cannot remove sensitive values interpolated into message strings.
-After:
+Never log passwords, tokens, cookies, authentication headers, raw credentials, or full user records. Keep email addresses, phone numbers, prompts, queries, and request payloads out of logs unless the operational need and retention policy are explicit.
-```typescript
-import { createServiceLogger } from "../../lib/logger/logger.js";
+## Legacy Calls
-class MyService {
- private logger = createServiceLogger("my-service");
+Direct `console` logging still exists in the server. New and modified code should use:
- start() {
- this.logger.info("Service starting...");
- }
+- `request.log` for request-bound work
+- `server.log` for Fastify lifecycle work
+- `createServiceLogger` for background modules
+- `logger` for process-wide work
- handleError(error: Error) {
- this.logger.error(error, "Failed to connect");
- }
-}
-```
+Migrating existing `console` calls and adding HTTP lifecycle events are separate refactors from the shared runtime.
diff --git a/server/src/lib/logger/logger.test.ts b/server/src/lib/logger/logger.test.ts
new file mode 100644
index 000000000..d72c7a03c
--- /dev/null
+++ b/server/src/lib/logger/logger.test.ts
@@ -0,0 +1,106 @@
+import type { LoggerOptions } from "pino";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+const { childLogger, childMock, pinoMock, rootLogger } = vi.hoisted(() => {
+ const childLogger = { kind: "child" };
+ const childMock = vi.fn(() => childLogger);
+ const rootLogger = { child: childMock };
+ const pinoMock = vi.fn((_options: LoggerOptions) => rootLogger);
+
+ return { childLogger, childMock, pinoMock, rootLogger };
+});
+
+vi.mock("pino", () => ({ pino: pinoMock }));
+
+const originalNodeEnv = process.env.NODE_ENV;
+const originalLogLevel = process.env.LOG_LEVEL;
+
+async function importLogger(nodeEnv: string, logLevel = "") {
+ process.env.NODE_ENV = nodeEnv;
+ process.env.LOG_LEVEL = logLevel;
+ vi.resetModules();
+ pinoMock.mockClear();
+ childMock.mockClear();
+
+ const loggerModule = await import("./logger.js");
+ const options = pinoMock.mock.calls[0]?.[0];
+ if (!options) throw new Error("Logging runtime did not create the root logger");
+
+ return { loggerModule, options };
+}
+
+beforeEach(() => {
+ process.env.LOG_LEVEL = "";
+});
+
+afterEach(() => {
+ if (originalNodeEnv === undefined) delete process.env.NODE_ENV;
+ else process.env.NODE_ENV = originalNodeEnv;
+
+ if (originalLogLevel === undefined) delete process.env.LOG_LEVEL;
+ else process.env.LOG_LEVEL = originalLogLevel;
+});
+
+describe("logging runtime", () => {
+ it("uses structured info logging in production", async () => {
+ const { options } = await importLogger("production");
+
+ expect(options).toMatchObject({
+ name: "rybbit",
+ level: "info",
+ redact: { censor: "[REDACTED]" },
+ });
+ expect(options).not.toHaveProperty("transport");
+ });
+
+ it("uses readable debug logging in development", async () => {
+ const { options } = await importLogger("development");
+
+ expect(options).toMatchObject({
+ level: "debug",
+ transport: {
+ target: "pino-pretty",
+ options: { colorize: true, singleLine: true, destination: 1 },
+ },
+ });
+ });
+
+ it("is silent by default in tests", async () => {
+ const { options } = await importLogger("test");
+
+ expect(options).toMatchObject({ level: "silent" });
+ expect(options).not.toHaveProperty("transport");
+ });
+
+ it("lets LOG_LEVEL override the environment default", async () => {
+ const { options } = await importLogger("production", "warn");
+
+ expect(options).toMatchObject({ level: "warn" });
+ });
+
+ it("creates background children from the shared root", async () => {
+ const { loggerModule } = await importLogger("test");
+
+ expect(loggerModule.createServiceLogger("uptime")).toBe(childLogger);
+ expect(childMock).toHaveBeenCalledWith({ service: "uptime" });
+ });
+
+ it("keeps request and response serialization in the shared runtime", async () => {
+ const { options } = await importLogger("production");
+
+ expect(
+ options.serializers?.req({
+ method: "GET",
+ url: "/api/sites/1",
+ params: { siteId: 1 },
+ headers: { authorization: "secret" },
+ })
+ ).toEqual({
+ method: "GET",
+ url: "/api/sites/1",
+ path: "/api/sites/1",
+ parameters: { siteId: 1 },
+ });
+ expect(options.serializers?.res({ statusCode: 204 })).toEqual({ statusCode: 204 });
+ });
+});
diff --git a/server/src/lib/logger/logger.ts b/server/src/lib/logger/logger.ts
index 72cb57cae..08706a8a0 100644
--- a/server/src/lib/logger/logger.ts
+++ b/server/src/lib/logger/logger.ts
@@ -1,21 +1,80 @@
+import "dotenv/config";
+
import type { FastifyBaseLogger } from "fastify";
-import { pino } from "pino";
+import { pino, type LoggerOptions } from "pino";
+
+const REDACTED_LOG_PATHS = [
+ "authorization",
+ "cookie",
+ "password",
+ "token",
+ "accessToken",
+ "refreshToken",
+ "apiKey",
+ "secret",
+ "headers.authorization",
+ "headers.cookie",
+ "req.headers.authorization",
+ "req.headers.cookie",
+ "request.headers.authorization",
+ "request.headers.cookie",
+ "*.password",
+ "*.token",
+ "*.accessToken",
+ "*.refreshToken",
+ "*.apiKey",
+ "*.secret",
+ "payload.license_key",
+ "payload.prev_license_key",
+ "payload.parent_license_key",
+] as const;
+
+function defaultLogLevel(): string {
+ if (process.env.NODE_ENV === "production") return "info";
+ if (process.env.NODE_ENV === "test") return "silent";
+ return "debug";
+}
-export const createLogger = (name: string): FastifyBaseLogger => {
- return pino({
+function createLogger(name: string): FastifyBaseLogger {
+ const options: LoggerOptions = {
name,
- level: process.env.LOG_LEVEL || "debug",
- transport: {
+ level: process.env.LOG_LEVEL || defaultLogLevel(),
+ redact: {
+ paths: [...REDACTED_LOG_PATHS],
+ censor: "[REDACTED]",
+ },
+ serializers: {
+ req(request) {
+ return {
+ method: request.method,
+ url: request.url,
+ path: request.url,
+ parameters: request.params,
+ };
+ },
+ res(reply) {
+ return {
+ statusCode: reply.statusCode,
+ };
+ },
+ },
+ };
+
+ if (process.env.NODE_ENV !== "production" && process.env.NODE_ENV !== "test") {
+ options.transport = {
target: "pino-pretty",
options: {
colorize: true,
singleLine: true,
translateTime: "HH:MM:ss",
ignore: "pid,hostname,name",
+ destination: 1,
},
- },
- }) as FastifyBaseLogger;
-};
+ };
+ }
+
+ return pino(options) as FastifyBaseLogger;
+}
export const logger = createLogger("rybbit");