Skip to content

KrataiB/elysia-logger

Folders and files

NameName
Last commit message
Last commit date

Latest commit

ย 

History

18 Commits
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 

Repository files navigation

Elysia Logger

npm version License: MIT

A high-performance, NestJS-style logger plugin for ElysiaJS with beautiful console output and flexible configuration.

Author: KrataiB

โœจ Features

  • ๐ŸŽจ NestJS-Style UI - Beautiful, colorful console output
  • โšก High Performance - Built on pino, one of the fastest Node.js loggers
  • ๐Ÿ“ Hybrid Logging - Console (pretty) + File (JSON) simultaneously
  • ๐Ÿ”ง Fully Configurable - Customize everything from log levels to formats
  • ๐Ÿ“Š Request Details - Log query params, path params, and request bodies
  • ๐ŸŽฏ Type-Safe - Full TypeScript support with proper type inference
  • ๐Ÿš€ Zero Dependencies Overhead - Only pino and picocolors

โšก Benchmark

Benchmark Results

๐Ÿ“ฆ Installation

# Using bun (recommended)
bun add elysia-logger

# Using npm
npm install elysia-logger

# Using yarn
yarn add elysia-logger

# Using pnpm
pnpm add elysia-logger

๐Ÿš€ Quick Start

import { Elysia } from "elysia";
import { logger } from "elysia-logger";

const app = new Elysia()
  .use(logger())
  .get("/", () => "Hello World")
  .listen(3000);

That's it! You'll now see beautiful logs like:

[Elysia] 12345  - 11/21/2025, 2:00:00 PM   INFO [Elysia] ๐ŸฆŠ Elysia is running at http://localhost:3000
[Elysia] 12345  - 11/21/2025, 2:00:00 PM   INFO [Elysia] Routes:
[Elysia] 12345  - 11/21/2025, 2:00:00 PM   INFO [Router] GET /
[Elysia] 12345  - 11/21/2025, 2:00:05 PM   INFO [Router] GET / +2ms

๐Ÿ“– Configuration

Basic Options

import { logger } from "elysia-logger";

app.use(
  logger({
    // Transport type: 'console' (pretty) or 'json'
    transport: "console", // default

    // Enable/disable all logging
    enabled: true, // default

    // Log level: 'fatal' | 'error' | 'warn' | 'info' | 'debug' | 'trace'
    level: "info", // default

    // Context name for logs
    context: "MyApp", // default: 'Elysia'

    // Custom server name for logs
    name: "MyServer", // default: 'Elysia'
  })
);

File Logging

Log to a file in JSON format (perfect for production):

app.use(
  logger({
    file: "./app.log",
  })
);

Hybrid Mode - Both console (pretty) AND file (JSON):

app.use(
  logger({
    transport: "console", // Pretty console output
    file: "./app.log", // JSON file output
  })
);

Request Logging Options

app.use(
  logger({
    // Auto-log all requests/responses
    autoLogging: true, // default

    // Log request start (before processing)
    logRequestStart: false, // default: true

    // Log request details (params, query, body)
    logDetails: true, // default: false
  })
);

Example with logDetails: true:

[Router] POST /user/123 +5ms {"params":{"id":"123"},"body":{"name":"John","email":"[email protected]"}}

Custom Formatter

Define your own log format:

app.use(
  logger({
    formatter: (level, message, context) => {
      return `[${level.toUpperCase()}] ${context}: ${message}`;
    },
  })
);

๐ŸŽฏ Advanced Usage

Using the Logger Manually

Access the logger instance via ctx.log:

app.get("/custom", (ctx) => {
  ctx.log.log("This is an info message", "MyContext");
  ctx.log.error("Something went wrong!", "Error stack trace", "ErrorContext");
  ctx.log.warn("Warning message");
  ctx.log.debug("Debug info");
  ctx.log.verbose("Verbose logging");

  return "Done";
});

Standalone Logger

Use the Logger class independently:

import { Logger } from "elysia-logger";

const log = new Logger({
  transport: "console",
  level: "debug",
});

