Registry / observability / log4js

log4js

JSON →
library6.9.1jsnpmunverified

Log4js is a comprehensive and configurable logging framework for Node.js, currently stable at version 6.9.1. It provides various appenders for outputting logs to the console, files (with rolling), and network services, alongside flexible layout patterns and category-based logging. While sharing a name with Java's Log4j, it behaves distinctly, making direct assumptions about parity a source of confusion. The project is actively maintained, with regular updates and a dedicated community. Key differentiators include its extensive appender support (many as optional, separate packages), highly customizable log levels (TRACE, DEBUG, INFO, WARN, ERROR, FATAL), and built-in TypeScript definitions, offering a robust solution for managing application logs in various environments.

npm install log4js
INSTALL
IMPORT
SIG · LOG4JS
L
log4js
observabilityjavascriptv6.9.1
Install
Import
Disk
Pass rate
0/ 6
Env Coverage0 / 6
glibc
1822
musl
1822
Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
node 18226 runs
build_error
glibc
node 18226 runs
build_error
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

log4js
import pkg from 'log4js'; const log4js = pkg;
import * as log4js from 'log4js'; // 'log4js' is a CommonJS module import log4js from 'log4js'; // Not a default export
Log4js is primarily a CommonJS module. For ESM environments (`'type': 'module'` in package.json), you must import the entire module as a default export, then destructure if needed. Direct named imports like `{ configure }` will fail.
getLogger
import pkg from 'log4js'; const { getLogger } = pkg; const logger = getLogger();
import { getLogger } from 'log4js'; // This will not work in ESM environments.
When using TypeScript or modern ESM, destructure `getLogger` and `configure` from the imported package object. The `require` syntax allows direct access to `log4js.getLogger`.
Configuration
import type { Configuration, Logger } from 'log4js';
TypeScript types are included, allowing for type-safe configuration objects and logger instances.
CommonJS require
const log4js = require('log4js');
This is the most common and robust way to import log4js in Node.js, especially in CommonJS environments or when `type: module` is not explicitly set. The official documentation and examples primarily use `require`.

This quickstart demonstrates configuring Log4js with both console and file appenders, setting different log levels for categories, and performing various log outputs. It also includes crucial `shutdown` handling for graceful application termination.

