@logtape/syslog 1.2.1 → 1.2.3

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/src/syslog.ts DELETED
@@ -1,734 +0,0 @@
1
- import type { LogLevel, LogRecord, Sink } from "@logtape/logtape";
2
- import { createSocket } from "node:dgram";
3
- import { Socket } from "node:net";
4
- import { hostname } from "node:os";
5
- import process from "node:process";
6
-
7
- /**
8
- * Syslog protocol type.
9
- * @since 0.12.0
10
- */
11
- export type SyslogProtocol = "udp" | "tcp";
12
-
13
- /**
14
- * Syslog facility codes as defined in RFC 5424.
15
- * @since 0.12.0
16
- */
17
- export type SyslogFacility =
18
- | "kernel" // 0 - kernel messages
19
- | "user" // 1 - user-level messages
20
- | "mail" // 2 - mail system
21
- | "daemon" // 3 - system daemons
22
- | "security" // 4 - security/authorization messages
23
- | "syslog" // 5 - messages generated internally by syslogd
24
- | "lpr" // 6 - line printer subsystem
25
- | "news" // 7 - network news subsystem
26
- | "uucp" // 8 - UUCP subsystem
27
- | "cron" // 9 - clock daemon
28
- | "authpriv" // 10 - security/authorization messages
29
- | "ftp" // 11 - FTP daemon
30
- | "ntp" // 12 - NTP subsystem
31
- | "logaudit" // 13 - log audit
32
- | "logalert" // 14 - log alert
33
- | "clock" // 15 - clock daemon
34
- | "local0" // 16 - local use 0
35
- | "local1" // 17 - local use 1
36
- | "local2" // 18 - local use 2
37
- | "local3" // 19 - local use 3
38
- | "local4" // 20 - local use 4
39
- | "local5" // 21 - local use 5
40
- | "local6" // 22 - local use 6
41
- | "local7"; // 23 - local use 7
42
-
43
- /**
44
- * Syslog facility code mapping.
45
- * @since 0.12.0
46
- */
47
- const FACILITY_CODES: Record<SyslogFacility, number> = {
48
- kernel: 0,
49
- user: 1,
50
- mail: 2,
51
- daemon: 3,
52
- security: 4,
53
- syslog: 5,
54
- lpr: 6,
55
- news: 7,
56
- uucp: 8,
57
- cron: 9,
58
- authpriv: 10,
59
- ftp: 11,
60
- ntp: 12,
61
- logaudit: 13,
62
- logalert: 14,
63
- clock: 15,
64
- local0: 16,
65
- local1: 17,
66
- local2: 18,
67
- local3: 19,
68
- local4: 20,
69
- local5: 21,
70
- local6: 22,
71
- local7: 23,
72
- };
73
-
74
- /**
75
- * Syslog severity levels as defined in RFC 5424.
76
- * @since 0.12.0
77
- */
78
- const SEVERITY_LEVELS: Record<LogLevel, number> = {
79
- fatal: 0, // Emergency: system is unusable
80
- error: 3, // Error: error conditions
81
- warning: 4, // Warning: warning conditions
82
- info: 6, // Informational: informational messages
83
- debug: 7, // Debug: debug-level messages
84
- trace: 7, // Debug: debug-level messages (same as debug)
85
- };
86
-
87
- /**
88
- * Options for the syslog sink.
89
- * @since 0.12.0
90
- */
91
- export interface SyslogSinkOptions {
92
- /**
93
- * The hostname or IP address of the syslog server.
94
- * @default "localhost"
95
- */
96
- readonly hostname?: string;
97
-
98
- /**
99
- * The port number of the syslog server.
100
- * @default 514
101
- */
102
- readonly port?: number;
103
-
104
- /**
105
- * The protocol to use for sending syslog messages.
106
- * @default "udp"
107
- */
108
- readonly protocol?: SyslogProtocol;
109
-
110
- /**
111
- * The syslog facility to use for all messages.
112
- * @default "local0"
113
- */
114
- readonly facility?: SyslogFacility;
115
-
116
- /**
117
- * The application name to include in syslog messages.
118
- * @default "logtape"
119
- */
120
- readonly appName?: string;
121
-
122
- /**
123
- * The hostname to include in syslog messages.
124
- * If not provided, the system hostname will be used.
125
- */
126
- readonly syslogHostname?: string;
127
-
128
- /**
129
- * The process ID to include in syslog messages.
130
- * If not provided, the current process ID will be used.
131
- */
132
- readonly processId?: string;
133
-
134
- /**
135
- * Connection timeout in milliseconds.
136
- * @default 5000
137
- */
138
- readonly timeout?: number;
139
-
140
- /**
141
- * Whether to include structured data in syslog messages.
142
- * @default `false`
143
- */
144
- readonly includeStructuredData?: boolean;
145
-
146
- /**
147
- * The structured data ID to use for log properties.
148
- * Should follow the format "name@private-enterprise-number".
149
- * @default "logtape@32473"
150
- */
151
- readonly structuredDataId?: string;
152
- }
153
-
154
- /**
155
- * Calculates the priority value for a syslog message.
156
- * Priority = Facility * 8 + Severity
157
- * @since 0.12.0
158
- */
159
- function calculatePriority(facility: SyslogFacility, severity: number): number {
160
- const facilityCode = FACILITY_CODES[facility];
161
- return facilityCode * 8 + severity;
162
- }
163
-
164
- /**
165
- * Formats a timestamp (number) as RFC 3339 timestamp for syslog.
166
- * @since 0.12.0
167
- */
168
- function formatTimestamp(timestamp: number): string {
169
- return new Date(timestamp).toISOString();
170
- }
171
-
172
- /**
173
- * Escapes special characters in structured data values.
174
- * @since 0.12.0
175
- */
176
- function escapeStructuredDataValue(value: string): string {
177
- return value
178
- .replace(/\\/g, "\\\\")
179
- .replace(/"/g, '\\"')
180
- .replace(/]/g, "\\]");
181
- }
182
-
183
- /**
184
- * Formats structured data from log record properties.
185
- * @since 0.12.0
186
- */
187
- function formatStructuredData(
188
- record: LogRecord,
189
- structuredDataId: string,
190
- ): string {
191
- if (!record.properties || Object.keys(record.properties).length === 0) {
192
- return "-";
193
- }
194
-
195
- const elements: string[] = [];
196
- for (const [key, value] of Object.entries(record.properties)) {
197
- const escapedValue = escapeStructuredDataValue(String(value));
198
- elements.push(`${key}="${escapedValue}"`);
199
- }
200
-
201
- return `[${structuredDataId} ${elements.join(" ")}]`;
202
- }
203
-
204
- /**
205
- * Formats a log record as RFC 5424 syslog message.
206
- * @since 0.12.0
207
- */
208
- function formatSyslogMessage(
209
- record: LogRecord,
210
- options: Required<
211
- Pick<
212
- SyslogSinkOptions,
213
- | "facility"
214
- | "appName"
215
- | "syslogHostname"
216
- | "processId"
217
- | "includeStructuredData"
218
- | "structuredDataId"
219
- >
220
- >,
221
- ): string {
222
- const severity = SEVERITY_LEVELS[record.level];
223
- const priority = calculatePriority(options.facility, severity);
224
- const timestamp = formatTimestamp(record.timestamp);
225
- const hostname = options.syslogHostname || "-";
226
- const appName = options.appName || "-";
227
- const processId = options.processId || "-";
228
- const msgId = "-"; // Could be enhanced to include message ID
229
-
230
- let structuredData = "-";
231
- if (options.includeStructuredData) {
232
- structuredData = formatStructuredData(record, options.structuredDataId);
233
- }
234
-
235
- // Format the message text
236
- let message = "";
237
- for (let i = 0; i < record.message.length; i++) {
238
- if (i % 2 === 0) {
239
- message += record.message[i];
240
- } else {
241
- message += JSON.stringify(record.message[i]);
242
- }
243
- }
244
-
245
- // RFC 5424 format: <PRI>VERSION TIMESTAMP HOSTNAME APP-NAME PROCID MSGID STRUCTURED-DATA MSG
246
- return `<${priority}>1 ${timestamp} ${hostname} ${appName} ${processId} ${msgId} ${structuredData} ${message}`;
247
- }
248
-
249
- /**
250
- * Gets the system hostname.
251
- * @since 0.12.0
252
- */
253
- function getSystemHostname(): string {
254
- try {
255
- // Try Deno first
256
- if (typeof Deno !== "undefined" && Deno.hostname) {
257
- return Deno.hostname();
258
- }
259
-
260
- // Try Node.js os.hostname()
261
- return hostname();
262
- } catch {
263
- // Fallback to environment variable or localhost
264
- return process.env.HOSTNAME || "localhost";
265
- }
266
- }
267
-
268
- /**
269
- * Gets the current process ID.
270
- * @since 0.12.0
271
- */
272
- function getProcessId(): string {
273
- try {
274
- // Try Deno first
275
- if (typeof Deno !== "undefined" && Deno.pid) {
276
- return Deno.pid.toString();
277
- }
278
-
279
- // Try Node.js
280
- return process.pid.toString();
281
- } catch {
282
- return "-";
283
- }
284
- }
285
-
286
- /**
287
- * Base interface for syslog connections.
288
- * @since 0.12.0
289
- */
290
- export interface SyslogConnection {
291
- connect(): void | Promise<void>;
292
- send(message: string): Promise<void>;
293
- close(): void;
294
- }
295
-
296
- /**
297
- * Deno UDP syslog connection implementation.
298
- * @since 0.12.0
299
- */
300
- export class DenoUdpSyslogConnection implements SyslogConnection {
301
- private encoder = new TextEncoder();
302
-
303
- constructor(
304
- private hostname: string,
305
- private port: number,
306
- private timeout: number,
307
- ) {}
308
-
309
- connect(): void {
310
- // For UDP, we don't need to establish a persistent connection
311
- }
312
-
313
- send(message: string): Promise<void> {
314
- const data = this.encoder.encode(message);
315
-
316
- try {
317
- // Deno doesn't have native UDP support, use Node.js APIs
318
- const socket = createSocket("udp4");
319
-
320
- if (this.timeout > 0) {
321
- return new Promise<void>((resolve, reject) => {
322
- const timeout = setTimeout(() => {
323
- socket.close();
324
- reject(new Error("UDP send timeout"));
325
- }, this.timeout);
326
-
327
- socket.send(data, this.port, this.hostname, (error) => {
328
- clearTimeout(timeout);
329
- socket.close();
330
- if (error) {
331
- reject(error);
332
- } else {
333
- resolve();
334
- }
335
- });
336
- });
337
- } else {
338
- // No timeout
339
- return new Promise<void>((resolve, reject) => {
340
- socket.send(data, this.port, this.hostname, (error) => {
341
- socket.close();
342
- if (error) {
343
- reject(error);
344
- } else {
345
- resolve();
346
- }
347
- });
348
- });
349
- }
350
- } catch (error) {
351
- throw new Error(`Failed to send syslog message: ${error}`);
352
- }
353
- }
354
-
355
- close(): void {
356
- // UDP connections don't need explicit closing
357
- }
358
- }
359
-
360
- /**
361
- * Node.js UDP syslog connection implementation.
362
- * @since 0.12.0
363
- */
364
- export class NodeUdpSyslogConnection implements SyslogConnection {
365
- private encoder = new TextEncoder();
366
-
367
- constructor(
368
- private hostname: string,
369
- private port: number,
370
- private timeout: number,
371
- ) {}
372
-
373
- connect(): void {
374
- // For UDP, we don't need to establish a persistent connection
375
- }
376
-
377
- send(message: string): Promise<void> {
378
- const data = this.encoder.encode(message);
379
-
380
- try {
381
- const socket = createSocket("udp4");
382
-
383
- return new Promise<void>((resolve, reject) => {
384
- const timeout = setTimeout(() => {
385
- socket.close();
386
- reject(new Error("UDP send timeout"));
387
- }, this.timeout);
388
-
389
- socket.send(data, this.port, this.hostname, (error) => {
390
- clearTimeout(timeout);
391
- socket.close();
392
- if (error) {
393
- reject(error);
394
- } else {
395
- resolve();
396
- }
397
- });
398
- });
399
- } catch (error) {
400
- throw new Error(`Failed to send syslog message: ${error}`);
401
- }
402
- }
403
-
404
- close(): void {
405
- // UDP connections don't need explicit closing
406
- }
407
- }
408
-
409
- /**
410
- * Deno TCP syslog connection implementation.
411
- * @since 0.12.0
412
- */
413
- export class DenoTcpSyslogConnection implements SyslogConnection {
414
- private connection?: Deno.TcpConn;
415
- private encoder = new TextEncoder();
416
-
417
- constructor(
418
- private hostname: string,
419
- private port: number,
420
- private timeout: number,
421
- ) {}
422
-
423
- async connect(): Promise<void> {
424
- try {
425
- if (this.timeout > 0) {
426
- // Use AbortController for proper timeout handling
427
- const controller = new AbortController();
428
- const timeoutId = setTimeout(() => {
429
- controller.abort();
430
- }, this.timeout);
431
-
432
- try {
433
- this.connection = await Deno.connect({
434
- hostname: this.hostname,
435
- port: this.port,
436
- transport: "tcp",
437
- signal: controller.signal,
438
- });
439
- clearTimeout(timeoutId);
440
- } catch (error) {
441
- clearTimeout(timeoutId);
442
- if (controller.signal.aborted) {
443
- throw new Error("TCP connection timeout");
444
- }
445
- throw error;
446
- }
447
- } else {
448
- // No timeout
449
- this.connection = await Deno.connect({
450
- hostname: this.hostname,
451
- port: this.port,
452
- transport: "tcp",
453
- });
454
- }
455
- } catch (error) {
456
- throw new Error(`Failed to connect to syslog server: ${error}`);
457
- }
458
- }
459
-
460
- async send(message: string): Promise<void> {
461
- if (!this.connection) {
462
- throw new Error("Connection not established");
463
- }
464
-
465
- const data = this.encoder.encode(message + "\n");
466
-
467
- try {
468
- if (this.timeout > 0) {
469
- // Implement timeout for send using Promise.race
470
- const writePromise = this.connection.write(data);
471
-
472
- const timeoutPromise = new Promise<never>((_, reject) => {
473
- setTimeout(() => {
474
- reject(new Error("TCP send timeout"));
475
- }, this.timeout);
476
- });
477
-
478
- await Promise.race([writePromise, timeoutPromise]);
479
- } else {
480
- // No timeout
481
- await this.connection.write(data);
482
- }
483
- } catch (error) {
484
- throw new Error(`Failed to send syslog message: ${error}`);
485
- }
486
- }
487
-
488
- close(): void {
489
- if (this.connection) {
490
- try {
491
- this.connection.close();
492
- } catch {
493
- // Ignore errors during close
494
- }
495
- this.connection = undefined;
496
- }
497
- }
498
- }
499
-
500
- /**
501
- * Node.js TCP syslog connection implementation.
502
- * @since 0.12.0
503
- */
504
- export class NodeTcpSyslogConnection implements SyslogConnection {
505
- private connection?: Socket;
506
- private encoder = new TextEncoder();
507
-
508
- constructor(
509
- private hostname: string,
510
- private port: number,
511
- private timeout: number,
512
- ) {}
513
-
514
- connect(): Promise<void> {
515
- try {
516
- return new Promise<void>((resolve, reject) => {
517
- const socket = new Socket();
518
-
519
- const timeout = setTimeout(() => {
520
- socket.destroy();
521
- reject(new Error("TCP connection timeout"));
522
- }, this.timeout);
523
-
524
- socket.on("connect", () => {
525
- clearTimeout(timeout);
526
- this.connection = socket;
527
- resolve();
528
- });
529
-
530
- socket.on("error", (error) => {
531
- clearTimeout(timeout);
532
- reject(error);
533
- });
534
-
535
- socket.connect(this.port, this.hostname);
536
- });
537
- } catch (error) {
538
- throw new Error(`Failed to connect to syslog server: ${error}`);
539
- }
540
- }
541
-
542
- send(message: string): Promise<void> {
543
- if (!this.connection) {
544
- throw new Error("Connection not established");
545
- }
546
-
547
- const data = this.encoder.encode(message + "\n");
548
-
549
- try {
550
- return new Promise<void>((resolve, reject) => {
551
- this.connection!.write(data, (error?: Error | null) => {
552
- if (error) {
553
- reject(error);
554
- } else {
555
- resolve();
556
- }
557
- });
558
- });
559
- } catch (error) {
560
- throw new Error(`Failed to send syslog message: ${error}`);
561
- }
562
- }
563
-
564
- close(): void {
565
- if (this.connection) {
566
- try {
567
- this.connection.end();
568
- } catch {
569
- // Ignore errors during close
570
- }
571
- this.connection = undefined;
572
- }
573
- }
574
- }
575
-
576
- /**
577
- * Creates a syslog sink that sends log messages to a syslog server using the
578
- * RFC 5424 syslog protocol format.
579
- *
580
- * This sink supports both UDP and TCP protocols for reliable log transmission
581
- * to centralized logging systems. It automatically formats log records according
582
- * to RFC 5424 specification, including structured data support for log properties.
583
- *
584
- * ## Features
585
- *
586
- * - **RFC 5424 Compliance**: Full implementation of the RFC 5424 syslog protocol
587
- * - **Cross-Runtime Support**: Works with Deno, Node.js, Bun, and browsers
588
- * - **Multiple Protocols**: Supports both UDP (fire-and-forget) and TCP (reliable) delivery
589
- * - **Structured Data**: Automatically includes log record properties as RFC 5424 structured data
590
- * - **Facility Support**: All standard syslog facilities (kern, user, mail, daemon, local0-7, etc.)
591
- * - **Automatic Escaping**: Proper escaping of special characters in structured data values
592
- * - **Connection Management**: Automatic connection handling with configurable timeouts
593
- *
594
- * ## Protocol Differences
595
- *
596
- * - **UDP**: Fast, connectionless delivery suitable for high-throughput logging.
597
- * Messages may be lost during network issues but has minimal performance impact.
598
- * - **TCP**: Reliable, connection-based delivery that ensures message delivery.
599
- * Higher overhead but guarantees that log messages reach the server.
600
- *
601
- * @param options Configuration options for the syslog sink
602
- * @returns A sink function that sends log records to the syslog server, implementing AsyncDisposable for proper cleanup
603
- *
604
- * @example Basic usage with default options
605
- * ```typescript
606
- * import { configure } from "@logtape/logtape";
607
- * import { getSyslogSink } from "@logtape/syslog";
608
- *
609
- * await configure({
610
- * sinks: {
611
- * syslog: getSyslogSink(), // Sends to localhost:514 via UDP
612
- * },
613
- * loggers: [
614
- * { category: [], sinks: ["syslog"], lowestLevel: "info" },
615
- * ],
616
- * });
617
- * ```
618
- *
619
- * @example Custom syslog server configuration
620
- * ```typescript
621
- * import { configure } from "@logtape/logtape";
622
- * import { getSyslogSink } from "@logtape/syslog";
623
- *
624
- * await configure({
625
- * sinks: {
626
- * syslog: getSyslogSink({
627
- * hostname: "log-server.example.com",
628
- * port: 1514,
629
- * protocol: "tcp",
630
- * facility: "mail",
631
- * appName: "my-application",
632
- * timeout: 10000,
633
- * }),
634
- * },
635
- * loggers: [
636
- * { category: [], sinks: ["syslog"], lowestLevel: "debug" },
637
- * ],
638
- * });
639
- * ```
640
- *
641
- * @example Using structured data for log properties
642
- * ```typescript
643
- * import { configure, getLogger } from "@logtape/logtape";
644
- * import { getSyslogSink } from "@logtape/syslog";
645
- *
646
- * await configure({
647
- * sinks: {
648
- * syslog: getSyslogSink({
649
- * includeStructuredData: true,
650
- * structuredDataId: "myapp@12345",
651
- * }),
652
- * },
653
- * loggers: [
654
- * { category: [], sinks: ["syslog"], lowestLevel: "info" },
655
- * ],
656
- * });
657
- *
658
- * const logger = getLogger();
659
- * // This will include userId and action as structured data
660
- * logger.info("User action completed", { userId: 123, action: "login" });
661
- * // Results in: <134>1 2024-01-01T12:00:00.000Z hostname myapp 1234 - [myapp@12345 userId="123" action="login"] User action completed
662
- * ```
663
- *
664
- * @since 0.12.0
665
- * @see {@link https://tools.ietf.org/html/rfc5424} RFC 5424 - The Syslog Protocol
666
- * @see {@link SyslogSinkOptions} for detailed configuration options
667
- */
668
- export function getSyslogSink(
669
- options: SyslogSinkOptions = {},
670
- ): Sink & AsyncDisposable {
671
- const hostname = options.hostname ?? "localhost";
672
- const port = options.port ?? 514;
673
- const protocol = options.protocol ?? "udp";
674
- const facility = options.facility ?? "local0";
675
- const appName = options.appName ?? "logtape";
676
- const syslogHostname = options.syslogHostname ?? getSystemHostname();
677
- const processId = options.processId ?? getProcessId();
678
- const timeout = options.timeout ?? 5000;
679
- const includeStructuredData = options.includeStructuredData ?? false;
680
- const structuredDataId = options.structuredDataId ?? "logtape@32473";
681
-
682
- const formatOptions = {
683
- facility,
684
- appName,
685
- syslogHostname,
686
- processId,
687
- includeStructuredData,
688
- structuredDataId,
689
- };
690
-
691
- // Create connection based on protocol and runtime
692
- const connection: SyslogConnection = (() => {
693
- if (typeof Deno !== "undefined") {
694
- // Deno runtime
695
- return protocol === "tcp"
696
- ? new DenoTcpSyslogConnection(hostname, port, timeout)
697
- : new DenoUdpSyslogConnection(hostname, port, timeout);
698
- } else {
699
- // Node.js runtime (and Bun, which uses Node.js APIs)
700
- return protocol === "tcp"
701
- ? new NodeTcpSyslogConnection(hostname, port, timeout)
702
- : new NodeUdpSyslogConnection(hostname, port, timeout);
703
- }
704
- })();
705
-
706
- let isConnected = false;
707
- let lastPromise = Promise.resolve();
708
-
709
- const sink: Sink & AsyncDisposable = (record: LogRecord) => {
710
- const syslogMessage = formatSyslogMessage(record, formatOptions);
711
-
712
- lastPromise = lastPromise
713
- .then(async () => {
714
- if (!isConnected) {
715
- await connection.connect();
716
- isConnected = true;
717
- }
718
- await connection.send(syslogMessage);
719
- })
720
- .catch((error) => {
721
- // If connection fails, try to reconnect on next message
722
- isConnected = false;
723
- throw error;
724
- });
725
- };
726
-
727
- sink[Symbol.asyncDispose] = async () => {
728
- await lastPromise.catch(() => {}); // Wait for any pending operations
729
- connection.close();
730
- isConnected = false;
731
- };
732
-
733
- return sink;
734
- }