Skip to content
Back to skills

Loglayer Rules

ASecurity

Team conventions for logging in a TypeScript app through LogLayer and Pino: one module logger per file, constant messages with values in withMetadata, errors through withError and logged once, levels, redaction, the request id, stdout in production. Use when adding, fixing or reviewing logging, or wiring the logger. Background knowledge that agents preload or load on demand; not a command.

  • 2 stars
  • 0 votes
  • 0 copies
  • 2 views
  • Added December 1, 2026
developmenttypescriptgonextjsnodeapi

Works with

  • cli
  • api

Security analysis

A100/100

Pro scans all 2 files and shows the line behind each finding

Scanned December 1, 2026

npx -y skills add JanSzewczyk/claude-plugins --skill loglayer-rules --agent claude-code

Installs into .claude/skills of the current project.

Are you the author of Loglayer Rules?

Add the live security badge to your README. It updates with every re-scan.

Security grade badge for Loglayer Rules
[![Security: A — Skills Directory](https://www.skillsdirectory.com/api/skills/janszewczyk-loglayer-rules/badge)](https://www.skillsdirectory.com/skills/janszewczyk-loglayer-rules)

More formats (shields.io, HTML) on the badges page. Keep it an A: scan every change in CI with Pro.

Download with Pro
SKILL.md
---
name: loglayer-rules
description: "Team conventions for logging in a TypeScript app through LogLayer and Pino: one module logger per file, constant messages with values in withMetadata, errors through withError and logged once, levels, redaction, the request id, stdout in production. Use when adding, fixing or reviewing logging, or wiring the logger. Background knowledge that agents preload or load on demand; not a command."
user-invocable: false
---

<!-- generated by knowledge.mjs from 13 note(s) (sha256 77fe343fb77f); edit the notes in knowledge/, then run build -->

# Logging rules (LogLayer)

Apply these rules to every log call you write or review, and when you wire the logger. The first section is always in force; open a rule from the table when the task touches it. Setting the logger up is in `setup-app-infrastructure`.

## Always apply (critical, high)

### Never log a secret or personal data; log an id, a masked value or a derived flag

_critical · typescript, loglayer_

**Rule.** Never pass a secret (password, token, API key, session id, cookie, `Authorization` header) or personal data (email, phone number, address, date of birth, card or bank number, health data) to a log call, nor a whole object that may contain one, such as a request, its headers or a provider response. Log the identifier (`userId`), a masked form (`maskEmail(email)`) or a derived signal (`hasAuthHeader: true`).

**Why.** A secret written to a log is copied into every log store, backup and aggregator that receives it and must be treated as leaked; personal data there breaks data-protection duties and outlives deletion requests.

**Incorrect:**

```ts
log.withMetadata({ email, password, headers: request.headers }).info("Sign-in attempt");
```

**Correct:**

```ts
log
  .withMetadata({ email: maskEmail(email), hasAuthHeader: request.headers.has("authorization") })
  .info("Sign-in attempt");
```

### Attach a caught error with withError, never in withMetadata or the message

_high · typescript, loglayer_

**Rule.** Attach a caught value with `.withError(error)` and keep the message constant. Do not put it in `.withMetadata({ error })` and do not copy `error.message` into the message.

**Why.** `withError` is LogLayer's documented path for an `Error`, where the configured error serializer and the `err` field apply; an `Error` placed in metadata is serialized as a plain object, and its fields are not enumerable, so it comes out as `{}` and the stack is lost.

**Correct:**

```ts
} catch (error) {
  log.withError(error).withMetadata({ budgetId }).error("Save budget failed");
}
```

### Keep the log message constant and put every value in withMetadata

_high · typescript, loglayer_

**Rule.** Pass a short, constant, human-readable message to the level method and put every variable value in `.withMetadata({ ... })`. Fields that hold for the logger's lifetime (`module`, `requestId`) go in `createLogger` or `.withContext()`; per-call values go in `.withMetadata()`.

**Why.** A message such as `` `Budget ${id} created` `` differs on every call, so entries cannot be grouped or counted by message and the id cannot be queried as a field.

**Correct:**

```ts
log.withMetadata({ budgetId: budget.id, userId }).info("Budget created");
```

### Log through one createLogger({ module }) logger per file, never through console

_high · typescript, loglayer_

**Rule.** At the top of each server file that logs, create a module logger with `createLogger({ module: "<domain>-<layer>" })` (for example `budgets-db`, `budgets-actions`, `templates-service`; files of one layer share the name) and log only through it. `createLogger` returns `logger.child().withContext(context)`: add context to a module logger, never to the root. Feature code never calls `console.*` and never imports the root logger from `~/lib/logger`.

**Why.** A line written through `console.log` or the root logger carries no `module` field, so it cannot be filtered or traced back to its code, and `console.*` also bypasses the level and redaction configured in `lib/logger.ts`.

**Correct:**

```ts
import { createLogger } from "~/lib/logger";

const log = createLogger({ module: "budgets-db" });

export async function getBudget(id: string) {
  log.withMetadata({ budgetId: id }).debug("Budget loaded");
}
```

**Exceptions.** A file in no layer folder (`permissions.ts`, a util) rarely logs; when it does, give it the module name of its feature.

Client error boundaries (`error.tsx`, `global-error.tsx`) run in the browser, where the server logger does not exist; they may call `console.error`.

### Configure Pino redact for sensitive keys as defence in depth

_high · typescript, loglayer, pino_

**Rule.** Give the Pino instance in `lib/logger.ts` a `redact` config with `remove: true` covering `password`, `token`, `apiKey`, `secret` and `authorization` at the top level and one level down (`*.token`), plus `req.headers.authorization` and `req.headers.cookie`. It backs up the rule against logging secrets; it does not replace it.

**Why.** Without redaction, one call that logs a whole object (a request, a provider response) writes every token in it to the log, and nothing stops it until someone reads the log.

**Correct:**

```ts
const pinoLogger = pino({
  level: env.LOG_LEVEL,
  redact: {
    paths: ["password", "*.password", "token", "*.token", "apiKey", "*.apiKey", "secret", "*.secret",
      "authorization", "*.authorization", "req.headers.authorization", "req.headers.cookie"],
    remove: true,
  },
});
```

**Exceptions.** Redaction matches key paths, not values: a secret under an unlisted key, nested deeper than one level, or inside a message still leaks.

## Read when the task touches it

| Impact | Rule | Applies to |
| --- | --- | --- |
| medium | [Log an error once, in the layer that finally handles it](references/rules.md#log-an-error-once-in-the-layer-that-finally-handles-it) — Intermediate layers add context and re-raise; only the handler at the boundary logs, so one failure is one entry. | any |
| medium | [Write logs to stdout or stderr and let the platform collect them](references/rules.md#write-logs-to-stdout-or-stderr-and-let-the-platform-collect-them) — A containerised app emits an event stream; rotation and shipping belong to the platform, not the app. | any |
| medium | [Choose the log level by what the event means; log an expected not-found at warn](references/rules.md#choose-the-log-level-by-what-the-event-means-log-an-expected-not-found-at-warn) — error for a failure to investigate, warn for an expected outcome such as not-found, info for normal events. | typescript, loglayer |
| medium | [Create the request id once in proxy.ts and forward it on the request headers](references/rules.md#create-the-request-id-once-in-proxyts-and-forward-it-on-the-request-headers) — proxy.ts mints requestId and forwards x-request-id on the request and response; handlers read it, never mint one. | typescript, nextjs, loglayer |
| medium | [Log a returned error with withError, its errorCode, isRetryable and the operation ids](references/rules.md#log-a-returned-error-with-witherror-its-errorcode-isretryable-and-the-operation-ids) — The handler's log of a returned ServiceError carries withError, errorCode, isRetryable and ids, at the right level. | typescript, loglayer |
| medium | [Log to stdout through Pino everywhere and add the tmp/app.log file only in development](references/rules.md#log-to-stdout-through-pino-everywhere-and-add-the-tmpapplog-file-only-in-development) — PinoTransport writes to stdout everywhere; LogFileRotationTransport is added only when NODE_ENV is development. | typescript, loglayer, pino |
| medium | [Set the logger's level from LOG_LEVEL in the server env, chosen per environment](references/rules.md#set-the-loggers-level-from-log_level-in-the-server-env-chosen-per-environment) — LOG_LEVEL is a validated enum in data/env/server.ts (debug locally, info in production) that lib/logger.ts reads. | typescript, loglayer, pino, t3-env |
| medium | [Name log fields from the shared vocabulary, one name per concept](references/rules.md#name-log-fields-from-the-shared-vocabulary-one-name-per-concept) — userId, requestId, operation, durationMs, errorCode, isRetryable, statusCode, path, method; never uid or user_id. | typescript, loglayer |

Files in this skill

  • SKILL.md8.1 KB
  • references/rules.md9.5 KB

Attribution

Is this your skill, or is something wrong with this listing? Request removal or report an issue. Author removals are honored within 72 hours.

View all in development →

Comments

Loading comments…

Newsletter

Get the weekly list of safe new skills, and the ones we pulled.