Deno nuggets: Log listening message
This article is a part of the Deno nuggets series, where each article attempts to suggest a pointed solution to a specific question that can be read in less than a minute. There is no ordering of nuggets.
Problem
How to log the HTTP server listening message that goes to console by default?
~: deno run --no-prompt --allow-net=:8000 app.ts
Listening on http://localhost:8000/
Solution
The solution is to simply provide a listening callback through the onListen attribute in the options bag of the serve API. The listen callback can take an object as input that contains:
- hostname
- port
The callback function can log the listening data anywhere it likes, such as log files, etc.
Here is the updated server code that logs the listening message in a log file:
import { serve } from "https://deno.land/std/http/mod.ts";async function logListen(data: any) {
await Deno.writeTextFile(
"./httpServer.log",
`HTTP server listening on ${data.hostname}:${data.port}`,
{ append: true },
);
}serve((_) => new Response("Hello from Deno!"), { onListen: logListen });
Let’s run it:
~: deno run --no-prompt --allow-net=:8000 --allow-write=. app.ts~: cat ./httpServer.log
HTTP server listening on 0.0.0.0:8000