Bun App Logs
×


Bun App Logs

1120

📝 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!


Best WordPress Hosting


Share:


Discount Coupons

Unlimited Video Generation

Best Platform to generate videos

Search and buy from Namecheap

Secure Domain for a Minimum Price



Leave a Reply


Comments
    Waiting for your comments

Coding Tag WhatsApp Chat