feat: add debug logging

Add debug logs using the `debug` library.

To use this new feature, set the `DEBUG` environment variable:
- `DEBUG=mineping:*` enables all logs from this library.
- `DEBUG=mineping:java` enables logs for the Java module only.
- `DEBUG=mineping:bedrock` enables logs for the Bedrock module only.
This commit is contained in:
2025-06-19 02:14:04 +03:00
parent c7b99cb6db
commit 7322034aba
4 changed files with 45 additions and 5 deletions

View File

@ -7,6 +7,9 @@
import dgram from "node:dgram";
import crypto from "node:crypto";
import createDebug from "debug";
const debug = createDebug("mineping:bedrock");
const MAGIC = "00ffff00fefefefefdfdfdfd12345678";
const START_TIME = Date.now();
@ -177,6 +180,7 @@ const parseUnconnectedPong = (pongPacket) => {
motdOffset,
motdOffset + motdLength
);
debug("received raw MOTD string: %s", motdString);
const rawMotd = parseMotd(motdString);
const motd = transformMotd(rawMotd);
@ -197,6 +201,7 @@ export const pingBedrock = (host, options = {}) => {
}
const { port = 19132, timeout = 5000 } = options;
debug("pinging Bedrock server %s:%d with %dms timeout", host, port, timeout);
return new Promise((resolve, reject) => {
const socket = dgram.createSocket("udp4");
@ -215,17 +220,20 @@ export const pingBedrock = (host, options = {}) => {
const cleanup = () => {
if (isCleanupCompleted) return;
isCleanupCompleted = true;
debug("cleaning up resources for %s:%d", host, port);
clearTimeout(timeoutTask);
socket.close();
};
// Generic error handler
socket.on("error", (err) => {
debug("socket error for %s:%d - %s", host, port, err.message);
cleanup();
reject(err);
});
socket.on("message", (pongPacket) => {
debug("received %d bytes from %s:%d", pongPacket.length, host, port);
try {
const motd = parseUnconnectedPong(pongPacket);
cleanup();
@ -237,6 +245,8 @@ export const pingBedrock = (host, options = {}) => {
try {
const pingPacket = createUnconnectedPingFrame(Date.now() - START_TIME);
debug("sending Unconnected Ping packet to %s:%d", host, port);
debug("packet: %o", pingPacket);
socket.send(pingPacket, 0, pingPacket.length, port, host);
} catch (err) {
// Handle any immediate, synchronous errors that might occur when sending the ping packet