### Basic Usage of Consola Logging Methods Source: https://github.com/unjs/consola/blob/main/README.md Shows how to import and use core Consola logging methods like info, start, warn, success, and error. It also includes an example of using the box and prompt features. ```javascript // ESM import { consola, createConsola } from "consola"; // CommonJS const { consola, createConsola } = require("consola"); consola.info("Using consola 3.0.0"); consola.start("Building project..."); consola.warn("A new version of consola is available: 3.0.1"); consola.success("Project built!"); consola.error(new Error("This is an example error. Everything is fine!")); consola.box("I am a simple box"); await consola.prompt("Deploy to the production?", { type: "confirm", }); ``` -------------------------------- ### Install Consola using npm, yarn, or pnpm Source: https://github.com/unjs/consola/blob/main/README.md Demonstrates how to install the Consola library using different package managers. This is the first step to integrating Consola into your project. ```bash npm i consola ``` ```bash yarn add consola ``` ```bash pnpm i consola ``` -------------------------------- ### Install Consola Source: https://context7.com/unjs/consola/llms.txt Command to install the Consola package via npm. ```bash npm install consola ``` -------------------------------- ### Mocking Consola Types for Testing Source: https://github.com/unjs/consola/blob/main/README.md Provides examples of how to mock Consola's logging types using Jest or Vitest for testing purposes. It covers mocking all types or specific types. ```javascript // Jest consola.mockTypes((typeName, type) => jest.fn()); // Vitest consola.mockTypes((typeName, type) => vi.fn()); ``` ```javascript // Jest const fn = jest.fn(); // Vitest const fn = vi.fn(); consola.mockTypes(() => fn); ``` ```javascript // Jest consola.mockTypes((typeName) => typeName === "fatal" && jest.fn()); // Vitest consola.mockTypes((typeName) => typeName === "fatal" && vi.fn()); ``` -------------------------------- ### Mock Consola for Jest/Vitest Integration Source: https://github.com/unjs/consola/blob/main/README.md Provides code examples for integrating Consola with testing frameworks like Jest and Vitest. It covers mocking log types to capture messages and verifying them within tests. This requires Consola and the respective testing framework. ```javascript describe("your-consola-mock-test", () => { beforeAll(() => { // Redirect std and console to consola too // Calling this once is sufficient consola.wrapAll(); }); beforeEach(() => { // Re-mock consola before each test call to remove // calls from before // Jest consola.mockTypes(() => jest.fn()); // Vitest consola.mockTypes(() => vi.fn()); }); test("your test", async () => { // Some code here // Let's retrieve all messages of `consola.log` // Get the mock and map all calls to their first argument const consolaMessages = consola.log.mock.calls.map((c) => c[0]); expect(consolaMessages).toContain("your message"); }); }); ``` -------------------------------- ### Initialize and Use Consola Logging Source: https://github.com/unjs/consola/blob/main/examples/index.legacy.html Demonstrates basic initialization and usage of the Consola library. It shows how to set the log level, wrap all console methods, and log messages of different types. This is useful for debugging and monitoring application output. ```javascript consola.level = 5; consola.wrapAll(); for (let type of Object.keys(consola.options.types).sort()) { consola[type]("Open developer tools to see the magic!"); } ``` -------------------------------- ### Create a New Consola Instance Source: https://github.com/unjs/consola/blob/main/README.md Illustrates how to create a new, independent instance of Consola with custom configurations. This allows for more granular control over logging behavior, such as setting the log level or enabling/disabling fancy formatting. Requires the 'consola' package. ```javascript import { createConsola } from "consola"; const logger = createConsola({ // level: 4, // fancy: true | false // formatOptions: { // columns: 80, // colors: false, // compact: false, // date: false, // }, }); ``` -------------------------------- ### Basic Logging Methods in Consola Source: https://context7.com/unjs/consola/llms.txt Demonstrates the various logging levels available in Consola, ranging from fatal errors to trace logs. Each method supports multiple arguments and object formatting. ```javascript import { consola } from "consola"; consola.fatal("Application crashed!", { code: "FATAL_001" }); consola.error(new Error("Database connection failed")); consola.warn("A new version of consola is available: 3.0.1"); consola.log("Processing item", { id: 123, status: "pending" }); consola.info("Using consola 3.0.0"); consola.success("Project built!"); consola.fail("Test suite failed"); consola.ready("Server listening on port 3000"); consola.start("Building project..."); consola.debug("Variable value:", { foo: "bar" }); consola.trace("Entering function"); ``` -------------------------------- ### Create Custom Consola Instances Source: https://context7.com/unjs/consola/llms.txt Shows how to use the createConsola factory function to instantiate a logger with custom configuration, including log levels, formatting options, and custom reporters. ```javascript import { createConsola } from "consola"; const logger = createConsola({ level: 4, fancy: true, formatOptions: { columns: 80, colors: true, compact: false, date: true, }, }); logger.info("Custom logger initialized"); const jsonLogger = createConsola({ reporters: [ { log: (logObj) => { console.log(JSON.stringify(logObj)); }, }, ], }); jsonLogger.info("This will be JSON output"); ``` -------------------------------- ### Importing Core Consola Builds Source: https://github.com/unjs/consola/blob/main/README.md Illustrates how to import different builds of Consola, including basic, browser, and core versions, which can help in reducing bundle size. ```typescript import { consola, createConsola } from "consola/basic"; ``` ```typescript import { consola, createConsola } from "consola/browser"; ``` ```typescript import { createConsola } from "consola/core"; ``` -------------------------------- ### Initialize and Use Consola in Browser Source: https://github.com/unjs/consola/blob/main/examples/index.html This snippet demonstrates how to import and initialize Consola in a browser environment. It sets the log level, wraps all console methods, and logs messages using various types and custom tags. This is useful for debugging in the browser's developer console. ```javascript import consola from "../src/browser.js"; consola.level = 5; consola.wrapAll(); for (let type of Object.keys(consola.options.types).sort()) { consola[type]("Open developer tools to see the magic!"); } consola.withTag("customTag").info("Im from custom world!"); consola.withTag("customTag").log("Im from custom world!"); consola.error(new Error("Whoo Haha")); ``` -------------------------------- ### Interactive User Prompts with Consola Source: https://context7.com/unjs/consola/llms.txt Demonstrates how to use the prompt function to gather user input through various interfaces like text fields, confirmation dialogs, and select menus. ```javascript import { consola } from "consola"; async function main() { const name = await consola.prompt("What is your name?", { type: "text", placeholder: "Enter your name", initial: "John", default: "Anonymous", }); const confirmed = await consola.prompt("Do you want to continue?", { type: "confirm", initial: false, }); const projectType = await consola.prompt("Pick a project type.", { type: "select", options: [ "JavaScript", "TypeScript", { label: "CoffeeScript", value: "coffee", hint: "legacy" }, ], initial: "TypeScript", }); const tools = await consola.prompt("Select additional tools.", { type: "multiselect", required: false, options: [ { value: "eslint", label: "ESLint", hint: "recommended" }, { value: "prettier", label: "Prettier" }, { value: "gh-action", label: "GitHub Action" }, ], initial: ["eslint", "prettier"], }); try { const value = await consola.prompt("Enter value:", { type: "text", cancel: "reject", }); } catch (error) { consola.warn("User cancelled the prompt"); } consola.success(`Welcome ${name}! Project type: ${projectType}`); } main(); ``` -------------------------------- ### Configure Log Levels Source: https://context7.com/unjs/consola/llms.txt Explains how to set log levels to filter output. Levels range from silent to verbose, and can be configured via instances or environment variables. ```javascript import { consola, createConsola, LogLevels } from "consola"; consola.level = LogLevels.debug; const debugLogger = createConsola({ level: 4 }); debugLogger.debug("This will appear"); const productionLogger = createConsola({ level: 1 }); productionLogger.warn("This will appear"); ``` -------------------------------- ### Initialize Custom Consola Instances Source: https://context7.com/unjs/consola/llms.txt Create isolated logger instances with specific configurations such as log levels or custom reporters. Useful for testing or specialized output formatting. ```javascript import { consola } from "consola"; const verboseLogger = consola.create({ level: 5 }); verboseLogger.trace("Detailed trace info"); const customLogger = consola.create({ reporters: [ { log: (logObj, ctx) => { const prefix = logObj.tag ? `[${logObj.tag}] ` : ""; process.stdout.write(`${prefix}${logObj.args.join(" ")}\n`); }, }, ], }); ``` -------------------------------- ### Import Console Utilities from Consola Source: https://github.com/unjs/consola/blob/main/README.md Shows how to import various utility functions for console manipulation from the 'consola/utils' module. These utilities include text alignment, stripping ANSI codes, and colorization. Supports both ESM and CommonJS module systems. ```javascript // ESM import { stripAnsi, centerAlign, rightAlign, leftAlign, align, box, colors, getColor, colorize, } from "consola/utils"; // CommonJS const { stripAnsi } = require("consola/utils"); ``` -------------------------------- ### Create Custom JSON Reporter with Consola Source: https://github.com/unjs/consola/blob/main/README.md Demonstrates how to create a custom reporter for Consola that stringifies log objects into JSON format. This is useful for structured logging or integration with systems that expect JSON input. It requires the 'consola' package. ```typescript import { createConsola } from "consola"; const consola = createConsola({ reporters: [ { log: (logObj) => { console.log(JSON.stringify(logObj)); }, }, ], }); // Prints {"date":"2023-04-18T12:43:38.693Z","args":["foo bar"],"type":"log","level":2,"tag":""} consola.log("foo bar"); ``` -------------------------------- ### Integrate Consola with JSDOM VirtualConsole Source: https://github.com/unjs/consola/blob/main/README.md Demonstrates how to redirect output from JSDOM's VirtualConsole to a Consola instance. This allows Consola to capture and process logs generated within a simulated browser environment. Requires 'consola' and 'jsdom'. ```javascript { new jsdom.VirtualConsole().sendTo(consola); } ``` -------------------------------- ### Consola Subpath Exports for Environment Optimization Source: https://context7.com/unjs/consola/llms.txt Demonstrates Consola's subpath exports, allowing developers to import specific builds optimized for different environments like Node.js, browsers, or minimal CI usage. Includes options for full-featured, browser-optimized, basic, core, and utility-only imports. ```javascript // Full-featured Node.js build with fancy reporter import { consola, createConsola } from "consola"; // Browser-optimized build import { consola, createConsola } from "consola/browser"; // Basic reporter (smaller bundle, good for CI) import { consola, createConsola } from "consola/basic"; // Core only (smallest bundle, BYOB - bring your own reporter) import { createConsola } from "consola/core"; // Utility functions only import { colors, box, formatTree, stripAnsi, colorize } from "consola/utils"; ``` -------------------------------- ### Use Raw Logging Method in Consola Source: https://github.com/unjs/consola/blob/main/README.md Explains and demonstrates the `raw` method in Consola, which ensures that objects passed to logging functions are treated as literal data rather than potentially being interpreted as log messages or arguments. This prevents unexpected output when logging objects with properties like 'message' or 'args'. Requires the 'consola' package. ```javascript // Prints "hello" consola.log({ message: "hello" }); // Prints "{ message: 'hello' }" consola.log.raw({ message: "hello" }); ``` -------------------------------- ### Manage Custom Reporters Source: https://context7.com/unjs/consola/llms.txt Demonstrates how to add, remove, and replace custom reporters to handle log output. Reporters can be used for custom formatting or triggering side effects like process termination. ```javascript import { consola, createConsola } from "consola"; const jsonReporter = { log: (logObj, ctx) => { const output = { timestamp: logObj.date.toISOString(), level: logObj.type, tag: logObj.tag || undefined, message: logObj.args.join(" "), }; process.stdout.write(JSON.stringify(output) + "\n"); }, }; consola.addReporter(jsonReporter); consola.removeReporter(jsonReporter); consola.setReporters([jsonReporter]); ``` -------------------------------- ### Mock Logging Methods for Testing Source: https://context7.com/unjs/consola/llms.txt Replaces standard logging methods with mock functions to facilitate unit testing. This allows assertions on log calls and messages using testing frameworks like Vitest. ```javascript import { consola } from "consola"; import { vi, describe, beforeEach, test, expect } from "vitest"; describe("my-module", () => { beforeEach(() => { consola.wrapAll(); consola.mockTypes(() => vi.fn()); }); test("logs correct messages", async () => { consola.info("Operation started"); consola.success("Operation completed"); const infoMessages = consola.info.mock.calls.map((c) => c[0]); expect(infoMessages).toContain("Operation started"); }); }); ``` -------------------------------- ### Perform Raw Logging Source: https://context7.com/unjs/consola/llms.txt Uses the .raw method to log objects exactly as provided without interpretation. This prevents Consola from parsing objects with specific keys as log metadata. ```javascript import { consola } from "consola"; const apiResponse = { message: "Success", data: { id: 1 } }; consola.info.raw(apiResponse); consola.warn.raw({ args: ["some", "data"] }); ``` -------------------------------- ### Create Tagged Loggers with Consola Source: https://context7.com/unjs/consola/llms.txt Use withTag to create loggers with specific identifiers. Tags can be chained to establish hierarchical logging structures for better categorization. ```javascript import { consola } from "consola"; const apiLogger = consola.withTag("api"); apiLogger.info("Request received"); const routerLogger = consola.withTag("unjs").withTag("router"); routerLogger.info("Route matched"); ``` -------------------------------- ### Consola String Alignment Utilities Source: https://context7.com/unjs/consola/llms.txt Offers functions for aligning strings within a specified width in the console. Includes utilities to strip ANSI escape codes, and perform left, right, center, and generic alignment with customizable padding characters. ```javascript import { stripAnsi, centerAlign, rightAlign, leftAlign, align } from "consola/utils"; // Strip ANSI escape codes from text const coloredText = "\u001b[31mRed text\u001b[0m"; const plainText = stripAnsi(coloredText); console.log(plainText); // "Red text" // Center align text within width console.log(centerAlign("Title", 20)); // Output: " Title " // Right align text console.log(rightAlign("Value", 20)); // Output: " Value" // Left align text (pads right) console.log(leftAlign("Label", 20)); // Output: "Label " // Generic align function console.log(align("center", "Centered", 30)); console.log(align("right", "Right", 30)); console.log(align("left", "Left", 30)); // Custom padding character console.log(centerAlign("Header", 20, "-")); // Output: "-------Header-------" ``` -------------------------------- ### Control Log Queuing with pauseLogs and resumeLogs Source: https://context7.com/unjs/consola/llms.txt Globally pauses logging to queue incoming messages and resumes them later. This is useful for batching logs or suppressing output during specific application states. ```javascript import { consola } from "consola"; const logger1 = consola.withTag("service-a"); const logger2 = consola.withTag("service-b"); consola.log("Before pause - appears immediately"); consola.pauseLogs(); logger1.log("Service A ready"); logger2.log("Service B ready"); consola.info("Application initializing"); setTimeout(() => { consola.resumeLogs(); consola.success("All services started!"); }, 1000); ``` -------------------------------- ### Configure Default Logger Properties Source: https://context7.com/unjs/consola/llms.txt Apply default metadata to all logs generated by a specific instance using withDefaults. This is useful for injecting service IDs or consistent tags across modules. ```javascript import { consola } from "consola"; const serviceLogger = consola.withDefaults({ tag: "my-service", additional: "Service ID: svc-12345", }); serviceLogger.info("Service started"); ``` -------------------------------- ### Consola Box Creation for Terminal Output Source: https://context7.com/unjs/consola/llms.txt Enables the creation of styled text boxes in the terminal. Supports customization of borders (style, color), padding, alignment, and margins, with predefined border styles like solid, double, and rounded. ```javascript import { box } from "consola/utils"; // Simple box console.log(box("Hello World")); // Box with title console.log(box("Content here", { title: "My Box" })); // Fully customized box console.log(box("Custom styled box content\nWith multiple lines", { title: "Styled Box", style: { borderColor: "cyan", borderStyle: "double", // solid, double, rounded, singleThick padding: 2, valign: "center", // top, center, bottom marginLeft: 2, marginTop: 1, marginBottom: 1, }, })); // Available border styles: // - solid: ┌─┐│└─┘ // - double: ╔═╗║╚═╝ // - rounded: ╭─╮│╰─╯ // - singleThick: ┏━┓┃┗━┛ ``` -------------------------------- ### Consola Error Logging Source: https://github.com/unjs/consola/blob/main/examples/index.legacy.html Shows how to log errors using Consola. It demonstrates passing an Error object directly to the logger, which provides enhanced formatting and details in the console output. ```javascript consola.error(new Error("Whoo Haha")); ``` -------------------------------- ### Add Reporter to Exit on Fatal Errors with Consola Source: https://github.com/unjs/consola/blob/main/README.md Shows how to add a custom reporter to Consola that monitors log types and exits the process with a status code of 1 if a 'fatal' log type is encountered. This is useful for ensuring critical errors halt execution immediately. Requires the 'consola' package. ```typescript import { consola } from 'consola'; consola.addReporter({ log(logObj) { if(logObj.type === 'fatal') { process.exit(1) } } }) // Will exit on this line. consola.fatal("fatal error"); ``` -------------------------------- ### Consola Color Functions for Terminal Styling Source: https://context7.com/unjs/consola/llms.txt Provides functions for applying colors and styles to terminal text. It automatically detects color support and includes direct color functions, bright variants, text styles, background colors, and helpers for dynamic color retrieval and general colorization. ```javascript import { colors, getColor, colorize } from "consola/utils"; // Direct color functions console.log(colors.red("Error text")); console.log(colors.green("Success text")); console.log(colors.yellow("Warning text")); console.log(colors.blue("Info text")); console.log(colors.cyan("Highlighted")); console.log(colors.magenta("Special")); console.log(colors.gray("Muted text")); // Bright variants console.log(colors.redBright("Bright red")); console.log(colors.greenBright("Bright green")); // Text styles console.log(colors.bold("Bold text")); console.log(colors.dim("Dimmed text")); console.log(colors.italic("Italic text")); console.log(colors.underline("Underlined")); console.log(colors.strikethrough("Strikethrough")); // Background colors console.log(colors.bgRed("Red background")); console.log(colors.bgGreen("Green background")); // Get color by name with fallback const errorColor = getColor("red", "reset"); console.log(errorColor("Dynamic color")); // Colorize helper console.log(colorize("cyan", "Colorized text")); ``` -------------------------------- ### Consola Custom Tag Logging Source: https://github.com/unjs/consola/blob/main/examples/index.legacy.html Illustrates how to use Consola with custom tags for better organization of log messages. This feature helps in filtering and identifying logs originating from specific parts of the application. ```javascript consola.withTag("customTag").info("Im from custom world!"); ``` -------------------------------- ### Consola Tree Formatting for Hierarchical Data Source: https://context7.com/unjs/consola/llms.txt Formats hierarchical data into visually appealing ASCII trees for terminal display. Supports customization of colors, indentation prefixes, maximum depth, and ellipsis for truncated branches. ```javascript import { formatTree } from "consola/utils"; // Simple flat list as tree const keywords = ["console", "logger", "reporter", "cli"]; console.log(formatTree(keywords)); // Output: // ├─console // ├─logger // ├─reporter // └─cli // Nested tree structure const tree = [ { text: "src", color: "cyan", children: [ { text: "components", children: ["Button.tsx", "Input.tsx"], }, { text: "utils", color: "yellow", children: ["helpers.ts", "format.ts"], }, ], }, { text: "package.json", color: "green", }, ]; console.log(formatTree(tree)); // With options console.log(formatTree(tree, { color: "gray", // Overall tree color prefix: " ", // Indentation prefix maxDepth: 2, // Limit nesting depth ellipsis: "...", // Text shown when depth exceeded })); // Custom prefix for different style console.log(formatTree(keywords, { color: "cyan", prefix: " | ", })); ``` -------------------------------- ### Redirect Global Console and Streams Source: https://context7.com/unjs/consola/llms.txt Globally intercept native console methods or stdout/stderr streams to route them through Consola. This ensures consistent formatting across the entire application and third-party dependencies. ```javascript import { consola } from "consola"; consola.wrapConsole(); console.info("This goes through consola"); consola.restoreConsole(); consola.wrapStd(); process.stdout.write("Direct stdout write\n"); consola.restoreStd(); ``` -------------------------------- ### Display Styled Boxed Messages Source: https://context7.com/unjs/consola/llms.txt Render important notifications or banners in a styled terminal box. Supports custom borders, colors, alignment, and padding. ```javascript import { consola } from "consola"; consola.box({ title: "Update Available", message: "`v1.0.2` → `v2.0.0`", style: { padding: 2, borderColor: "yellow", borderStyle: "rounded", }, }); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.