
Security News
Attackers Are Hunting High-Impact Node.js Maintainers in a Coordinated Social Engineering Campaign
Multiple high-impact npm maintainers confirm they have been targeted in the same social engineering campaign that compromised Axios.
@jshow/logger
Advanced tools
@jshow/logger is a powerful, flexible, and feature-rich logging library for TypeScript/JavaScript applications. It provides a clean API for structured logging with support for namespaces, tags, extra information, and customizable output formats.
error, warn, info, and debug levelsDEBUG_IGNORE environment variablejShow is an MIT-Licensed open source project with its ongoing development made possible entirely by the support of these awesome backers. If you'd like to join them, please consider:
Funds donated via Patreon go directly to support @jshow/logger You's full-time work on jShow. Funds donated via OpenCollective are managed with transparent expenses and will be used for compensating work and expenses for core team members or sponsoring community events. Your name/logo will receive proper recognition and exposure by donating on either platform.
npm install @jshow/logger
# or
pnpm add @jshow/logger
# or
yarn add @jshow/logger
import { configure, logger } from '@jshow/logger';
// Configure the logger (only need to call once at application startup)
configure();
// Use different log levels
logger.error('This is an error message');
logger.warn('This is a warning message');
logger.info('This is an info message');
logger.debug('This is a debug message');
@jshow/logger supports four log levels, ordered by severity from high to low:
error - Error levelwarn - Warning levelinfo - Info level (default)debug - Debug levellogger.error('Error message');
logger.warn('Warning message');
logger.info('Info message');
logger.debug('Debug message');
Use namespaces to organize and categorize logs:
// Create a logger with namespace
const appLogger = logger.fork({ namespace: 'app' });
appLogger.info('Application started');
const dbLogger = logger.fork({ namespace: 'database' });
dbLogger.info('Database connected');
// Nested namespaces
const apiLogger = logger.fork({ namespace: 'api' });
const userApiLogger = apiLogger.fork({ namespace: 'user' });
userApiLogger.info('Get user information');
Use the scope method to execute code in a specific context:
logger.scope({ namespace: 'request' }, log => {
log.info('Request processing started');
log.info('Processing request...');
log.info('Request processing completed');
});
Use tags to categorize and filter logs:
const taggedLogger = logger.fork({
namespace: 'payment',
tags: { module: 'payment', version: '1.0.0' }
});
taggedLogger.info('Processing payment request', { amount: 100, currency: 'USD' });
Use extra information to add structured data:
const loggerWithExtra = logger.fork({
namespace: 'api',
extra: { requestId: 'req-123', userId: 'user-456' }
});
loggerWithExtra.info('API request processing');
Dynamically set log level:
const debugLogger = logger.fork({ namespace: 'debug' });
debugLogger.setLevel('debug');
debugLogger.debug('This debug message will be shown');
debugLogger.setLevel('info');
debugLogger.debug('This debug message will not be shown');
import { configure, LoggerFactoryOfConsole } from '@jshow/logger';
configure(LoggerFactoryOfConsole, {
format: 'text', // 'text' or 'json'
enableNamespacePrefix: true,
enableNamespacePrefixColors: true,
appendTagsForTextPrint: true,
appendExtraForTextPrint: true
});
configure(LoggerFactoryOfConsole, {
format: 'json'
});
configure(LoggerFactoryOfConsole, {
format: 'text',
transformTagsForTextPrint: (tags, context) => {
return `[Tags: ${Object.keys(tags).join(', ')}]`;
},
transformExtraForTextPrint: (extra, context) => {
return `[Extra: ${JSON.stringify(extra)}]`;
}
});
Use filters to control which logs are output:
configure(LoggerFactoryOfConsole, {
filter: (namespace, tags) => {
// Only show logs from production environment
return tags.env === 'production';
}
});
Use hook functions to execute custom logic after log output:
configure(LoggerFactoryOfConsole, {
hook: (level, context, ...messages) => {
if (level === 'error') {
// Send errors to monitoring system
sendToMonitoring(level, context, messages);
}
}
});
Set global log level:
import { setLogLevel, setLogLevels } from '@jshow/logger';
// Set a single log level threshold
setLogLevel('debug'); // Show all log levels
setLogLevel('info'); // Show only info, warn, error
setLogLevel('warn'); // Show only warn, error
setLogLevel('error'); // Show only error
// Set multiple allowed log levels
setLogLevels('debug', 'info', 'warn', 'error'); // Show all log levels
setLogLevels('info', 'warn', 'error'); // Show only info, warn, error
setLogLevels('warn', 'error'); // Show only warn, error
setLogLevels('error'); // Show only error
Use the useLogger hook to automatically create loggers with namespaces extracted from context:
import { useLogger } from '@jshow/logger';
// Use string as namespace
const logger = useLogger('UserService');
logger.info('User created'); // Output: [UserService] User created
// Use class as context
class UserService {
constructor() {
this.logger = useLogger(this);
}
}
// logger namespace will be 'UserService'
// Use function as context
function handleRequest() {
const logger = useLogger(handleRequest);
logger.debug('Processing request');
}
// logger namespace will be 'handleRequest'
You can filter out specific namespaces using the DEBUG_IGNORE environment variable:
# Ignore logs from UserService and ApiClient namespaces
DEBUG_IGNORE=UserService,ApiClient node app.js
When a namespace is in the ignore list, useLogger returns a no-op logger that won't output anything.
The Color module provides utilities for color manipulation and display:
import { Color } from '@jshow/logger';
// Generate color from text
const color = Color.makeColorHexFromText('error'); // Returns [r, g, b]
// Invert color
const inverted = Color.invertHex([255, 128, 64]);
// Check if color is dark
const isDark = Color.isDarkColor([50, 50, 50]);
// Optimize color for better log display
const optimized = Color.betterLogColor([255, 0, 0]);
// Wrap text with ANSI colors (Node.js)
const ansiText = Color.wrapColorANSI('Hello', {
contentColor: [255, 0, 0],
backgroundColor: [0, 0, 0]
});
// Wrap text with CSS colors (Browser)
const [cssContent, cssStyle] = Color.wrapColorCSS('Hello', {
contentColor: [255, 0, 0],
backgroundColor: [0, 0, 0]
});
logger.error(...msg: unknown[])Log error level messages
logger.warn(...msg: unknown[])Log warning level messages
logger.info(...msg: unknown[])Log info level messages
logger.debug(...msg: unknown[])Log debug level messages
logger.fork(context: LoggerSubContext)Create a new child logger instance
logger.scope(context: LoggerSubContext, fn: (logger: Logger) => void)Execute callback function in specified context
logger.setLevel(level: LogLevel)Set the output level for current logger
logger.setLevels(...levels: LogLevel[])Set multiple allowed log levels for current logger
useLogger(ctx: string | Function | object)Create a logger instance with namespace extracted from context. Returns a no-op logger if namespace is in DEBUG_IGNORE environment variable.
setLoggerIgnore(ignore: string)Programmatically set the list of namespaces to ignore. Takes a comma-separated string of namespace names (case-insensitive).
import { setLoggerIgnore } from '@jshow/logger';
// Ignore logs from UserService and ApiClient namespaces
setLoggerIgnore('UserService,ApiClient');
setLogLevel(level: LogLevel)Set global log level threshold
setLogLevels(...levels: LogLevel[])Set global allowed log levels
useLogger(ctx: string | Function | object)Create a logger with namespace extracted from context
setLoggerIgnore(ignore: string)Programmatically set the list of namespaces to ignore
LogLeveltype LogLevel = 'error' | 'warn' | 'info' | 'debug';
LoggerContextinterface LoggerContext {
tags?: { [x: string]: unknown };
extra?: { [x: string]: string | number | boolean | undefined | null };
namespace?: string[];
readonly config: LoggerConfig;
}
LoggerConfiginterface LoggerConfig {
readonly format: 'text' | 'json';
readonly enableNamespacePrefix: boolean;
readonly enableNamespacePrefixColors: boolean;
readonly appendTagsForTextPrint: boolean;
readonly appendExtraForTextPrint: boolean;
readonly transformTagsForTextPrint?: (tags, context) => unknown;
readonly transformExtraForTextPrint?: (extra, context) => unknown;
readonly filter?: (namespace, tags) => boolean;
readonly hook?: (level, context, ...messages) => void;
}
configure() only once when your application startssetLogLevel() or setLogLevels() to control verbosity in different environmentsuseLogger hook for automatic namespace extraction from classes and functionsFor more usage examples, see the examples directory:
Comma-separated list of namespace names (case-insensitive) to ignore. When using useLogger, loggers with namespaces in this list will return no-op loggers.
DEBUG_IGNORE=UserService,ApiClient,Database
You can also set this programmatically:
import { setLoggerIgnore } from '@jshow/logger';
setLoggerIgnore('UserService,ApiClient,Database');
@jshow/logger is written in TypeScript and provides full type definitions out of the box. All APIs are fully typed, providing excellent IDE autocomplete and type safety.
import { logger, type Logger, type LogLevel } from '@jshow/logger';
// All methods are fully typed
const appLogger: Logger = logger.fork({ namespace: 'app' });
const level: LogLevel = 'info';
The library works in both Node.js and browser environments:
The same API works in both environments without any code changes.
@jshow/logger is designed with performance in mind:
Contributions are welcome! Please feel free to submit a Pull Request. For major changes, please open an issue first to discuss what you would like to change.
The issue list of this repo is exclusively for bug reports and feature requests.
Copyright (c) 2022 jShow.org
FAQs
@jshow/logger
We found that @jshow/logger demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 2 open source maintainers collaborating on the project.
Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Security News
Multiple high-impact npm maintainers confirm they have been targeted in the same social engineering campaign that compromised Axios.

Security News
Axios compromise traced to social engineering, showing how attacks on maintainers can bypass controls and expose the broader software supply chain.

Security News
Node.js has paused its bug bounty program after funding ended, removing payouts for vulnerability reports but keeping its security process unchanged.