Bun App Logs
×


Bun App Logs

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!


Best WordPress Hosting


Share:


Discount Coupons

Get a .COM for just $6.98

Secure Domain for a Mini Price



Leave a Reply


Comments
    Waiting for your comments

Coding Tag WhatsApp Chat