@apexmcp/logger
v1.0.0
Published
Universal logging utility for TypeScript applications. Supports structured logging, multiple log levels, and context tracking.
Maintainers
Readme
@apexmcp/logger
A universal logging utility for TypeScript applications with structured logging, multiple log levels, and context support. Works seamlessly across Bun, Deno, and Node.js environments.
Features
- ✅ Multiple log levels (DEBUG, INFO, LOG, WARN, ERROR)
- ✅ Structured logging with context support
- ✅ Child loggers for hierarchical logging
- ✅ Environment variable configuration (
LOG_LEVEL) - ✅ TypeScript support with full type safety
- ✅ Universal compatibility (Bun, Deno, Node.js)
- ✅ Zero dependencies
- ✅ ESM and CommonJS support
Installation
# Using bun
bun add @apexmcp/logger
# Using npm
npm install @apexmcp/logger
# Using yarn
yarn add @apexmcp/logger
# Using pnpm
pnpm add @apexmcp/loggerQuick Start
import { logger } from '@apexmcp/logger';
// Basic logging
logger.info('Application started');
logger.warn('This is a warning');
logger.error('This is an error');
// With additional data
logger.debug('Processing user', { userId: 123, action: 'login' });API Reference
Logger Instance
The package exports a default logger instance that can be used immediately:
import { logger } from '@apexmcp/logger';
logger.info('Hello, world!');Creating Custom Loggers
import { Logger, LOG_LEVEL } from '@apexmcp/logger';
// Create a logger with specific level
const customLogger = new Logger(LOG_LEVEL.DEBUG);
// Create a logger with context
const contextualLogger = new Logger(LOG_LEVEL.INFO, { service: 'api' });Log Levels
Available log levels in order of verbosity:
LOG_LEVEL.DEBUG- Detailed debugging informationLOG_LEVEL.INFO- General information messagesLOG_LEVEL.LOG- Standard log messagesLOG_LEVEL.WARN- Warning messagesLOG_LEVEL.ERROR- Error messages (always logged)
Logging Methods
All logging methods accept a message string and optional additional arguments:
logger.debug(message: string, ...args: unknown[]): void
logger.info(message: string, ...args: unknown[]): void
logger.log(message: string, ...args: unknown[]): void
logger.warn(message: string, ...args: unknown[]): void
logger.error(message: string, ...args: unknown[]): voidArguments are automatically serialized to JSON:
logger.info('User logged in', { userId: 123, timestamp: new Date() });
// Output: [2023-01-01T12:00:00.000Z] INFO: User logged in {"userId":123,"timestamp":"2023-01-01T12:00:00.000Z"}Structured Logging with Context
Add persistent context to loggers:
const userLogger = logger.child({ userId: 123, sessionId: 'abc' });
userLogger.info('User action performed', { action: 'login' });
// Output: [2023-01-01T12:00:00.000Z] INFO: {"userId":123,"sessionId":"abc"} User action performed {"action":"login"}Context is merged when creating child loggers:
const baseLogger = new Logger(LOG_LEVEL.INFO, { service: 'api' });
const requestLogger = baseLogger.child({ requestId: 'req-123' });
requestLogger.info('Processing request');
// Output: [2023-01-01T12:00:00.000Z] INFO: {"service":"api","requestId":"req-123"} Processing requestChanging Log Levels
// Change level on existing logger instance
const newLogger = logger.setLevel(LOG_LEVEL.DEBUG);
// Create new logger with different level
const debugLogger = new Logger(LOG_LEVEL.DEBUG);Environment Variable Configuration
Set the LOG_LEVEL environment variable to control logging verbosity:
# Enable debug logging
LOG_LEVEL=DEBUG bun run app.ts
# Only show warnings and errors
LOG_LEVEL=WARN node app.jsSupported values: DEBUG, INFO, LOG, WARN, ERROR
Universal Environment Support
The logger automatically detects and works in different JavaScript environments:
- Bun: Uses
process.env.LOG_LEVEL - Deno: Uses
Deno.env.get('LOG_LEVEL') - Node.js: Uses
process.env.LOG_LEVEL
Advanced Usage
Request Logging Middleware
function createRequestLogger(requestId: string) {
return logger.child({ requestId });
}
// In your request handler
const requestLogger = createRequestLogger('req-123');
requestLogger.info('Request received', { method: 'GET', path: '/api/users' });
// Later in processing
requestLogger.debug('Validating user input', { input: userData });
requestLogger.warn('Invalid email format', { email: 'invalid-email' });Service-Specific Loggers
class UserService {
private logger = logger.child({ service: 'UserService' });
async createUser(userData: any) {
this.logger.info('Creating user', { email: userData.email });
try {
// ... user creation logic
this.logger.info('User created successfully', { userId: result.id });
return result;
} catch (error) {
this.logger.error('Failed to create user', { error: error.message });
throw error;
}
}
}TypeScript Support
Full TypeScript support with exported types:
import type { Logger, LogLevel, LogContext } from '@apexmcp/logger';
interface CustomContext extends LogContext {
userId: string;
sessionId: string;
}
const customLogger: Logger = new Logger(LOG_LEVEL.INFO);Output Format
Log messages follow this format:
[timestamp] LEVEL: [context] message [args]- timestamp: ISO 8601 formatted timestamp
- LEVEL: Log level (DEBUG, INFO, LOG, WARN, ERROR)
- context: Optional JSON context object (only shown if context exists)
- message: Log message
- args: Optional additional arguments as JSON (only shown if args exist)
Examples
Basic Application Logging
import { logger } from '@apexmcp/logger';
function startApp() {
logger.info('Application starting...');
// Simulate app startup
logger.debug('Loading configuration...');
logger.debug('Connecting to database...');
logger.info('Database connected successfully');
logger.info('Application started successfully');
}
startApp();Error Handling
import { logger } from '@apexmcp/logger';
async function processUser(userId: string) {
const userLogger = logger.child({ userId });
try {
userLogger.debug('Processing user data');
const user = await fetchUser(userId);
userLogger.info('User data retrieved', { userFound: !!user });
return user;
} catch (error) {
userLogger.error('Failed to process user', {
error: error.message,
stack: error.stack,
});
throw error;
}
}Contributing
Contributions are welcome! Please ensure all tests pass and add tests for new features.
# Install dependencies
bun install
# Run tests
bun test
# Run tests in watch mode
bun test --watch
# Build the package
bun run buildLicense
MIT
