@vsfedorenko/next-logger 0.1.0 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,146 +1,96 @@
1
1
  # @vsfedorenko/next-logger
2
2
 
3
+ [![npm version](https://img.shields.io/npm/v/@vsfedorenko/next-logger.svg)](https://www.npmjs.com/package/@vsfedorenko/next-logger)
4
+ [![CI](https://github.com/vsfedorenko/next-logger/actions/workflows/ci.yml/badge.svg)](https://github.com/vsfedorenko/next-logger/actions/workflows/ci.yml)
5
+
6
+ > Languages: **English** | [Русский](README.ru.md) | [中文](README.zh.md)
7
+
3
8
  A **universal logging kit for Next.js**.
4
9
 
5
- Monkeypatches Next.js' internal logger (`next/dist/build/output/log`) **and**
6
- the global `console.*` so all diagnostic output flows through a single
7
- level-controllable sink — [consola](https://github.com/unjs/consola) by default,
8
- with pluggable reporters for **Sentry**, structured **JSON**, and more without
9
- a custom Next.js server.
10
+ Wraps the global `console.*` — the same sink Next.js' own internal logger
11
+ funnels through so all diagnostic output flows through a single
12
+ level-controllable [consola](https://github.com/unjs/consola) instance, with
13
+ pluggable reporters for structured **JSON** and more. No custom server, no
14
+ module monkey-patching (which is unreachable under Turbopack anyway).
10
15
 
11
16
  Inspired by [`sainsburys-tech/next-logger`](https://github.com/sainsburys-tech/next-logger),
12
17
  which does the same with [pino](https://getpino.io). This package swaps pino
13
- for consola as the default backend and adds a reporter API so logs can be
14
- fanned out to any integration (Sentry breadcrumbs, JSON aggregators, …).
18
+ for consola and delivers configuration through an idiomatic `withLogger()`
19
+ config wrapper.
15
20
 
16
21
  ## Install
17
22
 
18
23
  ```sh
19
- bun add @vsfedorenko/next-logger consola
20
- # or
21
24
  npm install @vsfedorenko/next-logger consola
25
+ # or
26
+ bun add @vsfedorenko/next-logger consola
22
27
  ```
23
28
 
24
29
  `consola` is a peer dependency — install it alongside this package.
25
30
 
26
- ## Usage
31
+ ## Quick start
27
32
 
28
- ### Option A — Instrumentation hook (recommended)
29
-
30
- ```ts
31
- // instrumentation.ts (project root)
32
- export async function register() {
33
- if (process.env.NEXT_RUNTIME === "nodejs") {
34
- await import("@vsfedorenko/next-logger");
35
- }
36
- }
37
- ```
33
+ Two steps.
38
34
 
39
- The default import applies both patches: Next.js' logger **and** the global
40
- `console.*`.
35
+ **1. Wrap your Next.js config** (`next.config.ts`):
41
36
 
42
- ### Option B — `-r` preload
37
+ ```ts
38
+ import { withLogger } from "@vsfedorenko/next-logger";
43
39
 
44
- ```sh
45
- node -r @vsfedorenko/next-logger server.js
40
+ export default withLogger({ consola: { level: 4 } })({
41
+ // ...your other next config
42
+ });
46
43
  ```
47
44
 
48
- ### Patch Next only (leave `console` untouched)
45
+ **2. Call `init()` from instrumentation** (`instrumentation.ts`, project root):
49
46
 
50
47
  ```ts
51
- // instrumentation.ts
52
48
  export async function register() {
53
49
  if (process.env.NEXT_RUNTIME === "nodejs") {
54
- await import("@vsfedorenko/next-logger/presets/next-only");
50
+ const { init } = await import("@vsfedorenko/next-logger");
51
+ init();
55
52
  }
56
53
  }
57
54
  ```
58
55
 
59
- Useful when you want Next's internal logs routed through consola but prefer
60
- native `console.*` formatting (e.g. in development).
56
+ Done. Every `console.*` call on the server now flows through consola. Next.js'
57
+ own logs (build output, route compilation, etc.) are captured too — they share
58
+ the same `console.*` sink.
61
59
 
62
- ### Browser / Client Components
63
-
64
- The main entry (`@vsfedorenko/next-logger`) imports the patch modules, which
65
- depend on `require.cache` and `lilconfig` — neither exists in a browser bundle.
66
- For Client Components or any browser-side code, use the
67
- **`@vsfedorenko/next-logger/browser`** subpath:
68
-
69
- ```ts
70
- "use client";
71
- import { logger } from "@vsfedorenko/next-logger/browser";
72
-
73
- export function MyComponent() {
74
- logger.info("rendered");
75
- logger.warn("deprecation notice");
76
- return <div>…</div>;
77
- }
78
- ```
79
-
80
- This entry builds a consola instance from env-driven defaults (same level
81
- resolution: `LOG_LEVEL` → `NEXT_PUBLIC_LOG_LEVEL` → `3`), without the
82
- server-side patching machinery. For build-time-inlined levels visible in the
83
- browser bundle, use `NEXT_PUBLIC_LOG_LEVEL`.
60
+ > A runnable example app lives in [`examples/basic/`](examples/basic/).
84
61
 
85
62
  ## Configuration
86
63
 
87
- Optional config file (discovered from cwd upward via
88
- [lilconfig](https://github.com/antonk52/lilconfig)). Supported filenames:
89
-
90
- - `next-logger.config.ts` / `next-logger.config.js` / `next-logger.config.cjs`
91
- - `.next-loggerrc.ts` / `.next-loggerrc.js` / `.next-loggerrc.cjs`
92
- - `.next-loggerrc` (JSON)
93
- - `.next-loggerrc.json`
94
- - `next-logger` key in `package.json`
95
-
96
- **TypeScript configs** (`.ts`) are loaded via [jiti](https://github.com/unjs/jiti).
97
- Install it as an optional peer dependency:
98
-
99
- ```sh
100
- bun add -d jiti # or: npm install -D jiti
101
- ```
102
-
103
- ### Custom consola instance
104
-
105
- ```ts
106
- // next-logger.config.ts
107
- import { createConsola } from "consola";
108
-
109
- export default {
110
- consola: createConsola({ level: 4 }),
111
- };
112
- ```
113
-
114
- ### Partial options (merged with defaults)
64
+ `withLogger(options)` serialises `options` into the `NEXT_LOGGER_CONFIG`
65
+ environment variable via Next.js' validated `env` config key — inlined at
66
+ build time, read back at runtime. No "Unrecognized key" warning, works under
67
+ both webpack and Turbopack.
115
68
 
116
69
  ```ts
117
- import type { ConsolaOptions } from "consola";
118
-
119
- export default {
120
- consola: { level: 4, formatOptions: { date: false } } satisfies Partial<ConsolaOptions>,
121
- };
70
+ withLogger({
71
+ consola: {
72
+ level: 4, // debug
73
+ formatOptions: { date: false }, // consola format options
74
+ },
75
+ })
122
76
  ```
123
77
 
124
- ### Factory (receives the library defaults)
78
+ Only serialisable consola options are supported (`level`, `formatOptions`, ).
125
79
 
126
- ```ts
127
- import type { ConsolaOptions } from "consola";
128
- import { createConsola } from "consola";
80
+ ### Skip console patching
129
81
 
130
- export default {
131
- consola: (defaults: Partial<ConsolaOptions>) =>
132
- createConsola({ ...defaults, level: 5 }),
133
- };
134
- ```
82
+ `init({ console: false })` builds the logger without wrapping `console.*`.
83
+ Use this if you want the configured consola instance (via `getLogger()`) for
84
+ manual logging but prefer to leave the global `console` untouched.
135
85
 
136
86
  ## Log level
137
87
 
138
- Without a config file, the level resolves from (in order):
139
-
140
- 1. `LOG_LEVEL` (numeric or named)
141
- 2. `NEXT_PUBLIC_LOG_LEVEL` (numeric or named)
88
+ The level resolves in order:
142
89
 
143
- Falling back to `3` (info).
90
+ 1. `consola.level` from `withLogger`
91
+ 2. `LOG_LEVEL` (numeric or named)
92
+ 3. `NEXT_PUBLIC_LOG_LEVEL` (numeric or named)
93
+ 4. `3` (info) — default
144
94
 
145
95
  Named levels: `silent` (-∞), `fatal` (0), `error` (0), `warn` (1),
146
96
  `log` (2), `info` (3), `success` (3), `debug` (4), `trace` (5), `verbose` (∞).
@@ -165,7 +115,7 @@ Newline-delimited JSON to stdout (errors → stderr), suitable for structured-lo
165
115
  aggregators (Loki, Datadog, CloudWatch, Elasticsearch). Best for production.
166
116
 
167
117
  ```json
168
- {"level":"error","type":"error","tag":"next.js","msg":"failed to compile","date":"2026-07-11T13:43:10.712Z"}
118
+ {"level":"info","type":"log","tag":"console","msg":"API /api/hello hit","date":"2026-07-12T10:00:00.000Z"}
169
119
  ```
170
120
 
171
121
  Each line contains:
@@ -174,54 +124,83 @@ Each line contains:
174
124
  |---------|------------------------------------------------------------------------------|
175
125
  | `level` | Named level (`error`/`warn`/`info`/`debug`/`trace`) |
176
126
  | `type` | Consola log type (e.g. `error`, `warn`, `info`, `success`, `ready`, `event`) |
177
- | `tag` | The consola tag (`next.js`, `console`, `app`, …) |
127
+ | `tag` | The consola tag (`next.js`, `console`, …) |
178
128
  | `msg` | The message string (multi-arg strings joined with space) |
179
- | `date` | ISO 8601 timestamp |
129
+ | `date` | ISO 8601 timestamp |
180
130
  | `args` | Additional structured arguments (omitted when none) |
181
131
 
182
132
  Errors are serialised as `{ name, message, stack }`. Circular references become
183
133
  `[Circular]`. BigInts become strings.
184
134
 
185
- Only applies to the server entry (`@vsfedorenko/next-logger`) the browser
186
- entry always uses consola's built-in browser reporter. A custom consola instance
187
- from a config file bypasses format selection entirely.
135
+ ## Browser / Client Components
136
+
137
+ The server entry patches `console.*`, which only makes sense in Node.js. For
138
+ Client Components or any browser-side code, use the
139
+ **`@vsfedorenko/next-logger/browser`** subpath:
140
+
141
+ ```ts
142
+ "use client";
143
+ import { logger } from "@vsfedorenko/next-logger/browser";
144
+
145
+ export function MyComponent() {
146
+ logger.info("rendered");
147
+ logger.warn("deprecation notice");
148
+ return <div>…</div>;
149
+ }
150
+ ```
151
+
152
+ This entry builds a consola instance from env-driven defaults (same level
153
+ resolution: `LOG_LEVEL` → `NEXT_PUBLIC_LOG_LEVEL` → `3`), without any
154
+ server-side patching. For build-time-inlined levels visible in the browser
155
+ bundle, use `NEXT_PUBLIC_LOG_LEVEL`.
188
156
 
189
157
  ## How it works
190
158
 
191
- 1. **Next.js logger patch** (`patches/next.ts`) — replaces the methods exported
192
- by `next/dist/build/output/log` (`wait`, `error`, `warn`, `ready`, `info`,
193
- `event`, `trace`) with bound consola methods tagged `next.js`. Preserves the
194
- critical Next 13+ workaround: since Next defines these exports as
195
- non-configurable accessors, the patch replaces `require.cache[...].exports`
196
- with a shallow copy, then redefines each method on the copy.
159
+ 1. **Config wrapper** (`withLogger`, build time) — serialises logger options
160
+ into `NEXT_LOGGER_CONFIG` via Next's `env` key. Next inlines this at build
161
+ time, so the runtime reads it as `process.env.NEXT_LOGGER_CONFIG` with no
162
+ file-system or Next.js-internal imports.
197
163
 
198
- 2. **Console patch** (`patches/console.ts`) — overwrites
199
- `console.{log,debug,info,warn,error}` with bound consola methods tagged
200
- `console`. `log` and `info` both map to consola `info`.
164
+ 2. **Console-sink patch** (`patches/console.ts`, runtime) — wraps
165
+ `console.{log,debug,info,warn,error}` so every call routes through the
166
+ shared consola instance. `log` and `info` both map to consola `info`.
201
167
 
202
- Both patches share a single consola instance built by `logger.ts`, so the log
203
- level is controllable from one place.
168
+ 3. **Next-log classifier** (`patches/next.ts`, runtime) inspects each
169
+ `console.*` call: if the first argument carries a Next.js marker symbol
170
+ (`▲`, `✓`, `⚠`, `●`, `✗`, …) the line is tagged `next.js`; otherwise it's
171
+ tagged `console`. This works under Turbopack, where the old
172
+ `require.cache`-based monkeypatch is dead (Next's logger lives in a separate
173
+ bundled instance).
204
174
 
205
175
  ### Empty-message skipping
206
176
 
207
- Both patches skip printing when a message is **empty** — no arguments, or only
208
- `undefined`/`null`/`""` (values that carry no diagnostic value and would render
209
- as a bare tag line under consola). This mirrors Next.js' own behaviour, where
210
- `prefixedLog` drops the prefix when the message is empty.
177
+ The patch skips printing when a message is **empty** — no arguments, or only
178
+ `undefined`/`null`/`""` (values that carry no diagnostic value and would
179
+ render as a bare tag line under consola). This mirrors Next.js' own behaviour,
180
+ where `prefixedLog` drops the prefix when the message is empty.
211
181
 
212
182
  Falsy-but-present values (`0`, `false`) are **not** considered empty and are
213
183
  printed normally.
214
184
 
185
+ ### Turbopack note
186
+
187
+ Next.js' **startup banner** (`▲ Next.js`, `✓ Ready`, …) prints *before* the
188
+ instrumentation hook runs, so those specific lines are not captured. Any log
189
+ emitted after boot — route compilation, request-time output, your own
190
+ `console.*` calls — flows through the patch normally.
191
+
215
192
  ## Differences from `sainsburys-tech/next-logger`
216
193
 
217
194
  | Concern | sainsburys-tech (pino) | this package (consola) |
218
195
  |-------------------|-----------------------------------------------|-------------------------------------------------|
219
196
  | Backend | pino (JSON to stdout) | consola (pretty by default) |
197
+ | Config delivery | `next-logger.config.js` + preload | `withLogger()` wrapper (idiomatic, type-safe) |
198
+ | Interception | patches `next/dist/build/output/log` | wraps `console.*` sink (Turbopack-safe) |
220
199
  | Arg normalisation | custom `hooks.logMethod` | not needed — consola handles console-style args |
221
200
  | Child logger | `logger.child({ name })` | `consola.withTag(tag)` |
222
- | Custom backend | any logger with `.child()` (pino, winston, …) | consola instances / options only |
223
201
  | `trace` level | falls back to `debug` (Winston has no trace) | native — consola has `trace` |
224
202
  | Default level | hardcoded `debug` | env-driven (`LOG_LEVEL`) |
203
+ | Turbopack | `require.cache` patch breaks | console-sink — works |
225
204
  | Language | plain JS (CommonJS) | TypeScript (CJS output) |
226
205
 
227
206
  ## License
package/README.ru.md ADDED
@@ -0,0 +1,210 @@
1
+ # @vsfedorenko/next-logger
2
+
3
+ [![npm version](https://img.shields.io/npm/v/@vsfedorenko/next-logger.svg)](https://www.npmjs.com/package/@vsfedorenko/next-logger)
4
+ [![CI](https://github.com/vsfedorenko/next-logger/actions/workflows/ci.yml/badge.svg)](https://github.com/vsfedorenko/next-logger/actions/workflows/ci.yml)
5
+
6
+ > Языки: [English](README.md) | **Русский** | [中文](README.zh.md)
7
+
8
+ **Универсальный набор для логирования в Next.js.**
9
+
10
+ Оборачивает глобальный `console.*` — тот же приёмник, через который проходит
11
+ внутренний логгер Next.js — так что весь диагностический вывод идёт через единый
12
+ управляемый по уровню экземпляр [consola](https://github.com/unjs/consola), с
13
+ подключаемыми репортерами для структурированного **JSON** и др. Без кастомного
14
+ сервера, без monkey-патчинга модулей (который под Turbopack всё равно недостижим).
15
+
16
+ Вдохновлено [`sainsburys-tech/next-logger`](https://github.com/sainsburys-tech/next-logger),
17
+ который делает то же самое на [pino](https://getpino.io). Этот пакет заменяет
18
+ pino на consola и доставляет конфигурацию через идиоматическую обёртку
19
+ `withLogger()`.
20
+
21
+ ## Установка
22
+
23
+ ```sh
24
+ npm install @vsfedorenko/next-logger consola
25
+ # или
26
+ bun add @vsfedorenko/next-logger consola
27
+ ```
28
+
29
+ `consola` — peer-зависимость, устанавливайте её вместе с пакетом.
30
+
31
+ ## Быстрый старт
32
+
33
+ Два шага.
34
+
35
+ **1. Оберните конфиг Next.js** (`next.config.ts`):
36
+
37
+ ```ts
38
+ import { withLogger } from "@vsfedorenko/next-logger";
39
+
40
+ export default withLogger({ consola: { level: 4 } })({
41
+ // ...остальной конфиг next
42
+ });
43
+ ```
44
+
45
+ **2. Вызовите `init()` из instrumentation** (`instrumentation.ts`, корень проекта):
46
+
47
+ ```ts
48
+ export async function register() {
49
+ if (process.env.NEXT_RUNTIME === "nodejs") {
50
+ const { init } = await import("@vsfedorenko/next-logger");
51
+ init();
52
+ }
53
+ }
54
+ ```
55
+
56
+ Готово. Каждый вызов `console.*` на сервере теперь проходит через consola.
57
+ Собственные логи Next.js (вывод сборки, компиляция роутов и т. д.) тоже
58
+ перехватываются — они используют тот же приёмник `console.*`.
59
+
60
+ > Рабочий пример приложения — в [`examples/basic/`](examples/basic/).
61
+
62
+ ## Конфигурация
63
+
64
+ `withLogger(options)` сериализует `options` в переменную окружения
65
+ `NEXT_LOGGER_CONFIG` через валидируемый конфиг-ключ `env` в Next.js —
66
+ встраивается на этапе сборки, считывается в рантайме. Без предупреждения
67
+ «Unrecognized key», работает и под webpack, и под Turbopack.
68
+
69
+ ```ts
70
+ withLogger({
71
+ consola: {
72
+ level: 4, // debug
73
+ formatOptions: { date: false }, // опции форматирования consola
74
+ },
75
+ })
76
+ ```
77
+
78
+ Поддерживаются только сериализуемые опции consola (`level`, `formatOptions`, …).
79
+
80
+ ### Пропустить патчинг консоли
81
+
82
+ `init({ console: false })` создаёт логгер без обёртки `console.*`. Используйте,
83
+ если вам нужен настроенный экземпляр consola (через `getLogger()`) для ручного
84
+ логирования, но вы предпочитаете не трогать глобальный `console`.
85
+
86
+ ## Уровень логирования
87
+
88
+ Уровень разрешается по порядку:
89
+
90
+ 1. `consola.level` из `withLogger`
91
+ 2. `LOG_LEVEL` (число или имя)
92
+ 3. `NEXT_PUBLIC_LOG_LEVEL` (число или имя)
93
+ 4. `3` (info) — по умолчанию
94
+
95
+ Именованные уровни: `silent` (-∞), `fatal` (0), `error` (0), `warn` (1),
96
+ `log` (2), `info` (3), `success` (3), `debug` (4), `trace` (5), `verbose` (∞).
97
+
98
+ ## Формат логов
99
+
100
+ Формат серверного вывода задаётся переменной окружения:
101
+
102
+ 1. `LOG_FORMAT` (`text` или `json`)
103
+ 2. `NEXT_PUBLIC_LOG_FORMAT` (те же значения)
104
+
105
+ По умолчанию `text` (стандартный «pretty»-репортер consola).
106
+
107
+ ### `text` (по умолчанию)
108
+
109
+ Человекочитаемый, с цветами в TTY и временными метками — встроенный репортер
110
+ consola. Подходит для локальной разработки.
111
+
112
+ ### `json`
113
+
114
+ Построчный JSON в stdout (ошибки → stderr), подходит для агрегаторов
115
+ структурированных логов (Loki, Datadog, CloudWatch, Elasticsearch). Подходит для
116
+ production.
117
+
118
+ ```json
119
+ {"level":"info","type":"log","tag":"console","msg":"API /api/hello hit","date":"2026-07-12T10:00:00.000Z"}
120
+ ```
121
+
122
+ Каждая строка содержит:
123
+
124
+ | Поле | Описание |
125
+ |--------|-------------------------------------------------------------------------------|
126
+ | `level`| Именованный уровень (`error`/`warn`/`info`/`debug`/`trace`) |
127
+ | `type` | Тип лога consola (`error`, `warn`, `info`, `success`, `ready`, `event` и т.д.)|
128
+ | `tag` | Тег consola (`next.js`, `console`, …) |
129
+ | `msg` | Строка сообщения (строковые аргументы объединяются пробелом) |
130
+ | `date` | ISO 8601 временная метка |
131
+ | `args` | Дополнительные структурированные аргументы (опускается, если их нет) |
132
+
133
+ Ошибки сериализуются как `{ name, message, stack }`. Циклические ссылки
134
+ становятся `[Circular]`. BigInt преобразуются в строки.
135
+
136
+ ## Браузер / Client Components
137
+
138
+ Серверный entrypoint патчит `console.*`, что имеет смысл только в Node.js. Для
139
+ Client Components или любого браузерного кода используйте подпуть
140
+ **`@vsfedorenko/next-logger/browser`**:
141
+
142
+ ```ts
143
+ "use client";
144
+ import { logger } from "@vsfedorenko/next-logger/browser";
145
+
146
+ export function MyComponent() {
147
+ logger.info("отрендерено");
148
+ logger.warn("устаревший API");
149
+ return <div>…</div>;
150
+ }
151
+ ```
152
+
153
+ Этот entrypoint создаёт экземпляр consola из значений по умолчанию, управляемых
154
+ переменными окружения (то же разрешение уровня: `LOG_LEVEL` →
155
+ `NEXT_PUBLIC_LOG_LEVEL` → `3`), без серверных механизмов патчинга. Для значений,
156
+ встраиваемых на этапе сборки (видимых в браузерном бандле), используйте
157
+ `NEXT_PUBLIC_LOG_LEVEL`.
158
+
159
+ ## Как это работает
160
+
161
+ 1. **Обёртка конфига** (`withLogger`, время сборки) — сериализует опции логгера
162
+ в `NEXT_LOGGER_CONFIG` через ключ `env` в Next. Next встраивает это на этапе
163
+ сборки, поэтому рантайм читает значение как `process.env.NEXT_LOGGER_CONFIG`
164
+ без файловых или внутренних импортов Next.js.
165
+
166
+ 2. **Патч приёмника консоли** (`patches/console.ts`, рантайм) — обёртывает
167
+ `console.{log,debug,info,warn,error}`, так что каждый вызов проходит через
168
+ общий экземпляр consola. `log` и `info` оба мапятся в consola `info`.
169
+
170
+ 3. **Классификатор логов Next** (`patches/next.ts`, рантайм) — проверяет каждый
171
+ вызов `console.*`: если первый аргумент несёт символ-маркер Next.js
172
+ (`▲`, `✓`, `⚠`, `●`, `✗`, …), строка тегируется `next.js`; иначе — `console`.
173
+ Это работает под Turbopack, где старый monkey-патч через `require.cache`
174
+ мёртв (логгер Next живёт в отдельном бандле).
175
+
176
+ ### Пропуск пустых сообщений
177
+
178
+ Патч пропускает печать, когда сообщение **пустое** — нет аргументов или только
179
+ `undefined`/`null`/`""` (значения без диагностической ценности, которые под
180
+ consola отрендерились бы как строка с тегом без полезной нагрузки). Это
181
+ повторяет поведение самого Next.js, где `prefixedLog` опускает префикс при пустом
182
+ сообщении.
183
+
184
+ Ложные, но присутствующие значения (`0`, `false`) **не** считаются пустыми и
185
+ печатаются как обычно.
186
+
187
+ ### Замечание про Turbopack
188
+
189
+ Стартовый баннер Next.js (**`▲ Next.js`**, `✓ Ready`, …) печатается *до* того,
190
+ как срабатывает instrumentation-хук, поэтому эти конкретные строки не
191
+ перехватываются. Любой лог после загрузки — компиляция роутов, вывод во время
192
+ запроса, ваши собственные вызовы `console.*` — проходит через патч как обычно.
193
+
194
+ ## Отличия от `sainsburys-tech/next-logger`
195
+
196
+ | Аспект | sainsburys-tech (pino) | этот пакет (consola) |
197
+ |--------------------|-----------------------------------------------|-------------------------------------------------|
198
+ | Бэкенд | pino (JSON в stdout) | consola («pretty» по умолчанию) |
199
+ | Доставка конфига | `next-logger.config.js` + preload | обёртка `withLogger()` (идиоматично, типобезопасно) |
200
+ | Перехват | патчит `next/dist/build/output/log` | обёртка `console.*` (Turbopack-safe) |
201
+ | Нормализация арг. | кастомный `hooks.logMethod` | не нужна — consola сам работает с console-арг. |
202
+ | Дочерний логгер | `logger.child({ name })` | `consola.withTag(tag)` |
203
+ | Уровень `trace` | fallback на `debug` (в Winston нет trace) | нативный — в consola есть `trace` |
204
+ | Уровень по умолч. | захардкожен `debug` | из env (`LOG_LEVEL`) |
205
+ | Turbopack | патч `require.cache` ломается | console-sink — работает |
206
+ | Язык | обычный JS (CommonJS) | TypeScript (вывод CJS) |
207
+
208
+ ## Лицензия
209
+
210
+ MIT