Bun App Logs
0 107
๐ Introduction to Bun App Logs
Logs are your appโs black box โ๏ธโ a running journal of everything happening under the hood. Whether you're debugging issues, monitoring requests, or tracking unexpected behaviors, logging is crucial for Bun apps in both development and production.
In this blog, weโll explore how to implement logging in Bun, log requests/responses, handle error logs, and even push logs to external services or structured log files.
๐ฆ Why Logging Matters in Bun Apps
Bun is blazing fast and developer-friendly, but even the fastest server can fail if you donโt know whatโs going wrong. Hereโs why Bun app logs matter:
- ๐ชต Track API usage and traffic
- ๐ง Debug crashes and failed requests
- ๐ต๏ธโโ๏ธ Understand user behavior
- ๐ Identify performance bottlenecks
๐ Basic Logging with console.log
For quick diagnostics, console.log
is your first tool. Here's a basic example inside a Bun server:
const server = Bun.serve({
port: 3000,
fetch(req) {
console.log(`[INFO] ${new Date().toISOString()} - ${req.method} ${req.url}`);
return new Response("Bun is logging ๐ฅ");
}
});
This will print each incoming request with a timestamp, making it easy to follow the serverโs activity.
๐ Logging Request Details
Want to go deeper? Log headers, query params, or IP addresses:
fetch(req) {
const ip = req.headers.get("x-forwarded-for") || "unknown";
console.log(`[INFO] Request from IP: ${ip}`);
console.log(`[DEBUG] Headers:`, JSON.stringify(Object.fromEntries(req.headers)));
return new Response("Detailed log โ
");
}
Useful for rate-limiting, geo-location, or debugging client-specific issues.
๐จ Logging Errors with console.error
Don't just log successful stuff. Catch and log errors too:
try {
throw new Error("Oops! Something broke.");
} catch (err) {
console.error(`[ERROR] ${err.message} at ${new Date().toISOString()}`);
}
Use different log levels like console.warn
, console.info
, and console.error
to separate logs by severity.
๐ Writing Logs to a File
Want persistent logs? Write to a file using Bunโs file system:
const logFile = Bun.file("logs/server.log");
function writeLog(message) {
Bun.write(logFile, `${new Date().toISOString()} ${message}\n`, { append: true });
}
// Usage
writeLog("[INFO] Server started");
This is useful for production deployments or archival purposes. Make sure you rotate logs if the file grows too large.
๐ฌ Sending Logs to Remote Log Services
To centralize logs from multiple servers or environments, send them to a cloud-based service like Logtail, Papertrail, or Elastic Stack:
await fetch("https://in.logtail.com", {
method: "POST",
headers: {
Authorization: "Bearer YOUR_API_KEY",
"Content-Type": "application/json"
},
body: JSON.stringify({
message: "๐ Bun API /start triggered",
level: "info",
timestamp: new Date().toISOString()
})
});
This lets you visualize and filter logs in real-time dashboards.
๐ง Custom Logger Utility Function
Letโs encapsulate all log types in a utility:
function logger(type, message) {
const timestamp = new Date().toISOString();
const formatted = `[${type.toUpperCase()}] ${timestamp} - ${message}`;
console.log(formatted);
Bun.write("logs/app.log", formatted + "\n", { append: true });
}
Now you can call:
logger("info", "New request to /api/users");
logger("error", "Database connection failed!");
This keeps logs clean, uniform, and scalable across your app.
๐ Real-time Log Streaming with WebSocket
Want to see logs live in a dashboard or another app? Use WebSocket to stream them:
const server = Bun.serve({
websocket: {
open(ws) {
ws.send("๐ก Live log stream started");
},
message(ws, msg) {
console.log("[LIVE LOG]", msg);
}
},
port: 4000
});
Perfect for building a real-time monitoring dashboard with minimal tools.
๐งฐ Tools That Work Well with Bun Logs
- PM2 โ Great for log management and process control
- SigNoz โ Open-source observability tool with Bun support
- LogDNA / Papertrail โ For hosted log analytics
๐ Wrapping Up: Logging is Your Lifeline
Logs are not just for fixing bugs โ they tell the story of your app ๐. With Bun, you have the flexibility to build your own logging system or plug into industry-standard tools.
Whether you're console-logging locally, writing to files, or pushing logs to a dashboard โ make sure you never run a production server blind.
If youโre passionate about building a successful blogging website, check out this helpful guide at Coding Tag โ How to Start a Successful Blog. It offers practical steps and expert tips to kickstart your blogging journey!
For dedicated UPSC exam preparation, we highly recommend visiting www.iasmania.com. It offers well-structured resources, current affairs, and subject-wise notes tailored specifically for aspirants. Start your journey today!

Share:
Comments
Waiting for your comments