@tylix/core 1.4.0 → 2.0.0
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 +59 -3
- package/package.json +12 -6
- package/src/http/debug/renderDebugPage.js +2 -0
- package/src/http/requireAuth.js +15 -4
- package/src/http/statusPage.js +20 -19
- package/src/index.d.ts +2 -0
- package/src/index.js +3 -0
- package/src/observability/index.d.ts +66 -1
- package/src/observability/logger.js +118 -20
- package/src/observability/logging.js +351 -0
- package/src/plugins/plugins.d.ts +81 -0
- package/src/plugins/plugins.js +200 -0
- package/src/queue/JobRecord.js +1 -1
- package/src/queue/dispatch.d.ts +47 -1
- package/src/queue/dispatch.js +17 -3
- package/src/queue/retry.js +89 -0
package/README.md
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
# @tylix/core
|
|
2
2
|
|
|
3
|
-
The Tylix server runtime: HTTP server and router,
|
|
4
|
-
health checks, a shared store, cache, rate limiting, queue
|
|
5
|
-
channels. `tylix dev` and `tylix start` set all of it up from your
|
|
3
|
+
The Tylix server runtime: HTTP server and router, log channels, metrics
|
|
4
|
+
and health checks, a shared store, cache, rate limiting, a queue with
|
|
5
|
+
retries, scheduler, channels and plugins. `tylix dev` and `tylix start` set all of it up from your
|
|
6
6
|
settings; import the pieces you use in app code.
|
|
7
7
|
|
|
8
8
|
```sh
|
|
@@ -43,6 +43,26 @@ addReadinessCheck('payments', () => paymentsApi.ping())
|
|
|
43
43
|
- `/health` and `/ready` are always on; `/metrics` (Prometheus format) with
|
|
44
44
|
`METRICS=true`, guarded by `METRICS_TOKEN`.
|
|
45
45
|
|
|
46
|
+
## Log channels
|
|
47
|
+
|
|
48
|
+
```js
|
|
49
|
+
import { Log } from '@tylix/core'
|
|
50
|
+
|
|
51
|
+
Log.info('Invoice sent', { invoiceId: 12 })
|
|
52
|
+
Log.channel('payments').error('Charge failed', { error })
|
|
53
|
+
Log.stack(['daily', 'slack']).critical('Payments are down')
|
|
54
|
+
Log.withContext({ tenant: 3 })
|
|
55
|
+
Log.extend('slack', (config) => ({ write(entry) { /* send it */ } }))
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
The levels are Laravel's eight: `debug`, `info`, `notice`, `warning`,
|
|
59
|
+
`error`, `critical`, `alert` and `emergency`. The drivers are `stack`,
|
|
60
|
+
`single`, `daily` (rotated, keeping `days`), `console`, `stderr`, `null`
|
|
61
|
+
and `custom`, and each channel has its own minimum `level`. They are set
|
|
62
|
+
in `logging` in `tylix.config` or with `LOG_CHANNEL`, `LOG_STACK` and
|
|
63
|
+
`LOG_DAILY_DAYS`. Files go in `storage/logs/`, one line per entry:
|
|
64
|
+
`[2026-11-15 10:22:01] production.ERROR: Charge failed {"orderId":7} {"requestId":"..."}`.
|
|
65
|
+
|
|
46
66
|
## Store, cache and rate limits
|
|
47
67
|
|
|
48
68
|
One store holds the cache, shared rate limits and channel messages, so
|
|
@@ -76,6 +96,42 @@ await broadcast('chat', { text: 'Deploy finished' }) // to clients of tylix chan
|
|
|
76
96
|
Queue workers claim each job atomically, so several workers never run the
|
|
77
97
|
same job.
|
|
78
98
|
|
|
99
|
+
Jobs retry with backoff:
|
|
100
|
+
|
|
101
|
+
```js
|
|
102
|
+
export const SendInvoice = {
|
|
103
|
+
tries: 3,
|
|
104
|
+
backoff: [10, 60, 300], // or 30, 'exponential', (attempt) => seconds
|
|
105
|
+
timeout: 120,
|
|
106
|
+
async handle(payload, { attempt }) {},
|
|
107
|
+
async failed(payload, error) {},
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
await dispatch('SendInvoice', { invoiceId: 12 }, { delay: 60 })
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
Throw a `PermanentJobError` to fail without retrying. `jobOptions`,
|
|
114
|
+
`backoffSeconds` and `afterFailure` are the rules the worker uses.
|
|
115
|
+
|
|
116
|
+
## Plugins
|
|
117
|
+
|
|
118
|
+
```js
|
|
119
|
+
import { definePlugin } from '@tylix/core'
|
|
120
|
+
|
|
121
|
+
export default definePlugin({
|
|
122
|
+
name: 'audit',
|
|
123
|
+
register({ use, logger }) { use((req, res, next) => next()) },
|
|
124
|
+
routes(router, { auth }) { router.get('/api/audit', auth(handler)) },
|
|
125
|
+
logDrivers: { slack: (config) => ({ write(entry) {} }) },
|
|
126
|
+
commands: { 'audit:prune': { run(args) {} } },
|
|
127
|
+
})
|
|
128
|
+
```
|
|
129
|
+
|
|
130
|
+
The hooks are `config`, `register`, `routes`, `boot` and `close`. Plugins
|
|
131
|
+
can also add `logDrivers`, `commands` and `deployAdapters`.
|
|
132
|
+
`loadPlugins(baseDir, config)` and `createPluginHost(plugins)` are what the
|
|
133
|
+
CLI uses.
|
|
134
|
+
|
|
79
135
|
## License
|
|
80
136
|
|
|
81
137
|
MIT
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tylix/core",
|
|
3
|
-
"version": "
|
|
4
|
-
"description": "The Tylix server core: HTTP server and router,
|
|
3
|
+
"version": "2.0.0",
|
|
4
|
+
"description": "The Tylix server core: HTTP server and router, Laravel-style log channels, metrics and health checks, a shared store (memory, database, Redis), cache, rate limiting, a queue with retries and backoff, scheduler, channels and plugins.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"author": "Mbiyrukzz",
|
|
7
7
|
"type": "module",
|
|
@@ -14,7 +14,13 @@
|
|
|
14
14
|
"observability",
|
|
15
15
|
"cache",
|
|
16
16
|
"queue",
|
|
17
|
-
"websocket"
|
|
17
|
+
"websocket",
|
|
18
|
+
"logging",
|
|
19
|
+
"log-channels",
|
|
20
|
+
"plugins",
|
|
21
|
+
"retries",
|
|
22
|
+
"backoff",
|
|
23
|
+
"scheduler"
|
|
18
24
|
],
|
|
19
25
|
"homepage": "https://github.com/Mbiyrukzz/tylix/tree/main/packages/core#readme",
|
|
20
26
|
"repository": {
|
|
@@ -44,9 +50,9 @@
|
|
|
44
50
|
"test": "node --test 'src/**/*.test.js'"
|
|
45
51
|
},
|
|
46
52
|
"dependencies": {
|
|
47
|
-
"@tylix/auth": "^
|
|
48
|
-
"@tylix/orm": "^
|
|
49
|
-
"@tylix/shared": "^
|
|
53
|
+
"@tylix/auth": "^2.0.0",
|
|
54
|
+
"@tylix/orm": "^2.0.0",
|
|
55
|
+
"@tylix/shared": "^2.0.0",
|
|
50
56
|
"ws": "^8.18.0"
|
|
51
57
|
},
|
|
52
58
|
"devDependencies": {
|
package/src/http/requireAuth.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { verifyTylixAccessToken, ACCESS_TOKEN_COOKIE } from "@tylix/auth";
|
|
2
2
|
|
|
3
3
|
// Shared across packages (Symbol.for), so `tylix dev` can print a lock next
|
|
4
4
|
// to every guarded route without importing anything from here.
|
|
@@ -10,9 +10,14 @@ const AUTH_MARK = Symbol.for("tylix.requireAuth");
|
|
|
10
10
|
* browser app now uses), then falls back to an
|
|
11
11
|
* "Authorization: Bearer <token>" header (for non-browser API clients
|
|
12
12
|
* that can't rely on cookies). On success, req.user is set to the
|
|
13
|
-
* token's payload (e.g. { userId }); on failure, responds 401 and
|
|
13
|
+
* token's payload (e.g. { userId, sid }); on failure, responds 401 and
|
|
14
14
|
* never calls the wrapped handler.
|
|
15
15
|
*
|
|
16
|
+
* Only real access tokens pass: email-verification links and other
|
|
17
|
+
* purpose tokens are refused, and when the app's AuthController manages
|
|
18
|
+
* sessions, a token whose session was ended (logout, "sign out
|
|
19
|
+
* everywhere", password reset) is refused immediately.
|
|
20
|
+
*
|
|
16
21
|
* options.hydrate(payload, req) is optional. It runs after the token is
|
|
17
22
|
* verified and can add fields to req.user (for example a team id):
|
|
18
23
|
* - return an object -> its fields are merged into req.user
|
|
@@ -27,7 +32,7 @@ export function requireAuth(handler, secret, options = {}) {
|
|
|
27
32
|
|
|
28
33
|
const authHeader = req.headers?.authorization || "";
|
|
29
34
|
const [scheme, headerToken] = authHeader.split(" ");
|
|
30
|
-
const bearerToken = scheme
|
|
35
|
+
const bearerToken = /^bearer$/i.test(scheme ?? "") ? headerToken : null;
|
|
31
36
|
|
|
32
37
|
const token = cookieToken || bearerToken;
|
|
33
38
|
|
|
@@ -35,7 +40,13 @@ export function requireAuth(handler, secret, options = {}) {
|
|
|
35
40
|
return res.status(401).json({ error: "Not authenticated." });
|
|
36
41
|
}
|
|
37
42
|
|
|
38
|
-
|
|
43
|
+
let result;
|
|
44
|
+
try {
|
|
45
|
+
result = await verifyTylixAccessToken(token, secret);
|
|
46
|
+
} catch (error) {
|
|
47
|
+
console.error("[auth] token check failed:", error);
|
|
48
|
+
return res.status(500).json({ error: "Couldn't check your session." });
|
|
49
|
+
}
|
|
39
50
|
if (!result.valid) {
|
|
40
51
|
return res.status(401).json({ error: result.error || "Invalid token." });
|
|
41
52
|
}
|
package/src/http/statusPage.js
CHANGED
|
@@ -56,18 +56,18 @@ export function renderStatusPage({
|
|
|
56
56
|
<style>
|
|
57
57
|
* { box-sizing: border-box; }
|
|
58
58
|
:root {
|
|
59
|
-
--bg:#
|
|
60
|
-
--text:#
|
|
61
|
-
--success:#
|
|
62
|
-
--error:#
|
|
63
|
-
--notfound:#
|
|
59
|
+
--bg:#f3f2f6; --card:#ffffff; --border:#dedbe6; --border-strong:#c9c5d4;
|
|
60
|
+
--text:#17151c; --muted:#6b6878; --brand:#0034ca; --brand-hover:#1a4be0;
|
|
61
|
+
--success:#0d8c67; --success-soft:rgba(13,140,103,.12);
|
|
62
|
+
--error:#cd3c3c; --error-soft:rgba(205,60,60,.10);
|
|
63
|
+
--notfound:#bd6226; --notfound-soft:rgba(189,98,38,.12);
|
|
64
64
|
}
|
|
65
65
|
html.dark {
|
|
66
|
-
--bg:#
|
|
67
|
-
--text:#
|
|
68
|
-
--success:#
|
|
69
|
-
--error:#
|
|
70
|
-
--notfound:#
|
|
66
|
+
--bg:#17161c; --card:#211f27; --border:#34313d; --border-strong:#46424f;
|
|
67
|
+
--text:#ecebf1; --muted:#9592a3; --brand:#3563ff; --brand-hover:#547cff;
|
|
68
|
+
--success:#5fe3b5; --success-soft:rgba(95,227,181,.12);
|
|
69
|
+
--error:#ff7b7b; --error-soft:rgba(255,123,123,.12);
|
|
70
|
+
--notfound:#ffb38a; --notfound-soft:rgba(255,179,138,.12);
|
|
71
71
|
}
|
|
72
72
|
html { color-scheme: light; } html.dark { color-scheme: dark; }
|
|
73
73
|
body {
|
|
@@ -77,12 +77,13 @@ export function renderStatusPage({
|
|
|
77
77
|
}
|
|
78
78
|
.card {
|
|
79
79
|
width:100%; max-width:440px; text-align:center; padding:36px 32px 32px;
|
|
80
|
-
|
|
81
|
-
|
|
80
|
+
border:1px solid transparent; border-radius:20px;
|
|
81
|
+
background:linear-gradient(var(--card),var(--card)) padding-box, linear-gradient(135deg,#6fe0ea,#c8f07a) border-box;
|
|
82
|
+
box-shadow:0 0 32px -8px rgba(111,224,234,.35), 0 12px 32px -16px rgba(0,0,0,.25);
|
|
82
83
|
}
|
|
83
|
-
html.dark .card { box-shadow:none; }
|
|
84
84
|
.brand { display:inline-flex; align-items:center; gap:8px; margin-bottom:24px; font-weight:600; color:var(--text); text-decoration:none; }
|
|
85
|
-
.brand img {
|
|
85
|
+
.brand img { height:20px; width:auto; }
|
|
86
|
+
html.dark .brand img { filter:brightness(1.7) saturate(1.1); }
|
|
86
87
|
.icon { width:60px; height:60px; margin:0 auto 18px; border-radius:50%; display:grid; place-items:center;
|
|
87
88
|
color:var(--tone); background:var(--tone-soft); }
|
|
88
89
|
.tone-success { --tone:var(--success); --tone-soft:var(--success-soft); }
|
|
@@ -93,12 +94,12 @@ export function renderStatusPage({
|
|
|
93
94
|
p.msg { margin:0 0 24px; color:var(--muted); font-size:14px; line-height:1.6; }
|
|
94
95
|
.actions { display:flex; gap:10px; justify-content:center; flex-wrap:wrap; }
|
|
95
96
|
.btn {
|
|
96
|
-
font-size:14px; font-weight:600; text-decoration:none; padding:9px 18px; border-radius:
|
|
97
|
+
font-size:14px; font-weight:600; text-decoration:none; padding:9px 18px; border-radius:9px;
|
|
97
98
|
color:var(--text); border:1px solid var(--border-strong); background:transparent; transition:all .15s;
|
|
98
99
|
}
|
|
99
|
-
.btn:hover { border-color:var(--
|
|
100
|
-
.btn-primary { color:#fff; border-color:transparent; background:
|
|
101
|
-
.btn-primary:hover { color:#fff;
|
|
100
|
+
.btn:hover { border-color:var(--brand); color:var(--brand); }
|
|
101
|
+
.btn-primary { color:#fff; border-color:transparent; background:var(--brand); }
|
|
102
|
+
.btn-primary:hover { color:#fff; background:var(--brand-hover); box-shadow:0 6px 18px -8px var(--brand); }
|
|
102
103
|
.ref { margin:22px 0 0; font-size:12px; color:var(--muted); }
|
|
103
104
|
.ref code { font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size:11px; padding:2px 6px;
|
|
104
105
|
border-radius:6px; background:var(--bg); border:1px solid var(--border); user-select:all; }
|
|
@@ -106,7 +107,7 @@ export function renderStatusPage({
|
|
|
106
107
|
</head>
|
|
107
108
|
<body>
|
|
108
109
|
<div class="card tone-${esc(tone)}">
|
|
109
|
-
<a class="brand" href="/"><img src="/logo-mark.
|
|
110
|
+
<a class="brand" href="/"><img src="/logo-mark.svg" alt="" onerror="if(!this.dataset.png){this.dataset.png=1;this.src='/logo-mark.png'}else{this.remove()}">Tylix</a>
|
|
110
111
|
<div class="icon">${ICONS[tone] ?? ICONS.error}</div>
|
|
111
112
|
${code ? `<p class="code">${esc(code)}</p>` : ''}
|
|
112
113
|
<h1>${esc(title)}</h1>
|
package/src/index.d.ts
CHANGED
package/src/index.js
CHANGED
|
@@ -15,13 +15,16 @@ export * from './discovery/registerRouteFiles.js'
|
|
|
15
15
|
export * from './discovery/loadCustomRoutes.js'
|
|
16
16
|
export * from './queue/JobRecord.js'
|
|
17
17
|
export * from './queue/dispatch.js'
|
|
18
|
+
export * from './queue/retry.js'
|
|
18
19
|
export * from './scheduling/Scheduler.js'
|
|
19
20
|
export * from './channels/ChannelServer.js'
|
|
20
21
|
export * from './cache/CacheRecord.js'
|
|
21
22
|
export * from './cache/Cache.js'
|
|
22
23
|
export * from './observability/context.js'
|
|
23
24
|
export * from './observability/logger.js'
|
|
25
|
+
export * from './observability/logging.js'
|
|
24
26
|
export * from './observability/metrics.js'
|
|
25
27
|
export * from './observability/health.js'
|
|
26
28
|
export * from './store/index.js'
|
|
27
29
|
export * from './channels/broadcast.js'
|
|
30
|
+
export * from './plugins/plugins.js'
|
|
@@ -9,7 +9,7 @@ export interface RequestContext {
|
|
|
9
9
|
export declare const requestContext: AsyncLocalStorage<RequestContext>
|
|
10
10
|
export declare function currentRequest(): RequestContext | null
|
|
11
11
|
|
|
12
|
-
export type LogLevel = 'debug' | 'info' | 'warn' | 'error' | 'silent'
|
|
12
|
+
export type LogLevel = 'debug' | 'info' | 'notice' | 'warn' | 'warning' | 'error' | 'critical' | 'alert' | 'emergency' | 'silent'
|
|
13
13
|
export interface LoggerOptions {
|
|
14
14
|
level?: LogLevel
|
|
15
15
|
/** json: one JSON line per entry (production); pretty: one readable line. */
|
|
@@ -20,14 +20,39 @@ export interface LoggerOptions {
|
|
|
20
20
|
/** Batch writes once per event-loop turn (default true). */
|
|
21
21
|
buffer?: boolean
|
|
22
22
|
base?: Record<string, unknown>
|
|
23
|
+
/** Where entries go. Default: the console. */
|
|
24
|
+
transports?: LogTransport[] | null
|
|
25
|
+
}
|
|
26
|
+
export interface LogEntry {
|
|
27
|
+
time: Date
|
|
28
|
+
level: Exclude<LogLevel, 'silent' | 'warning'>
|
|
29
|
+
message: string
|
|
30
|
+
fields: Record<string, unknown>
|
|
31
|
+
}
|
|
32
|
+
export interface LogTransport {
|
|
33
|
+
name?: string
|
|
34
|
+
/** Lowest level this transport writes. */
|
|
35
|
+
level?: LogLevel
|
|
36
|
+
write(entry: LogEntry): void
|
|
23
37
|
}
|
|
24
38
|
export interface Logger {
|
|
25
39
|
debug(message: string, fields?: Record<string, unknown>): void
|
|
26
40
|
info(message: string, fields?: Record<string, unknown>): void
|
|
27
41
|
warn(message: string, fields?: Record<string, unknown>): void
|
|
28
42
|
error(message: string, fields?: Record<string, unknown>): void
|
|
43
|
+
notice(message: string, fields?: Record<string, unknown>): void
|
|
44
|
+
warning(message: string, fields?: Record<string, unknown>): void
|
|
45
|
+
critical(message: string, fields?: Record<string, unknown>): void
|
|
46
|
+
alert(message: string, fields?: Record<string, unknown>): void
|
|
47
|
+
emergency(message: string, fields?: Record<string, unknown>): void
|
|
48
|
+
log(level: Exclude<LogLevel, 'silent'>, message: string, fields?: Record<string, unknown>): void
|
|
29
49
|
/** A logger that adds these fields to every entry. */
|
|
30
50
|
child(fields: Record<string, unknown>): Logger
|
|
51
|
+
/** The same logger, writing to these transports instead. */
|
|
52
|
+
withTransports(transports: LogTransport[]): Logger
|
|
53
|
+
/** Adds fields to every later entry of this logger and its children. */
|
|
54
|
+
withContext(fields: Record<string, unknown>): Logger
|
|
55
|
+
withoutContext(keys?: string[]): Logger
|
|
31
56
|
isLevelEnabled(level: LogLevel): boolean
|
|
32
57
|
/** Changes this logger and its children. */
|
|
33
58
|
configure(options: LoggerOptions): void
|
|
@@ -66,3 +91,43 @@ export declare function runReadinessChecks(): Promise<{
|
|
|
66
91
|
ok: boolean
|
|
67
92
|
checks: Record<string, { ok: boolean; ms: number; error?: string }>
|
|
68
93
|
}>
|
|
94
|
+
|
|
95
|
+
export interface LoggingSettings {
|
|
96
|
+
default?: string
|
|
97
|
+
channels?: Record<string, { driver: string; [key: string]: unknown }>
|
|
98
|
+
/** Shortcut for channels.stack.channels. */
|
|
99
|
+
stack?: string[]
|
|
100
|
+
}
|
|
101
|
+
export declare const DEFAULT_LOG_PATH: string
|
|
102
|
+
export declare const DEFAULT_LOG_CHANNELS: Record<string, { driver: string; [key: string]: unknown }>
|
|
103
|
+
/** Points the app logger at logging.default. */
|
|
104
|
+
export declare function configureLogging(settings?: LoggingSettings, options?: { baseDir?: string; environment?: string }): { default: string; transports: LogTransport[] }
|
|
105
|
+
/** One Laravel-style line: [2026-11-15 10:22:01] local.ERROR: message {context} {extra} */
|
|
106
|
+
export declare function formatLogLine(entry: LogEntry, environment?: string): string
|
|
107
|
+
export declare function dailyLogPath(basePath: string, date?: Date): string
|
|
108
|
+
export declare function logFiles(): Array<{ channel: string; path: string; base: string; daily: boolean }>
|
|
109
|
+
export declare function flushLogFiles(): void
|
|
110
|
+
type LogMethod = (message: string, context?: Record<string, unknown>) => void
|
|
111
|
+
export declare const Log: {
|
|
112
|
+
debug: LogMethod
|
|
113
|
+
info: LogMethod
|
|
114
|
+
notice: LogMethod
|
|
115
|
+
warning: LogMethod
|
|
116
|
+
warn: LogMethod
|
|
117
|
+
error: LogMethod
|
|
118
|
+
critical: LogMethod
|
|
119
|
+
alert: LogMethod
|
|
120
|
+
emergency: LogMethod
|
|
121
|
+
log(level: Exclude<LogLevel, 'silent'>, message: string, context?: Record<string, unknown>): void
|
|
122
|
+
/** Writes to one named channel only. */
|
|
123
|
+
channel(name: string): Logger
|
|
124
|
+
/** Writes to several channels. */
|
|
125
|
+
stack(names: string[]): Logger
|
|
126
|
+
/** A channel defined on the spot. */
|
|
127
|
+
build(config: { driver: string; name?: string; [key: string]: unknown }): Logger
|
|
128
|
+
withContext(context: Record<string, unknown>): typeof Log
|
|
129
|
+
withoutContext(keys?: string[]): typeof Log
|
|
130
|
+
/** Registers a driver for logging.channels.*.driver. */
|
|
131
|
+
extend(driver: string, factory: (config: any, context: { baseDir: string; environment: string }) => LogTransport | ((entry: LogEntry) => void)): typeof Log
|
|
132
|
+
flush(): void
|
|
133
|
+
}
|
|
@@ -11,9 +11,31 @@ import { currentRequest } from './context.js'
|
|
|
11
11
|
// while a request is handled carry its requestId, which is also sent to
|
|
12
12
|
// the client as X-Request-Id, so a user's report can be matched to logs.
|
|
13
13
|
|
|
14
|
-
|
|
14
|
+
// The eight RFC 5424 levels Laravel uses, plus "silent". "warning" is the
|
|
15
|
+
// same level as "warn".
|
|
16
|
+
export const LOG_LEVELS = {
|
|
17
|
+
debug: 10,
|
|
18
|
+
info: 20,
|
|
19
|
+
notice: 25,
|
|
20
|
+
warn: 30,
|
|
21
|
+
warning: 30,
|
|
22
|
+
error: 40,
|
|
23
|
+
critical: 50,
|
|
24
|
+
alert: 60,
|
|
25
|
+
emergency: 70,
|
|
26
|
+
silent: 100,
|
|
27
|
+
}
|
|
15
28
|
|
|
16
|
-
const COLORS = {
|
|
29
|
+
const COLORS = {
|
|
30
|
+
debug: '\x1b[90m',
|
|
31
|
+
info: '\x1b[36m',
|
|
32
|
+
notice: '\x1b[34m',
|
|
33
|
+
warn: '\x1b[33m',
|
|
34
|
+
error: '\x1b[31m',
|
|
35
|
+
critical: '\x1b[1;31m',
|
|
36
|
+
alert: '\x1b[1;35m',
|
|
37
|
+
emergency: '\x1b[1;41m',
|
|
38
|
+
}
|
|
17
39
|
const RESET = '\x1b[0m'
|
|
18
40
|
|
|
19
41
|
// Lines are collected and written in one batch per turn of the event
|
|
@@ -70,6 +92,33 @@ function prettyValue(value) {
|
|
|
70
92
|
return JSON.stringify(value)
|
|
71
93
|
}
|
|
72
94
|
|
|
95
|
+
// Writes entries to stdout/stderr, as one readable line or one JSON line.
|
|
96
|
+
// It reads the logger's settings on every entry, so configure() applies.
|
|
97
|
+
function consoleTransport(settings) {
|
|
98
|
+
return {
|
|
99
|
+
name: 'console',
|
|
100
|
+
write(entry) {
|
|
101
|
+
const target = entry.toStderr || LOG_LEVELS[entry.level] >= LOG_LEVELS.warn ? settings.errorStream : settings.stream
|
|
102
|
+
const emit = settings.buffer ? (text) => buffered(target, text) : (text) => target.write(text)
|
|
103
|
+
if (settings.format === 'json') {
|
|
104
|
+
emit(JSON.stringify({ time: entry.time.toISOString(), level: entry.level, msg: entry.message, ...plain(entry.fields) }) + '\n')
|
|
105
|
+
return
|
|
106
|
+
}
|
|
107
|
+
const time = entry.time.toTimeString().slice(0, 8)
|
|
108
|
+
const label = entry.level.toUpperCase().padEnd(5)
|
|
109
|
+
const tag = settings.colors ? `${COLORS[entry.level]}${label}${RESET}` : label
|
|
110
|
+
const extras = Object.entries(entry.fields)
|
|
111
|
+
.filter(([, value]) => value !== undefined)
|
|
112
|
+
.map(([key, value]) => `${key}=${prettyValue(value)}`)
|
|
113
|
+
.join(' ')
|
|
114
|
+
emit(`${time} ${tag} ${entry.message}${extras ? ` ${extras}` : ''}\n`)
|
|
115
|
+
},
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
// "warning" is written as "warn", so a level has one name in the output.
|
|
120
|
+
const canonical = (level) => (level === 'warning' ? 'warn' : level)
|
|
121
|
+
|
|
73
122
|
export function createLogger(options = {}) {
|
|
74
123
|
const settings = {
|
|
75
124
|
level: options.level ?? 'info',
|
|
@@ -79,46 +128,95 @@ export function createLogger(options = {}) {
|
|
|
79
128
|
colors: options.colors ?? Boolean(process.stdout.isTTY && process.env.NO_COLOR === undefined),
|
|
80
129
|
// Batch writes (see above). Tests pass false to read lines at once.
|
|
81
130
|
buffer: options.buffer ?? true,
|
|
131
|
+
// Where entries go: the console unless the logging config (Log
|
|
132
|
+
// channels, see logging.js) says otherwise.
|
|
133
|
+
transports: options.transports ?? null,
|
|
134
|
+
// Fields added to every entry of this logger and its children
|
|
135
|
+
// (Log.withContext).
|
|
136
|
+
context: {},
|
|
82
137
|
}
|
|
138
|
+
const console_ = consoleTransport(settings)
|
|
139
|
+
const defaultTransports = () => settings.transports ?? [console_]
|
|
83
140
|
|
|
84
|
-
function make(base) {
|
|
141
|
+
function make(base, pick = defaultTransports) {
|
|
85
142
|
function write(level, message, fields = {}) {
|
|
143
|
+
level = canonical(level)
|
|
86
144
|
if (LOG_LEVELS[level] < LOG_LEVELS[settings.level]) return
|
|
87
145
|
const requestId = currentRequest()?.requestId
|
|
88
|
-
const
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
146
|
+
const entry = {
|
|
147
|
+
time: new Date(),
|
|
148
|
+
level,
|
|
149
|
+
message: String(message),
|
|
150
|
+
fields: { ...settings.context, ...base, ...(requestId ? { requestId } : {}), ...(fields ?? {}) },
|
|
151
|
+
}
|
|
152
|
+
for (const transport of pick()) {
|
|
153
|
+
if (transport.level && LOG_LEVELS[level] < LOG_LEVELS[transport.level]) continue
|
|
154
|
+
try {
|
|
155
|
+
transport.write(entry)
|
|
156
|
+
} catch (err) {
|
|
157
|
+
// A broken channel must never break the request that logged.
|
|
158
|
+
reportTransportFailure(transport, err)
|
|
159
|
+
}
|
|
94
160
|
}
|
|
95
|
-
const time = new Date().toTimeString().slice(0, 8)
|
|
96
|
-
const label = level.toUpperCase().padEnd(5)
|
|
97
|
-
const tag = settings.colors ? `${COLORS[level]}${label}${RESET}` : label
|
|
98
|
-
const extras = Object.entries(all)
|
|
99
|
-
.filter(([, value]) => value !== undefined)
|
|
100
|
-
.map(([key, value]) => `${key}=${prettyValue(value)}`)
|
|
101
|
-
.join(' ')
|
|
102
|
-
emit(`${time} ${tag} ${message}${extras ? ` ${extras}` : ''}\n`)
|
|
103
161
|
}
|
|
104
|
-
|
|
162
|
+
const log = {
|
|
105
163
|
debug: (message, fields) => write('debug', message, fields),
|
|
106
164
|
info: (message, fields) => write('info', message, fields),
|
|
165
|
+
notice: (message, fields) => write('notice', message, fields),
|
|
107
166
|
warn: (message, fields) => write('warn', message, fields),
|
|
167
|
+
warning: (message, fields) => write('warn', message, fields),
|
|
108
168
|
error: (message, fields) => write('error', message, fields),
|
|
109
|
-
|
|
110
|
-
|
|
169
|
+
critical: (message, fields) => write('critical', message, fields),
|
|
170
|
+
alert: (message, fields) => write('alert', message, fields),
|
|
171
|
+
emergency: (message, fields) => write('emergency', message, fields),
|
|
172
|
+
// log('warning', 'Disk almost full')
|
|
173
|
+
log(level, message, fields) {
|
|
174
|
+
if (!(canonical(level) in LOG_LEVELS) || level === 'silent') throw new Error(`Unknown log level "${level}".`)
|
|
175
|
+
write(level, message, fields)
|
|
176
|
+
},
|
|
177
|
+
child: (fields) => make({ ...base, ...fields }, pick),
|
|
178
|
+
// The same logger, writing to other transports (Log.channel()).
|
|
179
|
+
withTransports: (transports) => make(base, () => transports),
|
|
180
|
+
// Adds fields to every later entry of this logger and its children.
|
|
181
|
+
withContext(fields = {}) {
|
|
182
|
+
Object.assign(settings.context, fields)
|
|
183
|
+
return log
|
|
184
|
+
},
|
|
185
|
+
withoutContext(keys) {
|
|
186
|
+
if (!keys) settings.context = {}
|
|
187
|
+
else for (const key of keys) delete settings.context[key]
|
|
188
|
+
return log
|
|
189
|
+
},
|
|
190
|
+
isLevelEnabled: (level) => LOG_LEVELS[canonical(level)] >= LOG_LEVELS[settings.level],
|
|
111
191
|
// Changes this logger and every child of it.
|
|
112
192
|
configure(next = {}) {
|
|
113
193
|
for (const key of Object.keys(settings)) if (next[key] !== undefined) settings[key] = next[key]
|
|
114
194
|
if (next.stream && next.errorStream === undefined) settings.errorStream = next.stream
|
|
115
195
|
},
|
|
196
|
+
// The console writer, so a "console" log channel can reuse it.
|
|
197
|
+
get consoleTransport() {
|
|
198
|
+
return console_
|
|
199
|
+
},
|
|
116
200
|
}
|
|
201
|
+
return log
|
|
117
202
|
}
|
|
118
203
|
if (!(settings.level in LOG_LEVELS)) throw new Error(`Unknown log level "${settings.level}".`)
|
|
119
204
|
return make(options.base ?? {})
|
|
120
205
|
}
|
|
121
206
|
|
|
207
|
+
const failedTransports = new WeakSet()
|
|
208
|
+
function reportTransportFailure(transport, err) {
|
|
209
|
+
if (failedTransports.has(transport)) return
|
|
210
|
+
failedTransports.add(transport)
|
|
211
|
+
try {
|
|
212
|
+
process.stderr.write(`[tylix] log channel "${transport.name ?? 'custom'}" failed: ${err?.message ?? err}\n`)
|
|
213
|
+
} catch {
|
|
214
|
+
// nowhere left to report it
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
export { plain as plainLogFields, serializeError }
|
|
219
|
+
|
|
122
220
|
// The app's logger. "tylix dev" and "tylix start" configure it from
|
|
123
221
|
// LOG_LEVEL / LOG_FORMAT; import it anywhere.
|
|
124
222
|
export const logger = createLogger({
|