### AMD Module Setup Source: https://github.com/pimterry/loglevel/blob/main/README.md This example shows how to load and use loglevel with AMD module loaders like RequireJS. ```javascript define(['loglevel'], function(log) { log.warn("dangerously convenient"); }); ``` -------------------------------- ### Usage Example Source: https://github.com/pimterry/loglevel/blob/main/_autodocs/STRUCTURE.md Demonstrates a typical usage pattern for initializing and using the loglevel library. Ensure loglevel is installed and imported before use. ```javascript // ✓ Usage example const log = require('loglevel'); log.setLevel('debug'); log.info("Application started"); ``` -------------------------------- ### Install loglevel Source: https://github.com/pimterry/loglevel/blob/main/_autodocs/index.md Install the loglevel package using npm. ```bash npm install loglevel ``` -------------------------------- ### Example Plugin: Prefixing Log Messages Source: https://github.com/pimterry/loglevel/blob/main/README.md Shows how to create a plugin that prefixes all log messages with 'Newsflash: '. This example redefines the `log.methodFactory` and then calls `log.rebuild()` to apply the plugin. ```javascript var originalFactory = log.methodFactory; log.methodFactory = function (methodName, logLevel, loggerName) { var rawMethod = originalFactory(methodName, logLevel, loggerName); return function (message) { rawMethod("Newsflash: " + message); }; }; log.rebuild(); // Be sure to call the rebuild method in order to apply plugin. ``` -------------------------------- ### Logger Usage Example Source: https://github.com/pimterry/loglevel/blob/main/_autodocs/types.md Illustrates how to configure a logger instance with a specific level and log messages. This example shows setting up both root and child loggers. ```typescript function setupLogger(logger: Logger): void { logger.setLevel('debug'); logger.debug("Initialized"); } const rootLog: RootLogger = require('loglevel'); const childLog: Logger = rootLog.getLogger('app'); setupLogger(rootLog); setupLogger(childLog); ``` -------------------------------- ### Start Integration Test Server Source: https://github.com/pimterry/loglevel/blob/main/CONTRIBUTING.md Starts a local test server on port 8000 for manual browser testing and debugging. This is the first step for running integration tests manually. ```bash npx grunt integration-test ``` -------------------------------- ### Valid Logger Name Examples Source: https://github.com/pimterry/loglevel/blob/main/_autodocs/errors.md Shows examples of valid arguments for log.getLogger(), which include non-empty strings and Symbols. These calls will not result in a TypeError. ```javascript log.getLogger('my-module'); // OK log.getLogger('API'); // OK log.getLogger(Symbol('unique')); // OK ``` -------------------------------- ### RootLogger Usage Example Source: https://github.com/pimterry/loglevel/blob/main/_autodocs/types.md Demonstrates how to import and use the root logger instance to log messages and create child loggers. ```typescript const log: RootLogger = require('loglevel'); log.info("message"); const child: Logger = log.getLogger('child'); ``` -------------------------------- ### Module Exports with Logging Source: https://github.com/pimterry/loglevel/blob/main/_autodocs/index.md Demonstrates how to get a logger for a specific module and export functions from that module. The main application can then get the same logger to control its logging level. ```javascript // In a module file: const log = require('loglevel').getLogger('my-module'); function doSomething() { log.trace("Starting operation"); // ... do work ... log.debug("Operation complete"); } module.exports = { doSomething }; // In app code: const myModule = require('./my-module'); const moduleLog = log.getLogger('my-module'); moduleLog.setLevel('trace'); // See all logs from my-module ``` -------------------------------- ### CommonJS Module Setup Source: https://github.com/pimterry/loglevel/blob/main/README.md Use this snippet to import and use loglevel in CommonJS environments like Node.js. ```javascript var log = require('loglevel'); log.warn("unreasonably simple"); ``` -------------------------------- ### Usage Example for LogLevel Source: https://github.com/pimterry/loglevel/blob/main/_autodocs/types.md Demonstrates how to set and check the current log level using the LogLevel constants. This is typically used for controlling logging verbosity. ```javascript log.setLevel(log.levels.ERROR); if (log.getLevel() <= log.levels.DEBUG) { log.debug("Debug enabled"); } ``` -------------------------------- ### Install grunt-template-jasmine-requirejs for Jasmine 1.x Source: https://github.com/pimterry/loglevel/blob/main/vendor/grunt-template-jasmine-requirejs/README.md Installs version ~0.1 of the template for compatibility with Jasmine 1.x test specs. ```bash npm install grunt-template-jasmine-requirejs@~0.1 --save-dev ``` -------------------------------- ### Example of defining a module within a RequireJS callback Source: https://github.com/pimterry/loglevel/blob/main/vendor/grunt-template-jasmine-requirejs/README.md Demonstrates defining a module named 'config' with specific properties inside a RequireJS callback function. ```javascript define("config", { "endpoint": "/path/to/endpoint" }) ``` -------------------------------- ### Install grunt-template-jasmine-requirejs for Jasmine 2.x Source: https://github.com/pimterry/loglevel/blob/main/vendor/grunt-template-jasmine-requirejs/README.md Installs the package for use with Jasmine 2.x. This is the default behavior. ```bash npm install grunt-template-jasmine-requirejs --save-dev ``` -------------------------------- ### Non-Test Example Source: https://github.com/pimterry/loglevel/blob/main/_autodocs/STRUCTURE.md Illustrates code that is not a test example, such as a unit test structure. This is provided for contrast to usage examples. ```javascript // ✗ Not a test example describe('loglevel', () => { it('logs messages', () => { expect(log.warn).toHaveBeenCalled(); }); }); ``` -------------------------------- ### Usage Examples for LoggingMethod Source: https://github.com/pimterry/loglevel/blob/main/_autodocs/types.md Shows how to assign a function to the LoggingMethod type and how it can be used with variadic arguments. Also illustrates its application within a method factory. ```typescript const traceFunc: LoggingMethod = log.trace; traceFunc("message", { data: 123 }, otherArg); // In methodFactory: const method: LoggingMethod = function(...msg) { console.log(...msg); }; ``` -------------------------------- ### Child Logger Logging Methods Example Source: https://github.com/pimterry/loglevel/blob/main/_autodocs/api-reference/logger.md Demonstrates how to use the trace, debug, info, warn, and error methods on a child logger instance. Ensure the child logger is created using log.getLogger(name). ```javascript const logger = log.getLogger('my-module'); logger.trace("Detailed trace"); logger.debug("Debug info"); logger.info("Informational message"); logger.warn("Warning message"); logger.error("Error message"); ``` -------------------------------- ### Usage Example for LogLevelDesc Source: https://github.com/pimterry/loglevel/blob/main/_autodocs/types.md Demonstrates how to use the LogLevelDesc type when setting the logging level. Invalid values will result in a TypeError at runtime. ```typescript function setLoggingLevel(level: LogLevelDesc) { log.setLevel(level); } setLoggingLevel('debug'); // OK setLoggingLevel(1); // OK setLoggingLevel(log.levels.WARN); // OK (this is 3) setLoggingLevel('invalid'); // Error at runtime: TypeError ``` -------------------------------- ### Testing Custom Method Factories Source: https://github.com/pimterry/loglevel/blob/main/_autodocs/api-reference/method-factory.md This example demonstrates how to test a custom `methodFactory` by intercepting log messages and asserting their content. ```javascript describe('Custom Factory', () => { it('should format messages correctly', () => { const messages = []; log.methodFactory = function(methodName, level, loggerName) { return function(...args) { messages.push({ method: methodName, args: args }); }; }; log.rebuild(); log.info("test", { data: 123 }); expect(messages[0].method).toBe('info'); expect(messages[0].args).toEqual(["test", { data: 123 }]); }); }); ``` -------------------------------- ### Example of log.rebuild() usage Source: https://github.com/pimterry/loglevel/blob/main/README.md Demonstrates how changing the root logger's level affects child loggers only after calling `log.rebuild()`. This is useful for updating existing child loggers when the root configuration changes. ```javascript var childLogger1 = log.getLogger("child1"); childLogger1.getLevel(); // WARN (inherited from the root logger) var childLogger2 = log.getLogger("child2"); childLogger2.setDefaultLevel("TRACE"); childLogger2.getLevel(); // TRACE log.setLevel("ERROR"); // At this point, the child loggers have not changed: childLogger1.getLevel(); // WARN childLogger2.getLevel(); // TRACE // To update them: log.rebuild(); childLogger1.getLevel(); // ERROR (still inheriting from root logger) childLogger2.getLevel(); // TRACE (no longer inheriting because `.setDefaultLevel() was called`) ``` -------------------------------- ### Usage Example for LogLevelNames Source: https://github.com/pimterry/loglevel/blob/main/_autodocs/types.md Demonstrates type-safe logging method calls using the LogLevelNames type alias. Note that setLevel() accepts case-insensitive strings. ```typescript // Type-safe method names const methodName: LogLevelNames = 'trace'; log[methodName]("message"); // log.trace("message") ``` -------------------------------- ### Project File Structure Source: https://github.com/pimterry/loglevel/blob/main/_autodocs/DELIVERY_SUMMARY.md This tree displays the directory and file organization for the loglevel project, including the main README, documentation guides, API references, and verification reports. ```text /workspace/home/output/ ├── README.md Entry point (8.4K) ├── STRUCTURE.md Navigation guide (8.2K) ├── index.md Overview (11K) ├── types.md Type definitions (8.2K) ├── configuration.md Configuration (8.4K) ├── errors.md Error reference (7.3K) ├── COMPLETENESS_CHECK.txt Verification report └── api-reference/ ├── root-logger.md Root logger API (17K) ├── logger.md Child logger API (11K) └── method-factory.md Plugin system (13K) ``` -------------------------------- ### Configure Loglevel Programmatically Source: https://github.com/pimterry/loglevel/blob/main/_autodocs/configuration.md Loglevel configuration must be done via API calls, not environment variables or config files. This example shows setting different levels based on the environment. ```javascript // This does NOT work: // process.env.LOG_LEVEL = 'debug' // Instead: log.setLevel('debug'); ``` ```javascript // logger-setup.js const log = require('loglevel'); exports.setup = function(env) { if (env === 'production') { log.setDefaultLevel('error'); log.getLogger('api').setDefaultLevel('warn'); } else { log.setLevel('debug'); } }; // In your app: const setup = require('./logger-setup'); setup(process.env.NODE_ENV); ``` -------------------------------- ### Send Logs to Server with Custom methodFactory Source: https://github.com/pimterry/loglevel/blob/main/_autodocs/api-reference/root-logger.md An advanced example of using methodFactory to send logs to a server in addition to the console. Ensure rebuild() is called after modification. ```javascript const originalFactory = log.methodFactory; log.methodFactory = function(methodName, logLevel, loggerName) { const rawMethod = originalFactory(methodName, logLevel, loggerName); return function(...args) { rawMethod(...args); fetch('/api/logs', { method: 'POST', body: JSON.stringify({ level: methodName, message: args.join(' '), logger: loggerName, timestamp: new Date().toISOString() }) }).catch(console.error); }; }; log.rebuild(); ``` -------------------------------- ### Usage Example for MethodFactory Source: https://github.com/pimterry/loglevel/blob/main/_autodocs/types.md Illustrates creating a custom logging method factory that prefixes log messages with the logger name and method name. This factory can be assigned to `log.methodFactory`. ```typescript const myFactory: MethodFactory = (methodName, level, loggerName) => { return (...msg) => { console.log(`[${loggerName}:${methodName}]`, ...msg); }; }; log.methodFactory = myFactory; log.rebuild(); ``` -------------------------------- ### Invalid Log Level Examples Source: https://github.com/pimterry/loglevel/blob/main/_autodocs/errors.md Demonstrates various ways to call setLevel() with invalid values that will trigger a TypeError. Includes string, number, and object types. ```javascript log.setLevel('invalid'); // TypeError log.setLevel(10); // TypeError (too high) log.setLevel(-1); // TypeError (negative) log.setLevel('INVALID'); // TypeError log.setLevel({}); // TypeError log.setLevel(null); // TypeError log.setLevel(undefined); // TypeError ``` -------------------------------- ### Child Logger Restrictions Example Source: https://github.com/pimterry/loglevel/blob/main/_autodocs/api-reference/logger.md Demonstrates the unavailability of getLogger and noConflict methods on child loggers, resulting in TypeErrors. ```javascript const logger = log.getLogger('app'); logger.trace("OK"); logger.setLevel("debug"); // OK logger.getLogger("nested"); // TypeError: logger.getLogger is not a function logger.noConflict(); // TypeError: logger.noConflict is not a function ``` -------------------------------- ### Usage Example for LogLevelNumbers Source: https://github.com/pimterry/loglevel/blob/main/_autodocs/types.md Shows how to use the LogLevelNumbers type alias for the return type of getLevel(). This ensures type safety when working with numeric log levels. ```typescript // Return type of getLevel() const level: LogLevelNumbers = log.getLevel(); ``` -------------------------------- ### Import and Usage of Loglevel Types in TypeScript Source: https://github.com/pimterry/loglevel/blob/main/_autodocs/types.md Demonstrates how to import and use key loglevel types like LogLevel, Logger, and LogLevelDesc in a TypeScript project. Ensure you have 'loglevel' installed and configured for TypeScript. ```typescript import log, { LogLevel, Logger, LogLevelDesc } from 'loglevel'; const level: LogLevelDesc = 'warn'; log.setLevel(level); const child: Logger = log.getLogger('app'); const allLevels: LogLevel = log.levels; ``` -------------------------------- ### Colorful Log Output Plugin for LogLevel Source: https://github.com/pimterry/loglevel/wiki/Home This plugin enhances log output with ANSI colors using the 'chalk' library. It requires 'loglevel' and 'chalk' to be installed. The plugin customizes the method factory to apply colors based on logger name and log level. ```javascript var log = require('loglevel'); var chalk = require('chalk'); // very simple quick'n'dirty hash function var getColorFromStr = function(str) { if (str === undefined || str.length == 0) return chalk.white var hash = 0, i, len; for (var i = str.length; i--; ) { hash += str.charCodeAt(i); } var chalkColors = [ chalk.red, chalk.green, chalk.yellow, chalk.blue, chalk.magenta, chalk.cyan] return chalkColors[ hash % chalkColors.length ] }; // loglevel Plugin to create colorfull log output using 'chalk' var originalFactory = log.methodFactory; log.methodFactory = function (methodName, logLevel, loggerName) { var rawMethod = originalFactory(methodName, logLevel, loggerName); var logLevelNames = ['TRACE', 'DEBUG', 'INFO ', 'WARN ', 'ERROR']; var messageColor = getColorFromStr(loggerName); // or getColorFromStr(logLevel) return function (message) { rawMethod(chalk.cyan.underline(loggerName) + " " + chalk.bold.magenta(logLevelNames[logLevel]) + " " + messageColor(message) ); }; }; log.setLevel("trace"); // must setLevel to activate plugin ``` -------------------------------- ### Handling Logger Creation TypeErrors Source: https://github.com/pimterry/loglevel/blob/main/_autodocs/errors.md Illustrates how to handle TypeError exceptions that may occur when creating a logger with an invalid name. This example shows a try-catch block to catch TypeErrors and fall back to the root logger. ```javascript function createLogger(name) { try { return log.getLogger(name); } catch (e) { if (e instanceof TypeError) { console.error("Cannot create logger:", e.message); // Fall back to root logger return log; } } } ``` -------------------------------- ### Add Logger Name Prefix to Log Messages Source: https://github.com/pimterry/loglevel/blob/main/_autodocs/api-reference/method-factory.md This example demonstrates how to modify the method factory to include the logger's name as a prefix in log messages. It handles root loggers by using '[root]' as the prefix. Rebuilding the logger is necessary after the change. ```javascript const log = require('loglevel'); const originalFactory = log.methodFactory; log.methodFactory = function(methodName, level, loggerName) { const rawMethod = originalFactory(methodName, level, loggerName); const prefix = loggerName ? `[${loggerName}]` : '[root]'; return function(...args) { rawMethod(prefix, ...args); }; }; log.rebuild(); // Usage const apiLogger = log.getLogger('api'); const dbLogger = log.getLogger('db'); log.info("Root message"); // [root] Root message apiLogger.info("API message"); // [api] API message dbLogger.info("DB message"); // [db] DB message ``` -------------------------------- ### Basic loglevel Usage Source: https://github.com/pimterry/loglevel/blob/main/_autodocs/index.md Demonstrates basic logging with default WARN level and changing the level to debug. Also shows how to create and configure module-specific loggers. ```javascript const log = require('loglevel'); // Default level is WARN - only warn and error are logged log.warn("Warning message"); // Logged log.info("Info message"); // Not logged log.error("Error message"); // Logged // Change the level log.setLevel('debug'); log.debug("Now this is logged"); // Create module-specific loggers const apiLogger = log.getLogger('api'); apiLogger.setLevel('trace'); apiLogger.debug("Detailed API logging"); ``` -------------------------------- ### Setting and Logging with Log Levels Source: https://github.com/pimterry/loglevel/blob/main/_autodocs/index.md Demonstrates how to set the log level and which messages are logged based on the set level. Messages at the specified level and higher are logged. ```javascript log.setLevel('warn'); // Level 3 log.trace("no"); // Level 0 - not logged log.debug("no"); // Level 1 - not logged log.info("no"); // Level 2 - not logged log.warn("yes"); // Level 3 - logged log.error("yes"); // Level 4 - logged ``` -------------------------------- ### TypeScript Global Declaration Source: https://github.com/pimterry/loglevel/blob/main/README.md Example of how to declare loglevel as a global variable in TypeScript for specific use cases. ```typescript import * as log from 'loglevel'; export as namespace log; export = log; ``` -------------------------------- ### Get Logger Level Source: https://github.com/pimterry/loglevel/blob/main/_autodocs/api-reference/logger.md Retrieves the current logging level of a logger as a number. Useful for conditional logging. ```javascript const logger = log.getLogger('myapp'); logger.setLevel('debug'); logger.getLevel(); // Returns 1 if (logger.getLevel() <= log.levels.INFO) { logger.info("Info and above are logged"); } ``` -------------------------------- ### Open Manual Test Page for Console Experimentation Source: https://github.com/pimterry/loglevel/blob/main/CONTRIBUTING.md Opens a specific HTML page designed for experimenting with the global `log` object in the browser's developer console. Requires the integration test server to be running. ```bash http://127.0.0.1:8000/test/manual-test.html ``` -------------------------------- ### Best Practice: Wrapping the Original Factory Source: https://github.com/pimterry/loglevel/blob/main/_autodocs/api-reference/method-factory.md Demonstrates the recommended approach for customizing the `methodFactory` by first storing and then wrapping the original factory function. This ensures that loglevel's default behaviors and fallbacks are preserved. ```javascript // GOOD const original = log.methodFactory; log.methodFactory = function(methodName, level, loggerName) { const originalMethod = original(methodName, level, loggerName); return function(...args) { // Your custom logic originalMethod(...args); // Call the original }; }; // BAD - loses all of loglevel's fallback behavior log.methodFactory = function(methodName, level, loggerName) { // Reinventing how to call console methods if (console[methodName]) { return console[methodName].bind(console); } else { return console.log.bind(console); } // Missing: IE trace handling, no-op for missing console, etc. ``` -------------------------------- ### Importing and Accessing the Root Logger Source: https://github.com/pimterry/loglevel/blob/main/_autodocs/api-reference/root-logger.md Demonstrates various ways to import or access the root logger instance in different module systems and environments. ```javascript // CommonJS const log = require('loglevel'); // ES6 Module (default export) import log from 'loglevel'; // ES6 Module (wildcard import) import * as log from 'loglevel'; // Global (script tag) ``` -------------------------------- ### Loglevel Fork Modification Example Source: https://github.com/pimterry/loglevel/blob/main/vendor/grunt-template-jasmine-requirejs/README.md Illustrates a modification made in the loglevel fork to work with current lodash versions. ```js // LOGLEVEL-FORK: Work with current versions of lodash. return _.template("xyz")({ data: "ok" }); // END LOGLEVEL-FORK ``` -------------------------------- ### Level Control Methods Source: https://github.com/pimterry/loglevel/blob/main/_autodocs/README.md Methods for managing the logging level, including setting, getting, enabling, and disabling loggers. ```APIDOC ## Level Control Methods ### Description These methods provide granular control over which log messages are actually outputted based on their severity level. You can set a global level or manage levels for specific loggers. ### Methods - `setLevel(level, persist)` - `getLevel()` - `setDefaultLevel(level)` - `resetLevel()` - `enableAll()` - `disableAll()` ### Parameters - `level` (string | number): The desired logging level (e.g., 'TRACE', 'DEBUG', 'INFO', 'WARN', 'ERROR', 'SILENT' or their corresponding numeric values). - `persist` (boolean): If true, the level will be persisted in local storage (if available). ### Usage Pattern ```javascript loglevel.setLevel('WARN'); // Set global level to WARN console.log(loglevel.getLevel()); // Get current level loglevel.enableAll(); // Enable all logging levels ``` ``` -------------------------------- ### Get Current Logging Level Source: https://github.com/pimterry/loglevel/blob/main/_autodocs/api-reference/root-logger.md Retrieves the current logging level as a numeric value. Useful for conditional logging to avoid expensive computations. ```javascript const currentLevel = log.getLevel(); // 3 (if currently at WARN level) ``` ```javascript if (log.getLevel() <= log.levels.DEBUG) { const expensiveDebugData = computeDebugInfo(); log.debug(expensiveDebugData); } ``` -------------------------------- ### RequireJS Configuration with Main Config Source: https://github.com/pimterry/loglevel/blob/main/vendor/grunt-template-jasmine-requirejs/src/templates/jasmine-requirejs.html Applies a main RequireJS configuration if provided in the options. ```javascript if (options.mainRequireConfig) { require.config(<%= serializeRequireConfig(options.mainRequireConfig) %>); } ``` -------------------------------- ### Configure Log Level Using Different Representations Source: https://github.com/pimterry/loglevel/blob/main/_autodocs/configuration.md Demonstrates setting the log level using string names (case-insensitive), numeric values, or predefined constants. ```javascript log.setLevel('WARN'); // String, any case log.setLevel('warn'); // Case-insensitive log.setLevel(3); // Numeric log.setLevel(log.levels.WARN); // Constant ``` -------------------------------- ### Get Current Log Level Source: https://github.com/pimterry/loglevel/blob/main/demo/index.html Retrieves the current active logging level of the loglevel instance. This is useful for inspecting the current state of logging. ```javascript log.getLevel() ``` -------------------------------- ### Default Method Factory Behavior Source: https://github.com/pimterry/loglevel/blob/main/_autodocs/api-reference/method-factory.md Illustrates the default implementations and fallbacks for logging methods when using the default factory. It shows how methods like trace, debug, info, warn, and error are handled, including IE-specific logic and fallbacks to console.log or no-op functions. ```javascript // For 'trace' method in IE, wraps console.log and console.trace // For other methods, directly binds the console method // Falls back to console.log if the method doesn't exist // Falls back to no-op if console doesn't exist // Example default implementations: log.trace; // Bound to console.trace (or special IE handling) log.debug; // Mapped to console.log (debug aliases to log in some envs) log.info; // Bound to console.info (or falls back to console.log) log.warn; // Bound to console.warn (or falls back to console.log) log.error; // Bound to console.error (or falls back to console.log) ``` -------------------------------- ### Utilities Source: https://github.com/pimterry/loglevel/blob/main/_autodocs/README.md Utility methods for managing the loglevel instance. ```APIDOC ## Utilities ### Description Utility methods for managing the loglevel instance. ### Methods - `noConflict() ``` -------------------------------- ### Level Management Source: https://github.com/pimterry/loglevel/blob/main/_autodocs/api-reference/logger.md Explains how log levels are managed, including initial level setting, persistence for string-named loggers, and inheritance behavior. ```APIDOC ## Level Inheritance and Persistence ### Initial Level When a child logger is created, it inherits the root logger's current level. ```javascript log.setLevel('warn'); const logger = log.getLogger('child'); logger.getLevel(); // 3 (WARN) ``` ### Level Persistence (String-Named Loggers) String-named loggers can have their levels persisted to browser storage. ```javascript const logger = log.getLogger('my-module'); logger.setLevel('debug'); // Stored in localStorage['loglevel:my-module'] or as a cookie // After page reload: const logger2 = log.getLogger('my-module'); logger2.getLevel(); // 1 (DEBUG) - restored from storage ``` ### Symbol-Named Loggers Symbol-named loggers never persist their levels. ```javascript const sym = Symbol('unique'); const logger = log.getLogger(sym); logger.setLevel('debug'); // After page reload: const logger2 = log.getLogger(sym); logger2.getLevel(); // 3 (WARN) - level not restored ``` ### Inheritance After Root Change Child loggers that have not called `setLevel()` or `setDefaultLevel()` will inherit level changes from the root logger. ```javascript const child = log.getLogger('child'); log.setLevel('error'); child.getLevel(); // 4 (ERROR) - still inheriting // But not if explicit level was set: child.setLevel('debug'); log.setLevel('error'); child.getLevel(); // 1 (DEBUG) - not affected by root change ``` To update child loggers after changing the root level, call `log.rebuild()`. ``` -------------------------------- ### Configure Per-Module Logging Source: https://github.com/pimterry/loglevel/blob/main/_autodocs/index.md Set up distinct loggers for different modules and configure global logging levels based on the environment. Individual modules can also have their logging levels specifically set. ```javascript const log = require('loglevel'); // In different modules/files: const moduleALog = log.getLogger('module-a'); const moduleBLog = log.getLogger('module-b'); // In main app initialization: if (process.env.NODE_ENV === 'development') { log.setLevel('debug'); } else { log.setLevel('warn'); } // Can also configure individual modules: log.getLogger('verbose-module').setLevel('warn'); log.getLogger('critical-module').setLevel('trace'); ``` -------------------------------- ### Retrieve All Child Loggers Source: https://github.com/pimterry/loglevel/blob/main/_autodocs/api-reference/root-logger.md Get a dictionary of all child loggers created with getLogger(). This is useful for batch operations like updating levels across all child loggers. ```javascript const moduleLogger = log.getLogger('my-module'); const appLogger = log.getLogger('app'); const allLoggers = log.getLoggers(); // { 'my-module': Logger, 'app': Logger } // Update all child loggers to a specific level Object.values(allLoggers).forEach(logger => { logger.setLevel('debug'); }); ``` -------------------------------- ### Loglevel File Structure Source: https://github.com/pimterry/loglevel/blob/main/_autodocs/index.md Overview of the directory and file organization within the loglevel project. ```bash loglevel/ ├── lib/ │ └── loglevel.js # Main source (UMD module) ├── dist/ │ ├── loglevel.js # Unminified build │ └── loglevel.min.js # Minified build ├── index.d.ts # TypeScript definitions ├── package.json # Package metadata └── README.md # Full documentation ``` -------------------------------- ### Custom Filtered Method Factory Source: https://github.com/pimterry/loglevel/blob/main/_autodocs/api-reference/method-factory.md Replaces the default method factory to filter out log messages containing specific patterns. This example prevents messages with '[INTERNAL]' from being logged. ```javascript const log = require('loglevel'); const originalFactory = log.methodFactory; log.methodFactory = function(methodName, level, loggerName) { const rawMethod = originalFactory(methodName, level, loggerName); return function(...args) { const message = args.join(' '); // Don't log if message matches filter pattern if (message.includes('[INTERNAL]')) { return; // Skip this message } rawMethod(...args); }; }; log.rebuild(); // Usage log.info("This is public"); // Logged log.info("[INTERNAL] Debug info"); // Not logged ``` -------------------------------- ### RequireJS Configuration with Callback Modification Source: https://github.com/pimterry/loglevel/blob/main/vendor/grunt-template-jasmine-requirejs/src/templates/jasmine-requirejs.html Configures RequireJS, potentially modifying the callback function to ensure `launchTest()` is called after initialization. ```javascript var hasCallback = false; if (options.requireConfig) { if ('callback' in options.requireConfig) { /* Inserting launchTest() as the last statement in callback function to make sure spec is called after all initialization stuffs */ // capture the arguments and body fo callback function options.requireConfig['callback'].toString().replace(/^function\s+\w*\(([^)]*)\)\s*\{((?:.|[\n\r])*)}/m, function(match, args, body) { var being_recreated_function = []; if (args.length > 0) { args = args.split(/,\s*/); being_recreated_function = being_recreated_function.concat(args); } // append launchTest() to the end of function body body += '\nlaunchTest();'; being_recreated_function = being_recreated_function.concat(body); // recreate an anonymouse function with modified body // re-assign callback property by just created new function // (return value dosen't matter) options.requireConfig['callback'] = Function.apply(this, being_recreated_function); hasCallback = true; }); } require.config(<%= serializeRequireConfig(options.requireConfig) %>); } ``` -------------------------------- ### Run General Browser Usage Tests Source: https://github.com/pimterry/loglevel/blob/main/CONTRIBUTING.md Tests the general usage of the global `log` variable in a browser environment. ```bash npx grunt jasmine:global ``` -------------------------------- ### Launching Tests with RequireJS Source: https://github.com/pimterry/loglevel/blob/main/vendor/grunt-template-jasmine-requirejs/src/templates/jasmine-requirejs.html Defines the `launchTest` function to load test scripts and reporters using RequireJS, and initiates the test run. ```javascript // Delay onLoad function until we are ready var startTests = window.onload; window.onload = null; function launchTest() { require([ <% scripts.src.forEach(function(script, i){ script = script.replace(/\\/g, '/') // replace all backward slashes to forward slash %> '<%= script %>' <%= i < scripts.src.length-1 ? ',' : '' %> <% }) %> ], function(){ require(['<%= \[\]\.concat(scripts.specs,scripts.reporters).join("','") %>'], function(){ startTests(); }); }) } <% if (!hasCallback) { %> launchTest(); <% } %> ``` -------------------------------- ### Factory Invocation Count with setLevel Source: https://github.com/pimterry/loglevel/blob/main/_autodocs/api-reference/method-factory.md Demonstrates that the `methodFactory` is called once for each enabled logging level when `setLevel()` is invoked. This example shows how the call count changes based on the level set. ```javascript let callCount = 0; log.methodFactory = function(methodName, level, loggerName) { callCount++; return () => {}; }; log.setLevel('trace'); // Factory called 5 times (trace, debug, info, warn, error are all enabled) log.setLevel('error'); // Factory called 1 time (only error is enabled) console.log(callCount); // 6 ``` -------------------------------- ### Reset Log Level to Default Source: https://github.com/pimterry/loglevel/blob/main/_autodocs/configuration.md Resets a logger to its default level and clears any persisted level from storage. On the next page load, the logger will start at its configured default level. ```javascript log.resetLevel(); // - Clears persisted level from storage // - Resets to default level // - On next page load, starts at default ``` -------------------------------- ### Run Browser Context Tests Source: https://github.com/pimterry/loglevel/blob/main/CONTRIBUTING.md Tests loglevel's behavior when injected into an anonymous function in a browser context, rather than included as a regular script. ```bash npx grunt test-browser-context ``` -------------------------------- ### Release Global log Variable with noConflict Source: https://github.com/pimterry/loglevel/blob/main/_autodocs/api-reference/root-logger.md Use noConflict to release the global 'log' variable and get the loglevel instance for reassignment. This is useful when other libraries also use the 'log' global. ```javascript const logger = log.noConflict(); logger.info("Using renamed logger"); ``` -------------------------------- ### Specifying Log Levels Source: https://github.com/pimterry/loglevel/blob/main/_autodocs/index.md Shows different ways to specify the log level using strings, numbers, or predefined constants. ```javascript log.setLevel('warn'); // String (case-insensitive) log.setLevel(3); // Number (0-5) log.setLevel(log.levels.WARN); // Constant ``` -------------------------------- ### Enable Automatic Log Level Persistence Source: https://github.com/pimterry/loglevel/blob/main/_autodocs/configuration.md By default, log levels are automatically persisted to browser storage (localStorage or cookies). This example shows setting a level that will be restored on the next page load. ```javascript log.setLevel('debug'); // Stored in: // - localStorage['loglevel'] for root logger // - localStorage['loglevel:loggerName'] for named loggers // Falls back to cookies if localStorage unavailable ``` ```javascript // On page reload: log.getLevel(); // 1 (debug) - restored from storage ``` -------------------------------- ### Custom Logger-Specific Formatting with MethodFactory Source: https://github.com/pimterry/loglevel/blob/main/_autodocs/api-reference/logger.md Demonstrates how to create a custom method factory for a specific logger to alter its output formatting. This involves defining a new factory function that wraps the original and then calling rebuild() to apply the changes. ```javascript const logger1 = log.getLogger('service-a'); const logger2 = log.getLogger('service-b'); // Custom factory for service-a const originalFactory = log.methodFactory; logger1.methodFactory = function(methodName, logLevel, loggerName) { const rawMethod = originalFactory(methodName, logLevel, loggerName); return function(...args) { rawMethod(`[${loggerName.toUpperCase()}]`, ...args); }; }; logger1.rebuild(); // service-b uses default formatting logger1.info("From service-a"); // [SERVICE-A] From service-a logger2.info("From service-b"); // From service-b ``` -------------------------------- ### Catch Errors When Getting Loggers Source: https://github.com/pimterry/loglevel/blob/main/_autodocs/errors.md Use a try-catch block when calling `getLogger` to handle potential `TypeError` exceptions, such as when an invalid or missing logger name is provided. This allows for graceful fallback, like using the root logger. ```javascript function getOrCreateLogger(name) { try { return log.getLogger(name); } catch (e) { if (e instanceof TypeError && e.message.includes("supply a name")) { console.warn(`Invalid logger name: ${name}, using root logger`); return log; } throw e; // Unexpected error } } ``` -------------------------------- ### Global Script Tag Loading Source: https://github.com/pimterry/loglevel/blob/main/_autodocs/index.md Include the loglevel library via a script tag in an HTML file to make it available globally. ```html ``` -------------------------------- ### info() Source: https://github.com/pimterry/loglevel/blob/main/_autodocs/api-reference/root-logger.md Outputs an info message to the console with appropriate icons. Falls back to console.log() if console.info() is unavailable. ```APIDOC ## info() ### Description Outputs an info message to the console with appropriate icons. Falls back to `console.log()` if `console.info()` is unavailable. ### Method `info(...msg: any[]): void` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters #### Variadic Arguments - **msg** (any[]) - Description: Any data to log to the console (variadic arguments) ### Response #### Success Response - **void** ### Example ```javascript log.info("Request processed successfully"); ``` ``` -------------------------------- ### RequireJS Runner with Callback Configuration Source: https://github.com/pimterry/loglevel/blob/main/vendor/grunt-template-jasmine-requirejs/README.md Shows how the generated runner page includes RequireJS configuration, particularly a callback function that can define modules before the main loading sequence. ```javascript var require = { ... callback: function() { // suppose we define a module here define("config", { "endpoint": "/path/to/endpoint" }) require([*YOUR SOURCE*], function() { require([*YOUR SPECS*], function() { require([*GRUNT-CONTRIB-JASMINE FILES*], function() { // at this point your tests are already running. } } } } ... } ``` -------------------------------- ### Open Manual Browser Test Runner Source: https://github.com/pimterry/loglevel/blob/main/CONTRIBUTING.md Opens the test runner HTML file in a browser to manually run and debug tests. Ensure the integration test server is running first. ```bash http://127.0.0.1:8000/_SpecRunner.html ``` -------------------------------- ### enableAll(persist?) Source: https://github.com/pimterry/loglevel/blob/main/_autodocs/api-reference/root-logger.md Enables all logging at all levels, equivalent to setting the level to TRACE. ```APIDOC ## enableAll(persist?) ### Description Enable all logging at all levels (equivalent to `setLevel(log.levels.TRACE)`). Optionally persists the setting. ### Method `enableAll(persist?: boolean): void` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **persist** (boolean) - Optional - Whether to persist the level to localStorage/cookies. Defaults to `true`. ### Returns void ### Example ```javascript // Development or debugging log.enableAll(); // Now all messages at trace level and above are logged // Enable without persisting log.enableAll(false); ``` ### Equivalent to: ```javascript log.setLevel(log.levels.TRACE, persist); ``` ``` -------------------------------- ### Logging Methods Source: https://github.com/pimterry/loglevel/blob/main/README.md Provides five core logging methods (trace, debug, info, warn, error) and an alias for debug (log). These methods are designed to be robust and fall back gracefully in different environments. ```APIDOC ## Logging Methods ### Description Provides five core logging methods (trace, debug, info, warn, error) and an alias for debug (log). These methods are designed to be robust and fall back gracefully in different environments. ### Methods - `log.trace(msg)` - `log.debug(msg)` - `log.info(msg) - `log.warn(msg)` - `log.error(msg)` - `log.log(msg)` (alias for `log.debug(msg)`) ### Usage These methods accept a message string and will output logs to the console, with formatting dependent on the environment. They are guaranteed not to fail and will use the most relevant available console method if the specific one is not found. ``` -------------------------------- ### Set Initial Log Level Source: https://github.com/pimterry/loglevel/blob/main/_autodocs/configuration.md Configure the initial log level for your application early in its initialization process. Messages below the set level will not be logged. ```javascript const log = require('loglevel'); // Set level at startup log.setLevel('warn'); log.info("This won't be logged (below warn level)"); log.warn("This will be logged"); ``` -------------------------------- ### Per-Logger Custom Factories in loglevel Source: https://github.com/pimterry/loglevel/blob/main/_autodocs/api-reference/method-factory.md Demonstrates how to assign unique method factories to individual loggers, allowing for different formatting rules per logger. Remember to rebuild each logger after assigning a new factory. ```javascript const log = require('loglevel'); const rootFactory = log.methodFactory; // Create child loggers const apiLogger = log.getLogger('api'); const debugLogger = log.getLogger('debug'); // Root logger: add timestamp log.methodFactory = function(methodName, level, loggerName) { const raw = rootFactory(methodName, level, loggerName); return function(...args) { raw(`[${new Date().toISOString()}]`, ...args); }; }; log.rebuild(); // API logger: add emoji apiLogger.methodFactory = function(methodName, level, loggerName) { const emoji = { trace: '📍', debug: '🐛', info: 'ℹ️', warn: '⚠️', error: '🔴' }; const raw = rootFactory(methodName, level, loggerName); return function(...args) { raw(`${emoji[methodName]}`, ...args); }; }; apiLogger.rebuild(); // Debug logger: use console group debugLogger.methodFactory = function(methodName, level, loggerName) { const raw = rootFactory(methodName, level, loggerName); return function(...args) { console.group(`[DEBUG] ${methodName.toUpperCase()}`); raw(...args); console.groupEnd(); }; }; debugLogger.rebuild(); // Usage log.info("App started"); // [2025-02-15T...] App started apiLogger.info("API request"); // ℹ️ API request debugLogger.info("Detailed debug info"); // [DEBUG] INFO (grouped) ``` -------------------------------- ### Run RequireJS Browser Tests Source: https://github.com/pimterry/loglevel/blob/main/CONTRIBUTING.md Tests the main test suite using Jasmine and RequireJS in a browser environment. ```bash npx grunt jasmine:requirejs ``` -------------------------------- ### Enable All Logging Source: https://github.com/pimterry/loglevel/blob/main/demo/index.html Activates all logging messages, equivalent to setting the level to 'trace'. Use this to ensure no messages are missed. ```javascript log.enableAll() ``` -------------------------------- ### Run Browser Tests Source: https://github.com/pimterry/loglevel/blob/main/CONTRIBUTING.md Execute detailed tests within a headless browser environment. This command encompasses multiple sub-groups of browser-specific tests. ```bash npm run test-browser ``` -------------------------------- ### Implement Remote Logging Source: https://github.com/pimterry/loglevel/blob/main/_autodocs/index.md Extend the loglevel method factory to send log messages to a remote server via a POST request, in addition to local logging. Network errors during the fetch request are ignored. ```javascript const log = require('loglevel'); const originalFactory = log.methodFactory; log.methodFactory = function(methodName, level, loggerName) { const rawMethod = originalFactory(methodName, level, loggerName); return function(...args) { rawMethod(...args); // Still log locally // Also send to server fetch('/api/logs', { method: 'POST', body: JSON.stringify({ level: methodName, message: args.join(' '), timestamp: new Date().toISOString() }) }).catch(() => {}); // Ignore network errors }; }; log.rebuild(); ``` -------------------------------- ### enableAll Source: https://github.com/pimterry/loglevel/blob/main/_autodocs/api-reference/logger.md Enables all logging levels for a logger, equivalent to setting the level to TRACE. ```APIDOC ## enableAll(persist?) ### Description Enable all logging on this logger. This is equivalent to setting the level to TRACE. ### Method ```javascript enableAll(persist?: boolean): void ``` ### Parameters #### Path Parameters - **persist** (boolean) - Optional - Default: true - Persist the level change ### Returns - void ### Request Example ```javascript const logger = log.getLogger('debug-module'); logger.enableAll(); // Now logs at trace level ``` ``` -------------------------------- ### Set Logging Level with Persistence Source: https://github.com/pimterry/loglevel/blob/main/demo/index.html Configure the logging level, optionally persisting the setting. Use 'true' for persistence to save the level across sessions, or 'false' to keep it temporary. ```javascript log.setLevel("trace", true) log.setLevel("debug", true) log.setLevel("info", true) log.setLevel("warn", true) log.setLevel("error", true) log.setLevel("silent", true) log.setLevel("trace", false) log.setLevel("debug", false) log.setLevel("info", false) log.setLevel("warn", false) log.setLevel("error", false) log.setLevel("silent", false) ``` -------------------------------- ### Default vs. Custom Method Factory Source: https://github.com/pimterry/loglevel/blob/main/_autodocs/api-reference/method-factory.md Illustrates how customizing the `methodFactory` can lead to stack trace loss in browsers. The default behavior preserves stack traces, while a custom factory might obscure the origin of the log message. ```javascript // Default behavior - preserves stack traces log.info("Message"); // Browser shows: at your-code.js:123 // With custom factory - breaks stack traces log.methodFactory = function(...) { const raw = log.methodFactory(...); return function(...args) { raw(...args); // The log appears to come from here }; }; // Browser shows: at loglevel.js or your factory code, not your calling code ``` -------------------------------- ### Customization Source: https://github.com/pimterry/loglevel/blob/main/_autodocs/README.md Options for customizing the logging behavior, such as providing a custom method factory. ```APIDOC ## Customization ### Description Options for customizing the logging behavior, such as providing a custom method factory. ### Properties - `methodFactory = customFactory` ### Methods - `rebuild() ``` -------------------------------- ### loglevel Exported Methods and Properties Source: https://github.com/pimterry/loglevel/blob/main/_autodocs/README.md Lists all available logging methods, level control functions, logger factory methods, customization options, utilities, and constants provided by the loglevel library. Use these for direct logging, managing log levels, creating child loggers, and customizing logging behavior. ```javascript // Logging methods log.trace(...msg) log.debug(...msg) log.log(...msg) // alias for debug() log.info(...msg) log.warn(...msg) log.error(...msg) // Level control log.setLevel(level, persist?) log.getLevel() log.setDefaultLevel(level) log.resetLevel() log.enableAll(persist?) log.disableAll(persist?) // Logger factory log.getLogger(name) log.getLoggers() // Customization log.methodFactory = customFactory log.rebuild() // Utilities log.noConflict() // Constants log.levels = { TRACE: 0, DEBUG: 1, INFO: 2, WARN: 3, ERROR: 4, SILENT: 5 } log.default = log ``` -------------------------------- ### Run All Tests Source: https://github.com/pimterry/loglevel/blob/main/CONTRIBUTING.md Execute all automated tests for the loglevel project. This command runs all test suites, including browser and Node.js tests. ```bash npm test ``` -------------------------------- ### Enable All Logging Levels Source: https://github.com/pimterry/loglevel/blob/main/_autodocs/api-reference/root-logger.md Enables all logging at all levels, equivalent to setting the level to TRACE. Optionally persists the setting. ```javascript log.enableAll(); ``` ```javascript log.enableAll(false); ``` -------------------------------- ### Customization Source: https://github.com/pimterry/loglevel/blob/main/_autodocs/README.md Options for customizing logger behavior, including the method factory and rebuilding the logger. ```APIDOC ## Customization ### Description Provides ways to customize the underlying logging mechanism and reconfigure the logger. ### Properties & Methods - `methodFactory` (property): Allows setting a custom factory function for log methods. - `rebuild()`: Rebuilds the logger, applying any changes to configuration or method factory. ### Usage Pattern ```javascript // Example of setting a custom method factory (advanced usage) loglevel.methodFactory = function(methodName, originalFactory) { return function(message, ...args) { // Custom logic before calling original factory console.log(`[Custom Log - ${methodName.toUpperCase()}]`, message, ...args); originalFactory(message, ...args); }; }; loglevel.rebuild(); // Apply the new method factory loglevel.info('This message will use the custom factory'); ``` ``` -------------------------------- ### Silent No-Op Logging with Missing Console Source: https://github.com/pimterry/loglevel/blob/main/_autodocs/errors.md Demonstrates how loglevel methods act as no-ops without throwing errors when the console object is unavailable, such as in very old browsers before dev tools are opened. Logging automatically reactivates when the console becomes available. ```javascript // In IE8 before opening developer console: log.trace("message"); // Silent no-op, no error log.debug("data"); // Silent no-op, no error // When console becomes available (dev tools opened): // The logging methods are automatically reactivated // This subsequent call will work: log.info("now visible"); // Works ``` -------------------------------- ### Setting Initial Logger Level Source: https://github.com/pimterry/loglevel/blob/main/_autodocs/api-reference/logger.md Demonstrates how a child logger inherits the root logger's level when created. The `setLevel` method on the root logger affects newly created child loggers. ```javascript log.setLevel('warn'); const logger = log.getLogger('child'); logger.getLevel(); // 3 (WARN) ``` -------------------------------- ### Run Node.js Tests Source: https://github.com/pimterry/loglevel/blob/main/CONTRIBUTING.md Execute tests specifically designed to verify loglevel's functionality within a Node.js environment. ```bash npm run test-node ```