sleek-logger
v1.3.1
Published
Sleek structured logger for TypeScript/Node.js with dual syntax support - traditional method calls and modern template literals
Maintainers
Readme
Sleek Logger
Sleek Logger is a structured logger for TypeScript/Node.js inspired by Go's slog, designed to simplify logging with key-value pairs. It supports both plain text and JSON formats, with context fields being logged as top-level keys such as username and request_id. Features dual syntax support with traditional method calls and modern template literal syntax.
Installation
Install Sleek Logger via npm:
npm install sleek-loggerBasic Usage
Logger logs messages along with additional context in a flat structure. Here's an example using the JSON format:
JSON Logging Example
import { Logger } from 'sleek-logger';
// Create SLogger instance with JSON format
let logger = new Logger({ format: "json" });
// Add initial context with username
logger = logger.withFields({ username: "johndoe" });
// Log a message with initial context
logger.info("User initialized session", { request_id: "abc123" });
// Log output:
// {
// "level": "INFO",
// "timestamp": "2024-01-15T10:30:00.000Z",
// "message": "User initialized session",
// "username": "johndoe",
// "request_id": "abc123"
// }Template Literal Syntax
Logger also supports modern template literal syntax with named parameters:
import { Logger } from 'sleek-logger';
const logger = new Logger({ format: "json" });
// Using template literals with named parameters
const userId = 123;
const requestId = "abc123";
logger.info`User ${{ userId }} initialized session ${{ requestId }}`;
// Log output:
// {
// "level": "INFO",
// "timestamp": "2024-01-15T10:30:00.000Z",
// "message": "User 123 initialized session abc123",
// "userId": 123,
// "requestId": "abc123"
// }Using .withFields()
The .withFields() method allows you to persist fields across multiple log calls. Each call to .withFields() returns a new Logger instance with the added fields, leaving the original context unchanged.
Example:
// Adding fields using .withFields()
logger = logger.withFields({ username: "johndoe", request_id: "abc123" });
// Logging with the updated context
logger.info("Performed a profile update", { action: "update_profile" });
// Log output:
// {
// "level": "INFO",
// "timestamp": "2024-01-15T10:30:00.000Z",
// "message": "Performed a profile update",
// "username": "johndoe",
// "request_id": "abc123",
// "action": "update_profile"
// }Template Literal with Context:
// Using template literals with existing context
const contextLogger = logger.withFields({ username: "johndoe" });
const action = "update_profile";
contextLogger.info`User performed ${{ action }}`;
// Log output includes both the context field and the named parameterAdding Context
You can continue adding fields with subsequent calls to .withFields(), merging new context with existing fields. This allows for flexibility when extending the log context.
Example with Added Context:
// Initial logger with username field
logger = logger.withFields({ username: "johndoe" });
// Adding more context with action and request_id
logger = logger.withFields({ action: "login", request_id: "def456" });
logger.info("Login successful");
// Log output:
// {
// "level": "INFO",
// "timestamp": "2024-01-15T10:30:00.000Z",
// "message": "Login successful",
// "username": "johndoe",
// "request_id": "def456",
// "action": "login"
// }Plain Text Format
For development and console output, use the plain text format:
const logger = new Logger({ format: "plain" });
logger.info("User logged in", { userId: 123, sessionId: "xyz789" });
// Output: [INFO] [2:40 PM] User logged in, userId=123, sessionId="xyz789"
// Template literal syntax
logger.info`User ${{ userId: 123 }} logged in`;
// Output: [INFO] [2:40 PM] User 123 logged in, userId=123Log Levels
Logger supports the following log levels:
import { LogLevel } from 'sleek-logger';
logger.debug("Debug message"); // LogLevel.DEBUG (10)
logger.info("Info message"); // LogLevel.INFO (20)
logger.warning("Warning message"); // LogLevel.WARNING (30)
logger.error("Error message"); // LogLevel.ERROR (40)
logger.critical("Critical message"); // LogLevel.CRITICAL (50)All methods support both traditional and template literal syntax:
// Traditional syntax
logger.error("Database connection failed", { connection_id: "db1", retry_count: 3 });
// Template literal syntax
const connectionId = "db1";
const retryCount = 3;
logger.error`Database connection ${{ connectionId }} failed after ${{ retryCount }} retries`;Configuration
Full Config
import { Logger, LogLevel } from 'sleek-logger';
import type { LogConfig } from 'sleek-logger';
const fullConfig: LogConfig = {
override: {
debug: console.debug,
info: console.info,
warn: console.warn,
error: console.error
},
colors: {
DEBUG: "\x1b[34m", // Blue
INFO: "\x1b[32m", // Green
WARNING: "\x1b[33m", // Yellow
ERROR: "\x1b[31m", // Red
CRITICAL: "\x1b[35m", // Magenta
reset: "\x1b[0m"
},
format: "json",
jsonFormatter: (obj) => JSON.stringify(obj, null, 2),
showCallerInfo: true,
logLevel: LogLevel.INFO
};
// Create Logger instance with the full configuration
const logger = new Logger(fullConfig);Override Defaults
// Same as new default config with just format and showCallerInfo overridden
const logger = new Logger({
format: 'json',
showCallerInfo: true
});