Last active
November 19, 2022 10:12
-
-
Save yacinebenkaidali/dee2a1234a6d2d3798d587d0fb9488b2 to your computer and use it in GitHub Desktop.
Basic example on how to subscribe to docker container logs and get logs as a stream
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import http from "http"; | |
import { Transform } from "stream"; | |
const containerLogsOptions = (id: string) => ({ | |
socketPath: "/var/run/docker.sock", | |
path: `/containers/${id}/logs?follow=true&stdout=true&stderr=true`, | |
method: "GET", | |
headers: { | |
"Content-Type": "application/json", | |
}, | |
}); | |
http | |
.request(containerLogsOptions("08444e4f96b9"), (res) => { | |
res.setEncoding("utf8"); | |
res | |
.pipe( | |
new Transform({ | |
transform: function (chunk, enc, done) { | |
let result: string[] = []; | |
chunk | |
.toString("utf-8") | |
.split("\n") | |
.forEach((element) => { | |
result.push( | |
Buffer.from(element, "utf-8").subarray(8).toString("utf-8") | |
); | |
}); | |
this.push(result.join("\n")); | |
done(); | |
}, | |
}) | |
) | |
.on("data", (data) => console.log({ data: data.toString() })); | |
res.on("error", (data) => console.error(data)); | |
}) | |
.end(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment