### Install log4js-node Source: https://log4js-node.github.io/log4js-node/index.html Install the log4js-node package using npm. ```bash npm install log4js ``` -------------------------------- ### v1 Configuration Example Source: https://log4js-node.github.io/log4js-node/migration-guide.html This is an example of a v1 configuration object for log4js. Note the array format for appenders. ```javascript { appenders: [ { type: "console" }, { type: "dateFile", filename: "logs/task", pattern: "-dd.log", alwaysIncludePattern: true, category: "task", }, ] } ``` -------------------------------- ### v2 Configuration Example Source: https://log4js-node.github.io/log4js-node/migration-guide.html This is an example of a v2 configuration object for log4js. Appenders are now named objects, and categories must be explicitly defined. ```javascript { appenders: { out: { type: 'console' }, task: { type: 'dateFile', filename: 'logs/task', pattern: '-dd.log', alwaysIncludePattern: true } }, categories: { default: { appenders: [ 'out' ], level: 'info' }, task: { appenders: [ 'task' ], level: 'info' } } } ``` -------------------------------- ### Configure MultiFile Appender with Log Rolling Source: https://log4js-node.github.io/log4js-node/multiFile.html This example demonstrates configuring the multiFile appender with log rolling and compressed backups. Logs are split by 'userID', capped at 10MB, and up to 3 compressed backups are kept. ```javascript log4js.configure({ appenders: { everything: { type: "multiFile", base: "logs/", property: "userID", extension: ".log", maxLogSize: 10485760, backups: 3, compress: true, }, }, categories: { default: { appenders: ["everything"], level: "debug" }, }, }); const userLogger = log4js.getLogger("user"); userLogger.addContext("userID", user.getID()); userLogger.info("this user just logged in"); ``` -------------------------------- ### Configure basic stdout appender with basic layout Source: https://log4js-node.github.io/log4js-node/layouts.html Configures the stdout appender to use the basic layout. This is a common setup for general logging. ```javascript log4js.configure({ appenders: { out: { type: "stdout", layout: { type: "basic" } } }, categories: { default: { appenders: ["out"], level: "info" } }, }); ``` -------------------------------- ### Log an error message with basic layout Source: https://log4js-node.github.io/log4js-node/layouts.html Demonstrates logging an error message using the basic layout. This example shows the typical output format including timestamp, level, category, and the message. ```javascript log4js.configure({ appenders: { out: { type: "stdout", layout: { type: "basic" } } }, categories: { default: { appenders: ["out"], level: "info" } }, }); const logger = log4js.getLogger("cheese"); logger.error("Cheese is too ripe!"); ``` -------------------------------- ### Install pm2-intercom for PM2 Integration Source: https://log4js-node.github.io/log4js-node/clustering.html Install the pm2-intercom module to enable log4js to work correctly with PM2. This is a prerequisite for configuring log4js for PM2. ```bash pm2 install pm2-intercom ``` -------------------------------- ### Configure Synchronous File Appender Source: https://log4js-node.github.io/log4js-node/fileSync.html Configure the 'fileSync' appender to write all logs to a single file. This setup is suitable for basic logging needs where immediate persistence is required. ```javascript log4js.configure({ appenders: { everything: { type: "fileSync", filename: "all-the-logs.log" }, }, categories: { default: { appenders: ["everything"], level: "debug" }, }, }); const logger = log4js.getLogger(); logger.debug("I will be logged in all-the-logs.log"); ``` -------------------------------- ### Configure File Appender with Log Rolling and Compression Source: https://log4js-node.github.io/log4js-node/file.html Configure the file appender with log rolling based on size and compressed backups. This setup ensures that log files do not grow indefinitely and are stored efficiently. ```javascript log4js.configure({ appenders: { everything: { type: "file", filename: "all-the-logs.log", maxLogSize: 10485760, backups: 3, compress: true, }, }, categories: { default: { appenders: ["everything"], level: "debug" }, }, }); ``` -------------------------------- ### Log a message with messagePassThrough layout Source: https://log4js-node.github.io/log4js-node/layouts.html Logs a message using the messagePassThrough layout. This example shows how only the message data is outputted, without timestamp, level, or category. ```javascript const logger = log4js.getLogger("cheese"); const cheeseName = "gouda"; logger.error("Cheese is too ripe! Cheese was: ", cheeseName); ``` -------------------------------- ### Output of Custom JSON Layout Source: https://log4js-node.github.io/log4js-node/layouts.html This is the expected output when using the custom JSON layout defined in the previous example. Note that the exact timestamp will vary. ```json {"startTime":"2017-06-05T22:23:08.479Z","categoryName":"json-test","data":["this is just a test"],"level":{"level":20000,"levelStr":"INFO"},"context":{}}, {"startTime":"2017-06-05T22:23:08.483Z","categoryName":"json-test","data":["of a custom appender"],"level":{"level":40000,"levelStr":"ERROR"},"context":{}}, {"startTime":"2017-06-05T22:23:08.483Z","categoryName":"json-test","data":["that outputs json"],"level":{"level":30000,"levelStr":"WARN"},"context":{}}, ``` -------------------------------- ### Get Logger Instance Source: https://log4js-node.github.io/log4js-node/api.html Retrieves a logger instance for a specified category. If the logger is not configured, it defaults to 'default' category. ```javascript const logger = log4js.getLogger('myCategory'); ``` ```javascript const logger = log4js.getLogger(); ``` -------------------------------- ### Configure File Appender with Log Rolling Source: https://log4js-node.github.io/log4js-node/fileSync.html Configure the 'file' appender with 'maxLogSize' and 'backups' for log rolling. This example demonstrates how to set up automatic log file rotation when a specified size is reached, preserving a history of log files. ```javascript log4js.configure({ appenders: { everything: { type: "file", filename: "all-the-logs.log", maxLogSize: 10458760, backups: 3, }, }, categories: { default: { appenders: ["everything"], level: "debug" }, }, }); ``` -------------------------------- ### Configure No-Log Filter with Multiple Exclusions Source: https://log4js-node.github.io/log4js-node/noLogFilter.html This example shows how to configure the no-log filter using an array of regular expressions to exclude messages. It demonstrates excluding messages containing 'NOT', digits (\d), or empty strings. Note that empty strings are ignored, and the matching is case-insensitive. ```javascript log4js.configure({ appenders: { everything: { type: "file", filename: "all-the-logs.log" }, filtered: { type: "noLogFilter", exclude: ["NOT", "\\d", ""], appender: "everything", }, }, categories: { default: { appenders: ["filtered"], level: "debug" }, }, }); const logger = log4js.getLogger(); logger.debug("I will be logged in all-the-logs.log"); logger.debug("I will be not logged in all-the-logs.log"); logger.debug("A 2nd message that will be excluded in all-the-logs.log"); ``` -------------------------------- ### Add Custom JSON Layout to Log4js Source: https://log4js-node.github.io/log4js-node/layouts.html Define and configure a custom JSON layout for log4js. This example shows how to register a new layout type and use it with a stdout appender. Ensure `log4js.addLayout` is called before `log4js.configure`. ```javascript const log4js = require("log4js"); log4js.addLayout("json", function (config) { return function (logEvent) { return JSON.stringify(logEvent) + config.separator; }; }); log4js.configure({ appenders: { out: { type: "stdout", layout: { type: "json", separator: "," } } }, categories: { default: { appenders: ["out"], level: "info" } }, }); const logger = log4js.getLogger("json-test"); logger.info("this is just a test"); logger.error("of a custom appender"); logger.warn("that outputs json"); log4js.shutdown(() => {}); ``` -------------------------------- ### Stdout Appender with Shutdown Function Source: https://log4js-node.github.io/log4js-node/writing-appenders.html This example extends the basic stdout appender by adding a `shutdown` function. The `shutdown` function is called when log4js is stopping and should be used for resource cleanup. Ensure your shutdown function accepts a callback. ```javascript // This is the function that generates an appender function function stdoutAppender(layout, timezoneOffset) { // This is the appender function itself const appender = (loggingEvent) => { process.stdout.write(`${layout(loggingEvent, timezoneOffset)}\n`); }; // add a shutdown function. appender.shutdown = (done) => { process.stdout.write("", done); }; return appender; } // ... rest of the code as above ``` -------------------------------- ### Configure Category Filter Appender Source: https://log4js-node.github.io/log4js-node/categoryFilter.html Use this configuration to set up a categoryFilter appender that excludes logs from 'noisy.component' and directs all other logs to 'all-the-logs.log'. This setup is beneficial when you need to isolate logs from specific noisy parts of your application. ```javascript log4js.configure({ appenders: { everything: { type: "file", filename: "all-the-logs.log" }, "no-noise": { type: "categoryFilter", exclude: "noisy.component", appender: "everything", }, }, categories: { default: { appenders: ["no-noise"], level: "debug" }, }, }); const logger = log4js.getLogger(); const noisyLogger = log4js.getLogger("noisy.component"); logger.debug("I will be logged in all-the-logs.log"); noisyLogger.debug("I will not be logged."); ``` -------------------------------- ### Configure Log Level Filter Appender Source: https://log4js-node.github.io/log4js-node/logLevelFilter.html Use this configuration to filter log events based on their level. Events within the specified 'level' and 'maxLevel' range are sent to the wrapped appender. This example sends 'error' and 'fatal' events to 'panic-now.log' while all events go to 'all-the-logs.log'. ```javascript log4js.configure({ appenders: { everything: { type: "file", filename: "all-the-logs.log" }, emergencies: { type: "file", filename: "panic-now.log" }, "just-errors": { type: "logLevelFilter", appender: "emergencies", level: "error", }, }, categories: { default: { appenders: ["just-errors", "everything"], level: "debug" }, }, }); ``` -------------------------------- ### Configure No-Log Filter with Single Exclusion Source: https://log4js-node.github.io/log4js-node/noLogFilter.html This example demonstrates how to configure the no-log filter to exclude messages containing the string 'not'. Ensure the 'noLogFilter' type is specified, along with the 'exclude' pattern and the target 'appender'. ```javascript log4js.configure({ appenders: { everything: { type: "file", filename: "all-the-logs.log" }, filtered: { type: "noLogFilter", exclude: "not", appender: "everything", }, }, categories: { default: { appenders: ["filtered"], level: "debug" }, }, }); const logger = log4js.getLogger(); logger.debug("I will be logged in all-the-logs.log"); logger.debug("I will be not logged in all-the-logs.log"); ``` -------------------------------- ### Handle File Appender Memory Usage Source: https://log4js-node.github.io/log4js-node/file.html Listen for 'log4js:pause' events to manage memory usage when the file appender starts buffering logs. Stop logging when 'true' is received and resume when 'false' is received. ```javascript log4js.configure({ appenders: { output: { type: "file", filename: "out.log" }, }, categories: { default: { appenders: ["output"], level: "debug" } }, }); let paused = false; process.on("log4js:pause", (value) => (paused = value)); const logger = log4js.getLogger(); while (!paused) { logger.info("I'm logging, but I will stop once we start buffering"); } ``` -------------------------------- ### Configure Default and Appenders with Categories Source: https://log4js-node.github.io/log4js-node/categories.html Sets up stdout and file appenders, defining default and 'app' categories with trace level. Use this to establish basic logging configurations. ```javascript const log4js = require("log4js"); log4js.configure({ appenders: { out: { type: "stdout" }, app: { type: "file", filename: "application.log" }, }, categories: { default: { appenders: ["out"], level: "trace" }, app: { appenders: ["app"], level: "trace" }, }, }); const logger = log4js.getLogger(); logger.trace("This will use the default category and go to stdout"); const logToFile = log4js.getLogger("app"); logToFile.trace("This will go to a file"); ``` -------------------------------- ### Configure and Use Connect Logger Source: https://log4js-node.github.io/log4js-node/connect-logger.html Set up log4js with console and file appenders, then use connectLogger to log requests to a specific logger. Requires express and log4js. ```javascript var log4js = require("log4js"); var express = require("express"); log4js.configure({ appenders: { console: { type: "console" }, file: { type: "file", filename: "cheese.log" }, }, categories: { cheese: { appenders: ["file"], level: "info" }, default: { appenders: ["console"], level: "info" }, }, }); var logger = log4js.getLogger("cheese"); var app = express(); app.use(log4js.connectLogger(logger, { level: "info" })); app.get("/", function (req, res) { res.send("hello world"); }); app.listen(5000); ``` -------------------------------- ### Basic stdout Appender Configuration Source: https://log4js-node.github.io/log4js-node/writing-appenders.html This code defines the `configure` function for a simple stdout appender. It demonstrates how to load a layout and return the appender function. Use this as a template for creating custom appenders. ```javascript // This is the function that generates an appender function function stdoutAppender(layout, timezoneOffset) { // This is the appender function itself return (loggingEvent) => { process.stdout.write(`${layout(loggingEvent, timezoneOffset)}\n`); }; } // stdout configure doesn't need to use findAppender, or levels function configure(config, layouts) { // the default layout for the appender let layout = layouts.colouredLayout; // check if there is another layout specified if (config.layout) { // load the layout layout = layouts.layout(config.layout.type, config.layout); } //create a new appender instance return stdoutAppender(layout, config.timezoneOffset); } //export the only function needed exports.configure = configure; ``` -------------------------------- ### Configure stdout and file appenders Source: https://log4js-node.github.io/log4js-node/appenders.html Define 'out' for standard output and 'app' for file logging. Set the default category to use both with debug level. ```javascript const log4js = require("log4js"); log4js.configure({ appenders: { out: { type: "stdout" }, app: { type: "file", filename: "application.log" }, }, categories: { default: { appenders: ["out", "app"], level: "debug" }, }, }); ``` -------------------------------- ### Configure Hourly Log Rolling with Compressed Backups Source: https://log4js-node.github.io/log4js-node/dateFile.html Configure hourly log rolling with compressed backups. Log files are renamed and compressed with a `.gz` extension each hour. ```javascript log4js.configure({ appenders: { everything: { type: "dateFile", filename: "all-the-logs.log", pattern: "yyyy-MM-dd-hh", compress: true, }, }, categories: { default: { appenders: ["everything"], level: "debug" }, }, }); ``` -------------------------------- ### log4js.configure(object || string) Source: https://log4js-node.github.io/log4js-node/api.html Configures the log4js library. Accepts a configuration object directly or a string path to a JSON configuration file. Configuration should be done early in the application lifecycle. If using `cluster`, configure in worker processes as well. ```APIDOC ## POST /log4js.configure ### Description Configures the log4js library with a given configuration object or a file path. ### Method POST ### Endpoint /log4js.configure ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **config** (object | string) - Required - The configuration object or a string path to a JSON configuration file. ### Request Example ```json { "config": { "levels": { "custom": {"value": 1337, "colour": "blue"} }, "appenders": { "out": {"type": "stdout", "layout": {"type": "pattern", "pattern": "%[[%date] %-5level%] %-10category : %m%n%s"}}, "app": {"type": "file", "filename": "all-the-logs.log"} }, "categories": { "default": {"appenders": ["out"], "level": "INFO"}, "http": {"appenders": ["out", "app"], "level": "DEBUG"} } } } ``` ### Response #### Success Response (200) - **log4js_object** (object) - The configured log4js object. #### Response Example ```json { "message": "Configuration successful" } ``` ``` -------------------------------- ### Configure Categories with Inheritance Source: https://log4js-node.github.io/log4js-node/categories.html Demonstrates category inheritance using dots (e.g., 'catA.catB'). Events in 'catA.catB' will use appenders and levels from 'catA' if not specified, and also log to 'app' appender. This is useful for hierarchical logging structures. ```javascript const log4js = require("log4js"); log4js.configure({ appenders: { console: { type: "console" }, app: { type: "file", filename: "application.log" }, }, categories: { default: { appenders: ["console"], level: "trace" }, catA: { appenders: ["console"], level: "error" }, "catA.catB": { appenders: ["app"], level: "trace" }, }, }); const loggerA = log4js.getLogger("catA"); loggerA.error("This will be written to console with log level ERROR"); loggerA.trace("This will not be written"); const loggerAB = log4js.getLogger("catA.catB"); loggerAB.error( "This will be written with log level ERROR to console and to a file" ); loggerAB.trace( "This will be written with log level TRACE to console and to a file" ); ``` -------------------------------- ### Configure Pattern Layout with Logger Context Source: https://log4js-node.github.io/log4js-node/layouts.html Shows how to use values from the logger's context within a pattern layout. The '%X{user}' specifier retrieves the 'user' value previously set using logger.addContext(). ```javascript log4js.configure({ appenders: { out: { type: "stdout", layout: { type: "pattern", pattern: "%d %p %c %X{user} %m%n", }, }, }, categories: { default: { appenders: ["out"], level: "info" } }, }); const logger = log4js.getLogger(); logger.addContext("user", "charlie"); logger.info("doing something."); ``` -------------------------------- ### Configure MultiFile Appender by Category Source: https://log4js-node.github.io/log4js-node/multiFile.html Use this configuration to split logs into separate files based on the category name. Ensure the 'multi' appender is configured with 'property: "categoryName"'. ```javascript log4js.configure({ appenders: { multi: { type: "multiFile", base: "logs/", property: "categoryName", extension: ".log", }, }, categories: { default: { appenders: ["multi"], level: "debug" }, }, }); const logger = log4js.getLogger(); logger.debug("I will be logged in logs/default.log"); const otherLogger = log4js.getLogger("cheese"); otherLogger.info("Cheese is cheddar - this will be logged in logs/cheese.log"); ``` -------------------------------- ### Basic Usage of log4js-node Source: https://log4js-node.github.io/log4js-node/index.html Initialize a logger and set its level for basic logging. The default log level is OFF. ```javascript var log4js = require("log4js"); var logger = log4js.getLogger(); logger.level = "debug"; // default level is OFF - which means no logs at all. logger.debug("Some debug messages"); ``` -------------------------------- ### Configure and Use Recording Appender Source: https://log4js-node.github.io/log4js-node/recording.html Configure log4js to use the 'recording' appender for in-memory log storage, useful for testing. This snippet demonstrates basic logging and retrieving/clearing recorded events. ```javascript const recording = require("log4js/lib/appenders/recording"); const log4js = require("log4js"); log4js.configure({ appenders: { vcr: { type: "recording" } }, categories: { default: { appenders: ["vcr"], level: "info" } }, }); const logger = log4js.getLogger(); logger.info("some log event"); const events = recording.replay(); // events is an array of LogEvent objects. recording.erase(); // clear the appender's array. ``` -------------------------------- ### Configure Pattern Layout with Custom Token Source: https://log4js-node.github.io/log4js-node/layouts.html Demonstrates how to define and use a custom token within a pattern layout. The custom token 'user' is defined as a function that retrieves the current user, and it's included in the log pattern. ```javascript log4js.configure({ appenders: { out: { type: "stdout", layout: { type: "pattern", pattern: "%d %p %c %x{user} %m%n", tokens: { user: function (logEvent) { return AuthLibrary.currentUser(); }, }, }, }, }, categories: { default: { appenders: ["out"], level: "info" } }, }); const logger = log4js.getLogger(); logger.info("doing something."); ``` -------------------------------- ### Configure Basic File Appender Source: https://log4js-node.github.io/log4js-node/file.html Configure the file appender to write all logs to a single file. Ensure to call log4js.shutdown on application termination. ```javascript log4js.configure({ appenders: { everything: { type: "file", filename: "all-the-logs.log" }, }, categories: { default: { appenders: ["everything"], level: "debug" }, }, }); const logger = log4js.getLogger(); logger.debug("I will be logged in all-the-logs.log"); ``` -------------------------------- ### Configure TCP Server Appender Source: https://log4js-node.github.io/log4js-node/tcp-server.html Configure the TCP server appender to listen on a specific host and forward logs to a file appender. Ensure the server appender is not listed in categories to avoid self-logging. ```javascript log4js.configure({ appenders: { file: { type: "file", filename: "all-the-logs.log" }, server: { type: "tcp-server", host: "0.0.0.0" }, }, categories: { default: { appenders: ["file"], level: "info" }, }, }); ``` -------------------------------- ### Configure stdout appender with messagePassThrough layout Source: https://log4js-node.github.io/log4js-node/layouts.html Sets up the stdout appender to use the messagePassThrough layout. This layout is useful for appenders that serialize events in a specific format, as it only outputs the log event data. ```javascript log4js.configure({ appenders: { out: { type: "stdout", layout: { type: "messagePassThrough" } }, }, categories: { default: { appenders: ["out"], level: "info" } }, }); ``` -------------------------------- ### Logger Management - log4js.getLogger([category]) Source: https://log4js-node.github.io/log4js-node/api.html Retrieves a logger instance. If log4js is not configured, it will be configured with default settings. You can specify a category for the logger or use the default category. ```APIDOC ## Logger Management - `log4js.getLogger([category])` ### Description Retrieves a logger instance. If log4js is not configured, it will be configured with default settings. You can specify a category for the logger or use the default category. ### Method `log4js.getLogger([category])` ### Parameters #### Path Parameters - **category** (string) - Optional - The category name for the logger. Defaults to 'default' if not provided. ### Logger Object Methods #### `(args...)` - **Description**: Dispatches a log event with the specified level. The level can be any lowercase name of the defined log levels (e.g., 'info', 'warn', 'error'). Formatting placeholders like `%s` and `%d` are delegated to `util.format`. - **Example**: `logger.info('User logged in: %s', userId)` #### `isEnabled()` - **Description**: Returns `true` if a log event of the specified level (camel case, e.g., `isInfoEnabled`) would be dispatched. This depends on the logger's configured level. - **Example**: `if (logger.isInfoEnabled()) { logger.info('This is an informational message.'); }` #### `addContext(key, value)` - **Description**: Adds a key-value pair to the logger's context. This context is added to all log events generated by this logger. Primarily used by `logFaces` appenders for tracking information like user IDs. - **Parameters**: - **key** (string) - Required - The key for the context data. - **value** (any) - Required - The value to associate with the key. - **Example**: `logger.addContext('userId', 'abc-123')` #### `removeContext(key)` - **Description**: Removes a previously defined key-value pair from the logger's context. - **Parameters**: - **key** (string) - Required - The key of the context data to remove. - **Example**: `logger.removeContext('userId')` #### `clearContext()` - **Description**: Removes all context key-value pairs from the logger. - **Example**: `logger.clearContext()` #### `setParseCallStackFunction(function | undefined)` - **Description**: Allows overriding the default function used to parse call stack data for log layouts. A generic JavaScript `Error` object is passed to this function. It must return an object with properties like `fileName`, `lineNumber`, `columnNumber`, `callStack`, `className`, `functionName`, `functionAlias`, and `callerName`. Passing `undefined` resets it to the default parser. - **Parameters**: - **function** (function | undefined) - Optional - The custom function to parse the call stack, or `undefined` to reset to default. - **Example**: `logger.setParseCallStackFunction(myCustomParser)` ### Logger Object Properties #### `level` - **Description**: Overrides the configured log level for this logger. Can be a log4js level object or a string (e.g., 'info', 'INFO'). Changing this affects all loggers of the same category. - **Type**: `string` or `object` #### `useCallStack` - **Description**: Overrides the configured `useCallStack` setting for this logger. If `true`, log events will include call stack information (line numbers, file names). Changing this affects all loggers of the same category. - **Type**: `boolean` #### `callStackLinesToSkip` - **Description**: Customizes how many lines of the call stack are skipped when parsing. Defaults to `0`. Useful for ignoring wrapper functions in the stack trace. - **Type**: `number` ``` -------------------------------- ### Replicating Console Logging in v2 Source: https://log4js-node.github.io/log4js-node/migration-guide.html This code snippet shows how to replicate the v1 behavior of replacing node.js console functions with log4js loggers in v2. Ensure log4js is configured before binding console methods. ```javascript log4js.configure(...); // set up your categories and appenders const logger = log4js.getLogger('console'); // any category will work console.log = logger.info.bind(logger); // do the same for others - console.debug, etc. ``` -------------------------------- ### Configure stdout appender with dummy layout Source: https://log4js-node.github.io/log4js-node/layouts.html Configures the stdout appender to use the dummy layout. This layout is primarily intended for specific appenders like logstashUDP and outputs only the first value in the log event's data. ```javascript log4js.configure({ appenders: { out: { type: "stdout", layout: { type: "dummy" } } }, categories: { default: { appenders: ["out"], level: "info" } }, }); ``` -------------------------------- ### Configure log4js for PM2 with Custom Instance Variable Source: https://log4js-node.github.io/log4js-node/clustering.html Configure log4js to work with PM2 by setting `pm2: true`. If you use a custom environment variable for PM2 instances (e.g., 'INSTANCE_ID'), specify it using `pm2InstanceVar`. ```javascript log4js.configure({ appenders: { out: { type: "stdout" } }, categories: { default: { appenders: ["out"], level: "info" } }, pm2: true, pm2InstanceVar: "INSTANCE_ID", }); ``` -------------------------------- ### Configure Status Code Rulesets Source: https://log4js-node.github.io/log4js-node/connect-logger.html Customize the log levels for specific HTTP status code ranges using the statusRules option in connectLogger. ```javascript app.use( log4js.connectLogger(logger, { level: "auto", statusRules: [ { from: 200, to: 299, level: "debug" }, { codes: [303, 304], level: "info" }, ], }) ); ``` -------------------------------- ### Configure custom appender module Source: https://log4js-node.github.io/log4js-node/appenders.html Load a custom appender module named 'gouda' with a specific flavor. This demonstrates using external appender modules. ```javascript log4js.configure({ appenders: { gouda: { type: "cheese/appender", flavour: "tasty" } }, categories: { default: { appenders: ["gouda"], level: "debug" } }, }); ``` -------------------------------- ### log4js.isConfigured() Source: https://log4js-node.github.io/log4js-node/api.html Checks if the log4js library has been configured. This includes explicit calls to `configure` or implicit configuration via `getLogger`. ```APIDOC ## GET /log4js.isConfigured ### Description Checks if the log4js library has been initialized via `configure()`. ### Method GET ### Endpoint /log4js.isConfigured ### Parameters None ### Request Example ```json {} ``` ### Response #### Success Response (200) - **configured** (boolean) - True if log4js has been configured, false otherwise. #### Response Example ```json { "configured": true } ``` ``` -------------------------------- ### Configure Default Daily Log Rolling Source: https://log4js-node.github.io/log4js-node/dateFile.html Use this configuration for daily log file rotation. The log file will be named based on the current date. ```javascript log4js.configure({ appenders: { everything: { type: "dateFile", filename: "all-the-logs.log" }, }, categories: { default: { appenders: ["everything"], level: "debug" }, }, }); ``` -------------------------------- ### Configure appender by passing module object Source: https://log4js-node.github.io/log4js-node/appenders.html Pass a custom appender module object directly into the configuration. Useful for bundlers like webpack. ```javascript const myAppenderModule = { configure: (config, layouts, findAppender, levels) => { /* ...your appender config... */ }, }; log4js.configure({ appenders: { custom: { type: myAppenderModule } }, categories: { default: { appenders: ["custom"], level: "debug" } }, }); ``` -------------------------------- ### Custom Layout Using Response Context Source: https://log4js-node.github.io/log4js-node/connect-logger.html Define a custom log layout that utilizes the response object from the logging event context to include status information in logs. ```javascript log4js.addLayout("customLayout", () => { return (loggingEvent) => { const res = loggingEvent.context.res; return util.format( ...loggingEvent.data, res ? `status: ${res.statusCode}` : "" ); }; }); ``` -------------------------------- ### Custom Log Format with Express Logger Source: https://log4js-node.github.io/log4js-node/connect-logger.html Configure the connectLogger with a custom format string or a formatting function for detailed log messages. Supports Express 3.x and 4.x. ```javascript app.use( log4js.connectLogger(logger, { level: log4js.levels.INFO, format: ":method :url", }) ); ``` ```javascript app.use( log4js.connectLogger(logger, { level: "auto", // include the Express request ID in the logs format: (req, res, format) => format( `:remote-addr - ${req.id} - ":method :url HTTP/:http-version" :status :content-length ":referrer" ":user-agent"` ), }) ); ``` ```javascript app.use( log4js.connectLogger(logger, { level: "info", format: (req, res, format) => format(`:remote-addr :method :url ${JSON.stringify(req.body)}`), }) ); ``` -------------------------------- ### Automatic Log Level Detection Source: https://log4js-node.github.io/log4js-node/connect-logger.html Enable automatic log level detection for connect-logger based on HTTP status codes. Compatible with Express 3.x and 4.x. ```javascript app.use(log4js.connectLogger(logger, { level: "auto" })); ``` -------------------------------- ### Configure Standard Output Appender Source: https://log4js-node.github.io/log4js-node/stdout.html Configures the stdout appender for log4js. This is the default appender and writes logs to the standard output stream. Ensure the appender type is set to 'stdout'. ```javascript log4js.configure({ appenders: { out: { type: "stdout" } }, categories: { default: { appenders: ["out"], level: "info" } }, }); ``` -------------------------------- ### Configure Call Stack Usage Source: https://log4js-node.github.io/log4js-node/api.html Allows overriding the 'useCallStack' configuration for a logger category. This affects line number and file name generation in log events. ```javascript logger.useCallStack = true; ``` -------------------------------- ### Custom Layouts - log4js.addLayout(type, fn) Source: https://log4js-node.github.io/log4js-node/api.html Allows you to define and register custom log layout functions. These functions format log events according to your specific needs. ```APIDOC ## Custom Layouts - `log4js.addLayout(type, fn)` ### Description This function is used to add user-defined layout functions to log4js. These custom layouts can then be used in your log4js configuration. ### Method `log4js.addLayout(type, fn)` ### Parameters #### Path Parameters - **type** (string) - Required - The name of the layout type (e.g., 'myCustomLayout'). - **fn** (function) - Required - The layout function. This function receives the log event data and should return a formatted string. ### Request Example ```javascript log4js.addLayout('json', (logEvent) => { return JSON.stringify({ timestamp: logEvent.startTime, level: logEvent.level.levelStr, message: logEvent.messages.join(' '), category: logEvent.categoryName }); }); // Then in your log4js configuration: // { // type: 'console', // layout: { type: 'json' } // } ``` ``` -------------------------------- ### Replace console logging with log4js Source: https://log4js-node.github.io/log4js-node/faq.html Manually override console methods like `console.log` to use a specific log4js logger. This requires configuring log4js first and then binding the logger methods to the console functions. ```javascript log4js.configure(...); // set up your categories and appenders const logger = log4js.getLogger('console'); console.log = logger.info.bind(logger); // do the same for others - console.debug, etc. ``` -------------------------------- ### Configure TCP Appender Source: https://log4js-node.github.io/log4js-node/tcp.html Configure the TCP appender to send error messages to a remote log server. Ensure the log server is running and configured to receive logs. ```javascript log4js.configure({ appenders: { network: { type: "tcp", host: "log.server" }, }, categories: { default: { appenders: ["network"], level: "error" }, }, }); ``` -------------------------------- ### Add Custom Layout Source: https://log4js-node.github.io/log4js-node/api.html Registers a user-defined layout function with log4js. This allows for custom log message formatting. ```javascript log4js.addLayout('myLayout', function(config) { return function(loggingEvent) { // custom layout logic return `${loggingEvent.startTime} - ${loggingEvent.level.levelStr} - ${loggingEvent.data.join(' ')}`; }; }); ``` -------------------------------- ### Configure Multiprocess Appender as Master Source: https://log4js-node.github.io/log4js-node/multiprocess.html Configure the multiprocess appender in master mode to listen for log events from workers. The `appender` property specifies where the master should send received logs. ```javascript log4js.configure({ appenders: { file: { type: "file", filename: "all-the-logs.log" }, server: { type: "multiprocess", mode: "master", appender: "file", loggerHost: "0.0.0.0", }, }, categories: { default: { appenders: ["file"], level: "info" }, }, }); ``` -------------------------------- ### Add Context to Logger Source: https://log4js-node.github.io/log4js-node/api.html Adds a key-value pair to all log events generated by this logger. Useful for tracking requests or user sessions. ```javascript logger.addContext('requestId', 'abc-123'); ``` -------------------------------- ### Log Message with Level Source: https://log4js-node.github.io/log4js-node/api.html Dispatches a log event with a specific level. Supports util.format placeholders for string formatting. ```javascript logger.info('User %s logged in from %s', user.name, user.ip); ``` -------------------------------- ### Configure Call Stack Lines to Skip Source: https://log4js-node.github.io/log4js-node/api.html Customizes the number of call stack lines to skip when parsing error stacks. Useful for ignoring wrapper functions. ```javascript logger.callStackLinesToSkip = 1; ``` -------------------------------- ### Enable line numbers in log output Source: https://log4js-node.github.io/log4js-node/faq.html Configure log4js to include line numbers in log messages by enabling `enableCallStack` for the category and using a pattern layout that includes `%f` (file) and `%l` (line number). ```javascript const log4js = require("log4js"); log4js.configure({ appenders: { out: { type: "stdout", layout: { type: "pattern", pattern: "%d %p %c %f:%l %m%n", }, }, }, categories: { default: { appenders: ["out"], level: "info", enableCallStack: true }, }, }); const logger = log4js.getLogger("thing"); logger.info("this should give me a line number now"); ``` -------------------------------- ### Shutdown - log4js.shutdown([callback]) Source: https://log4js-node.github.io/log4js-node/api.html Gracefully shuts down log4js by closing all appenders and ensuring all pending log events are written. This should be called before your application exits. ```APIDOC ## Shutdown - `log4js.shutdown([callback])` ### Description Gracefully shuts down log4js by closing all appenders and ensuring all pending log events are written. This should be called before your application exits to guarantee all logs are flushed and resources are released. ### Method `log4js.shutdown([callback])` ### Parameters #### Path Parameters - **callback** (function) - Optional - A function to be called once log4js has finished shutting down. ### Response Example ```javascript log4js.shutdown(() => { console.log('Log4js has shut down successfully.'); }); ``` ``` -------------------------------- ### Configure Console Appender in log4js-node Source: https://log4js-node.github.io/log4js-node/console.html Configure the console appender for log4js-node. Ensure the appender type is set to 'console' and specify the default category level. ```javascript log4js.configure({ appenders: { console: { type: "console" } }, categories: { default: { appenders: ["console"], level: "info" } }, }); ``` -------------------------------- ### Exclude Logs with Nolog Option Source: https://log4js-node.github.io/log4js-node/connect-logger.html Use the nolog option to specify patterns (string, regexp, array, or function) to omit certain log messages from being recorded. ```javascript app.use( log4js.connectLogger(logger, { level: "auto", format: ":method :url", nolog: ".gif|\.jpg$", }) ); ``` ```javascript app.use( log4js.connectLogger(logger, { level: "auto", format: ":method :url", nolog: (req, res) => res.statusCode < 400, }) ); ``` -------------------------------- ### Handle Memory Usage with 'log4js:pause' Events Source: https://log4js-node.github.io/log4js-node/dateFile.html Listen for 'log4js:pause' events to manage memory usage when the appender is buffering messages. Stop logging when `true` is received and resume when `false` is received. ```javascript log4js.configure({ appenders: { output: { type: "dateFile", filename: "out.log" }, }, categories: { default: { appenders: ["output"], level: "debug" } }, }); let paused = false; process.on("log4js:pause", (value) => (paused = value)); const logger = log4js.getLogger(); while (!paused) { logger.info("I'm logging, but I will stop once we start buffering"); } ``` -------------------------------- ### Configure Appenders Without Category Filter Source: https://log4js-node.github.io/log4js-node/categoryFilter.html This configuration achieves a similar outcome to the category filter by setting the log level of the 'noisy.component' category to 'off', effectively preventing its logs from being written to 'all-the-logs.log'. This method is an alternative when direct control over category logging levels is preferred. ```javascript log4js.configure({ appenders: { everything: { type: "file", filename: "all-the-logs.log" }, }, categories: { default: { appenders: ["everything"], level: "debug" }, "noisy.component": { appenders: ["everything"], level: "off" }, }, }); const logger = log4js.getLogger(); const noisyLogger = log4js.getLogger("noisy.component"); logger.debug("I will be logged in all-the-logs.log"); noisyLogger.debug("I will not be logged."); ``` -------------------------------- ### Configure Logger Level Source: https://log4js-node.github.io/log4js-node/api.html Allows overriding the configured log level for a specific logger category. Changes apply to all loggers of that category. ```javascript logger.level = 'DEBUG'; ``` -------------------------------- ### Check Log Level Enabled Source: https://log4js-node.github.io/log4js-node/api.html Returns true if a log event of the specified level would be dispatched. Useful for performance optimizations. ```javascript if (logger.isInfoEnabled()) { logger.info('This will only be logged if INFO level is enabled'); } ``` -------------------------------- ### Set Custom Call Stack Parser Source: https://log4js-node.github.io/log4js-node/api.html Allows overriding the default call stack parsing logic. The provided function must return specific properties about the call stack. ```javascript logger.setParseCallStackFunction(function (error) { // custom parsing logic return { fileName: error.fileName, lineNumber: error.lineNumber, columnNumber: error.columnNumber, callStack: error.callStack, className: error.className, functionName: error.functionName, functionAlias: error.functionAlias, callerName: error.callerName }; }); ``` ```javascript logger.setParseCallStackFunction(undefined); // Reset to default ``` -------------------------------- ### Configure Standard Error Appender Source: https://log4js-node.github.io/log4js-node/stderr.html Configures log4js to use the standard error appender. This appender writes all log events to the standard error stream. Ensure the appender type is set to 'stderr'. ```javascript log4js.configure({ appenders: { err: { type: "stderr" } }, categories: { default: { appenders: ["err"], level: "ERROR" } }, }); ```