import pkg from 'log4js'; const { configure, getLogger, shutdown } = pkg; // Configure log4js with a console and a file appender configure({ appenders: { console: { type: 'console' }, fileAppender: { type: 'file', filename: 'application.log', maxLogSize: 10485760, // 10MB backups: 3, compress: true } }, categories: { default: { appenders: ['console'], level: 'info' }, app: { appenders: ['console', 'fileAppender'], level: 'debug' } } }); const logger = getLogger('app'); logger.trace('Entering application module.'); logger.debug('This is a debug message for the app category.'); logger.info('Application started successfully.'); logger.warn('A non-critical warning occurred.'); logger.error('An error happened: Something went wrong!'); logger.fatal('Fatal error: Application is shutting down.'); // Important: Call shutdown on application exit to ensure all logs are written. process.on('SIGINT', () => { console.log('Caught interrupt signal, shutting down log4js...'); shutdown(() => { console.log('Log4js shutdown complete. Exiting.'); process.exit(0); }); }); // Simulate some async operation for logs to process setTimeout(() => { logger.info('Simulated operation finished.'); }, 500);
Debug
Known issues
breakingThe configuration format changed significantly in version 2.x. Older configurations (e.g., from v1.x) will likely result in errors like 'must have property 'appenders' of type object'. Programmatic configuration functions like `addAppender` were removed in favor of a single `configure` function.
fix
Review the migration guide and update your configuration object to include named appenders and define categories explicitly, especially the `default` category. All configuration must now pass through the `configure` function.
affects: >=2.0.0
breakingMany optional appenders (e.g., GELF, Hipchat, Loggly, SMTP, Logstash, Redis, RabbitMQ) were removed from the core package in version 3.x and moved to their own dedicated `@log4js-node/<appender>` npm packages. Node.js versions less than 6 are also no longer supported.
fix
If you used any of these appenders, you must explicitly install their corresponding package (e.g., `npm i @log4js-node/smtp`) and update your configuration. Ensure your Node.js environment is at least version 6.
affects: >=3.0.0
breakingVersion 6.4.0 introduced a breaking change regarding default file permissions, which may cause external applications or users to be unable to read log files created by Log4js.
fix
Manually adjust file permissions in your code or configuration if external access to log files is required. Refer to the `streamroller` documentation or `log4js` changelog for specifics.
affects: >=6.4.0
gotchaBy default, Log4js sets the log level for the `default` category to `OFF`, meaning no logs will be output unless you explicitly set a level (e.g., `logger.level = 'debug'` or in `configure`). This is often a source of confusion when logs are not appearing.
fix
Always set the desired log level either programmatically on the logger instance or declaratively within your `log4js.configure` object, especially for the `default` category.
affects: >=2.0.0
gotchaLog4js for Node.js is inspired by, but not a direct port of, Apache Log4j for Java. It does not behave identically to the Java library, and assuming similar functionality or configuration will lead to issues and incorrect expectations.
fix
Refer exclusively to the `log4js-node` documentation for usage and configuration. Do not apply concepts or configurations directly from Log4j (Java).
affects: *
gotchaThe `replaceConsole` feature, which replaced Node.js's native `console` functions with Log4js, was removed in version 2.x due to causing unexpected errors. Configuration hot-reloading (watching config files for changes) was also removed.
fix
To replace `console` functions, you must now bind logger methods manually (e.g., `console.log = logger.info.bind(logger)`). For config reloading, integrate with an external file watcher library (like `watchr`) and manually call `log4js.shutdown()` followed by `log4js.configure()` again.
affects: >=2.0.0
gotchaFor applications with long-running processes or using file appenders, it is critical to call `log4js.shutdown()` before your application terminates. This ensures that all buffered log messages are flushed to their destinations and resources (like file handles) are properly released, preventing data loss.
fix
Add a `process.on('SIGINT', log4js.shutdown)` or similar handler to explicitly call `shutdown()` on application exit, especially for production environments.
affects: >=2.0.0
Errors
Common errors & fixes
SyntaxError: Named export 'configure' not found. The requested module 'log4js' is a CommonJS module, which may not support all module.exports as named exports.
Attempting to use named ES Module imports (`import { configure } from 'log4js';`) in a Node.js project configured for ES Modules (`'type': 'module'`) when `log4js` is a CommonJS module.
fix
Use the CommonJS `require` syntax (`const log4js = require('log4js');`) or, if strictly in an ESM context, import the entire module as a default export and destructure (`import pkg from 'log4js'; const { configure, getLogger } = pkg;`).
Error: log4js configuration must have property "appenders" of type object
Using an outdated configuration format (from v1.x) with Log4js v2.x or later. The new format requires an `appenders` object and a `categories` object, with the `default` category also explicitly defined.
fix
Update your `log4js.configure` object to match the v2.x schema, ensuring it defines named appenders within an `appenders` object and categories (including a `default` category) within a `categories` object.
Logger does not output anything to console/file.
The default log level for the `default` category in Log4js (since v2.x) is `OFF`, meaning no logs are processed unless a level is explicitly set.
fix
Set the log level for your logger or a category to `debug`, `info`, `warn`, `error`, etc., either in your `log4js.configure` object (e.g., `categories: { default: { appenders: ['console'], level: 'info' } }`) or programmatically (`logger.level = 'debug';`).
type "multiFile" could not be found - TypeError: appenderModule.configure is not a function
Attempting to use an optional appender (like `multiFile`, `gelf`, `smtp`, etc.) without installing its dedicated `@log4js-node/<appender>` package (since v3.x) or using an incorrect `type` name.
fix
Install the correct npm package for the desired optional appender (e.g., `npm install @log4js-node/multi-file`) and ensure the `type` property in your configuration matches the appender's registered name.
Upgrade
Version history
6.9.1latest on npm
Audit
Dependencies
date-formatrequiredInternal dependency for date formatting in log layouts.
streamrollerrequiredUsed for file appenders, particularly for log rolling and file management.
@log4js-node/smtpoptionalOptional appender for sending logs via SMTP. Must be installed separately since v3.
@log4js-node/gelfoptionalOptional appender for sending logs to GELF-compatible servers. Must be installed separately since v3.
Agent activity
10 hits · last 30 days
node
8
OpenAI (training)
2
Resources
log4js — npm install log4js · libregistry