log.log("Hello from standalone logger!");
log.error("Error message", "Stack trace");

๐Ÿšจ Error Handling

Elysia Logger comes with a built-in HttpError class (similar to elysia-http-error) for easy error handling:

import { Elysia } from "elysia";
import { logger, HttpError } from "elysia-logger";

const app = new Elysia()
  .use(logger())
  .get("/not-found", () => {
    throw HttpError.NotFound("Resource not found");
  })
  .get("/bad-request", () => {
    throw HttpError.BadRequest("Invalid input");
  })
  .get("/custom-error", () => {
    throw new HttpError(418, "I'm a teapot");
  });

Available static methods:

  • HttpError.BadRequest(message?) (400)
  • HttpError.Unauthorized(message?) (401)
  • HttpError.Forbidden(message?) (403)
  • HttpError.NotFound(message?) (404)
  • HttpError.MethodNotAllowed(message?) (405)
  • HttpError.Conflict(message?) (409)
  • HttpError.PreconditionFailed(message?) (412)
  • HttpError.UnprocessableEntity(message?) (422)
  • HttpError.TooManyRequests(message?) (429)
  • HttpError.InternalServerError(message?) (500)

๐Ÿ“Š Complete Example

import { Elysia } from "elysia";
import { logger } from "elysia-logger";

const app = new Elysia()
  .use(
    logger({
      transport: "console",
      file: "./logs/app.log",
      level: "info",
      logDetails: true,
      logRequestStart: false,
    })
  )
  .get("/", () => "Hello World")
  .get("/user/:id", ({ params, log }) => {
    log.log(`Fetching user ${params.id}`, "UserController");
    return { user: params.id };
  })
  .post("/create", ({ body, log }) => {
    log.log("Creating new item", "CreateController");
    return { created: true };
  })
  .onError(({ error, log }) => {
    log.error("Unhandled error", error.stack, "GlobalError");
    return { error: error.message };
  })
  .listen(3000);

console.log("Server running on http://localhost:3000");

๐Ÿ“ API Reference

LoggerOptions

Option Type Default Description
transport 'console' | 'json' 'console' Output format
enabled boolean true Enable/disable logging
level 'fatal' | 'error' | 'warn' | 'info' | 'debug' | 'trace' 'info' Minimum log level
context string 'Elysia' Default context name
name string 'Elysia' Custom server name
file string undefined File path for JSON logs
autoLogging boolean true Auto-log requests/responses
logRequestStart boolean true Log when request starts
logDetails boolean false Log request params/query/body
formatter (level, message, context?) => string undefined Custom format function

Logger Class Methods

class Logger {
  log(message: string, context?: string): void;
  error(message: string, trace?: string, context?: string): void;
  warn(message: string, context?: string): void;
  debug(message: string, context?: string): void;
  verbose(message: string, context?: string): void;
}

๐ŸŽจ Log Levels

Logs are color-coded by level:

  • ๐ŸŸข INFO - Green
  • ๐Ÿ”ด ERROR - Red
  • ๐ŸŸก WARN - Yellow
  • ๐Ÿ”ต DEBUG - Blue
  • ๐Ÿ”ท VERBOSE - Cyan

๐Ÿ”’ Production Best Practices

Recommended Production Config

app.use(
  logger({
    transport: "json", // Structured logs for log aggregators
    file: "./logs/app.log", // Persist to file
    level: "info", // Filter out debug/verbose
    logDetails: false, // Avoid logging sensitive data
    logRequestStart: false, // Reduce log noise
  })
);

Log Rotation

For production, use a log rotation tool like logrotate or pm2.

๐Ÿงช Testing

bun test

๐Ÿ“„ License

MIT ยฉ KrataiB

๐Ÿค Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

๐Ÿ“ฎ Issues

Found a bug? Have a feature request? Please open an issue.

๐ŸŒŸ Show Your Support

Give a โญ๏ธ if this project helped you!


Built with โค๏ธ for the Elysia community

About

No description, website, or topics provided.

Resources

License

Stars

Watchers

Forks

Packages

No packages published