All posts

Svelte Logging Best Practices

Implement production-ready logging in Svelte and SvelteKit applications with server hooks, client error capture, and structured log formatting.

Svelte Logging Best Practices

SvelteKit runs on both server and client. Your logging strategy needs to cover both.

Server-Side Logging with Hooks

// src/hooks.server.ts
import type { Handle, HandleServerError } from '@sveltejs/kit';

export const handle: Handle = async ({ event, resolve }) => {
  const requestId = crypto.randomUUID();
  event.locals.requestId = requestId;
  const start = performance.now();

  const response = await resolve(event);
  const duration = performance.now() - start;

  console.log(JSON.stringify({
    type: 'request',
    requestId,
    method: event.request.method,
    path: event.url.pathname,
    status: response.status,
    duration_ms: Math.round(duration),
  }));

  return response;
};

export const handleError: HandleServerError = ({ error, event }) => {
  console.error(JSON.stringify({
    type: 'error',
    requestId: event.locals.requestId,
    message: error instanceof Error ? error.message : 'Unknown error',
    stack: error instanceof Error ? error.stack : undefined,
    path: event.url.pathname,
  }));

  return {
    message: 'Internal server error',
  };
};

Client-Side Error Logging

// src/hooks.client.ts
import type { HandleClientError } from '@sveltejs/kit';

export const handleError: HandleClientError = ({ error, message }) => {
  console.error('Client error:', error);

  // Send to logging endpoint
  fetch('/api/log', {
    method: 'POST',
    body: JSON.stringify({
      type: 'client_error',
      message: error instanceof Error ? error.message : message,
      stack: error instanceof Error ? error.stack : undefined,
      url: window.location.href,
      userAgent: navigator.userAgent,
    }),
    keepalive: true,
  }).catch(() => {}); // Don't let logging failures break the app

  return { message: 'Something went wrong' };
};

Structured Logging in Server Routes

// src/routes/api/orders/+server.ts
import type { RequestHandler } from './$types';

export const POST: RequestHandler = async ({ request, locals }) => {
  const logger = createLogger(locals.requestId);

  logger.info('Creating order', { userId: locals.user.id });

  try {
    const order = await createOrder(await request.json());
    logger.info('Order created', { orderId: order.id });
    return json(order, { status: 201 });
  } catch (error) {
    logger.error('Order creation failed', { error: error.message });
    throw error;
  }
};

What to Log

  • All requests — method, path, status, duration
  • Business events — order created, user signed up
  • Errors — with full context and request ID
  • External calls — API requests with latency

Connect Bugsly for comprehensive error tracking across both server and client contexts in your SvelteKit application.

Try Bugsly Free

AI-powered error tracking that explains your bugs. Set up in 2 minutes, free forever for small projects.

Get Started Free