UNPKG

@logtail/node

Version:
89 lines 3.41 kB
import { encode } from "@msgpack/msgpack"; import http from "node:http"; import https from "node:https"; import zlib from "node:zlib"; import { Base } from "@logtail/core"; import { getStackContext } from "./context"; export class Node extends Base { constructor(sourceToken, options) { super(sourceToken, options); const agent = this.createAgent(); // Sync function const sync = async (logs) => { const request = this.getHttpModule().request(this._options.endpoint, { method: "POST", headers: { "Content-Type": "application/msgpack", "Content-Encoding": "gzip", Authorization: `Bearer ${this._sourceToken}`, "User-Agent": "logtail-js(node)", }, agent, }); const response = await new Promise((resolve, reject) => { request.on("response", resolve); request.on("error", reject); // Compress the logs using gzip zlib.gzip(this.encodeAsMsgpack(logs), (err, compressedData) => { if (err) { reject(err); return; } request.write(compressedData); request.end(); }); }); if (response.statusCode && response.statusCode >= 200 && response.statusCode < 300) { return logs; } throw new Error(response.statusMessage); }; // Set the throttled sync function this.setSync(sync); } /** * Override `Base` log to enable Node.js streaming * * @param message: string - Log message * @param level (LogLevel) - Level to log at (debug|info|warn|error) * @param context: (Context) - Log context for passing structured data * @param stackContextHint: (StackContextHint|null) - Info about which methods to consider as origin in context.runtime * @returns Promise<ILogtailLog> after syncing */ async log(message, level, context = {}, stackContextHint) { // Process/sync the log, per `Base` logic context = Object.assign(Object.assign({}, getStackContext(this, stackContextHint)), context); const processedLog = await super.log(message, level, context); // Push the processed log to the stream, for piping if (this._writeStream) { this._writeStream.write(JSON.stringify(processedLog) + "\n"); } // Return the transformed log return processedLog; } /** * Pipe JSON stringified `ILogtailLog` to a stream after syncing * * @param stream - Writable|Duplex stream */ pipe(stream) { this._writeStream = stream; return stream; } encodeAsMsgpack(logs) { const encoded = encode(logs); const buffer = Buffer.from(encoded.buffer, encoded.byteOffset, encoded.byteLength); return buffer; } createAgent() { const nodeOptions = this._options; const family = nodeOptions.useIPv6 ? 6 : 4; return new (this.getHttpModule().Agent)({ family, }); } getHttpModule() { return this._options.endpoint.startsWith("https") ? https : http; } } //# sourceMappingURL=node.js.map