### Install Pretty Logger Source: https://github.com/millosaurs/prettylogs/blob/main/README.md Installs the prettylogs package using various Node.js package managers. This is the first step to integrating the logger into your project. ```bash npm install @millosaurs/prettylogs ``` ```bash yarn add @millosaurs/prettylogs ``` ```bash pnpm add @millosaurs/prettylogs ``` ```bash bun add @millosaurs/prettylogs ``` -------------------------------- ### Development Debugging with Pretty Logger Source: https://github.com/millosaurs/prettylogs/blob/main/README.md Demonstrates using prettylogs for development debugging. This example shows how to log detailed information during complex operations like calculating a total, using logger.debug and logger.success. ```typescript import { logger } from "@millosaurs/prettylogs"; function calculateTotal(items: Item[]) { logger.debug(`Calculating total for ${items.length} items`); const total = items.reduce((sum, item) => { logger.debug(`Adding item: ${item.name} - $${item.price}`); return sum + item.price; }, 0); logger.success(`Total calculated: $${total}`); return total; } ``` -------------------------------- ### Express.js Integration with Pretty Logger Source: https://github.com/millosaurs/prettylogs/blob/main/README.md Shows how to integrate prettylogs into an Express.js application. It logs incoming requests using logger.info and provides examples for debugging and success logging within routes. ```typescript import express from "express"; import { logger } from "@millosaurs/prettylogs"; const app = express(); app.use((req, res, next) => { logger.info(`${req.method} ${req.path}`); next(); }); app.get("/api/users", (req, res) => { logger.debug("Fetching users from database"); // ... fetch users logger.success("Users retrieved successfully"); res.json(users); }); app.listen(3000, () => { logger.info("Server listening on port 3000"); }); ``` -------------------------------- ### Express.js Server with Complete Logging Source: https://context7.com/millosaurs/prettylogs/llms.txt Full integration example showing request logging, error handling, and operation tracking in an Express application using PrettyLogs. This snippet demonstrates how to use PrettyLogs middleware for request logging and error handling, along with logging CRUD operations. ```typescript import express from "express"; import { logger } from "@millosaurs/prettylogs"; const app = express(); app.use(express.json()); // Request logging middleware app.use((req, res, next) => { logger.info(`${req.method} ${req.path}`); next(); }); // Error handling middleware app.use((err, req, res, next) => { logger.error(`Unhandled error: ${err.message}`); logger.error(`Stack: ${err.stack}`); res.status(500).json({ error: "Internal server error" }); }); // CRUD operations with logging app.get("/api/users", async (req, res) => { try { logger.debug("Fetching users from database"); const users = await db.users.find({}); logger.success(`Retrieved ${users.length} users`); res.json(users); } catch (error) { logger.error(`Failed to fetch users: ${error.message}`); res.status(500).json({ error: "Failed to retrieve users" }); } }); app.post("/api/users", async (req, res) => { try { logger.debug(`Creating user: ${req.body.email}`); if (!req.body.email || !req.body.name) { logger.warn("Invalid user data received"); return res.status(400).json({ error: "Email and name required" }); } const user = await db.users.create(req.body); logger.success(`User created: ${user.id}`); res.status(201).json(user); } catch (error) { logger.error(`User creation failed: ${error.message}`); res.status(500).json({ error: "Failed to create user" }); } }); // Server initialization const PORT = process.env.PORT || 3000; app.listen(PORT, () => { logger.info(`Starting server on port ${PORT}`); logger.success("Server ready to accept connections"); }); ``` -------------------------------- ### Error Handling with Pretty Logger Source: https://github.com/millosaurs/prettylogs/blob/main/README.md Illustrates how to use prettylogs for error handling within an asynchronous function. It logs the start of processing, and catches and logs any errors using logger.error. ```typescript import { logger } from "@millosaurs/prettylogs"; async function processData() { try { logger.info("Starting data processing"); await fetchData(); logger.success("Data processing completed"); } catch (error) { logger.error(`Processing failed: ${error.message}`); } } ``` -------------------------------- ### Basic Logger Usage in TypeScript Source: https://github.com/millosaurs/prettylogs/blob/main/README.md Demonstrates the basic usage of the prettylogs logger in TypeScript. It shows how to import the logger and use its different levels (info, debug, warn, error, success) to log messages. ```typescript import { logger } from "@millosaurs/prettylogs"; logger.info("Server started on port 3000"); logger.debug("Fetching data from cache"); logger.warn("Cache miss, fetching from DB"); logger.error("Database connection failed"); logger.success("Data cached successfully"); ``` -------------------------------- ### TypeScript Definitions Usage Source: https://github.com/millosaurs/prettylogs/blob/main/README.md Shows how to import and use the logger in TypeScript, highlighting the benefit of built-in type safety and autocompletion provided by the package's TypeScript definitions. ```typescript import { logger } from "@millosaurs/prettylogs"; // Full type safety and autocomplete support logger.info("Typed message"); ``` -------------------------------- ### Logger API Reference Source: https://github.com/millosaurs/prettylogs/blob/main/README.md This section details the available methods for logging messages using the Pretty Logger library, including their purpose and usage. ```APIDOC ## Logger API Reference This section details the available methods for logging messages using the Pretty Logger library, including their purpose and usage. ### `logger.info(message: string): void` Logs an informational message with a cyan-colored badge. Use for general application status updates and non-critical information. ### `logger.debug(message: string): void` Logs a debug message with an orange-colored badge. Use for detailed diagnostic information during development. ### `logger.warn(message: string): void` Logs a warning message with a yellow-colored badge. Use for potentially problematic situations that don't prevent execution. ### `logger.error(message: string): void` Logs an error message with a red-colored badge. Use for error conditions and failures that require attention. ### `logger.success(message: string): void` Logs a success message with a green-colored badge. Use to confirm successful completion of operations. ``` -------------------------------- ### TypeScript Data Processing Pipeline with Pretty Logs Source: https://context7.com/millosaurs/prettylogs/llms.txt This TypeScript code demonstrates a data processing pipeline that reads from a file, parses JSON, validates records, transforms data, calculates statistics, and writes to an output file. It extensively uses the Pretty Logger for informational, debug, warning, success, and error messages, including file operations with fs/promises and error handling with try-catch blocks. ```typescript import { logger } from "@millosaurs/prettylogs"; import fs from "fs/promises"; interface DataRecord { id: string; name: string; value: number; } async function processDataPipeline(inputFile: string, outputFile: string) { logger.info(`Starting data pipeline: ${inputFile} -> ${outputFile}`); try { // Step 1: Read input file logger.debug(`Reading input file: ${inputFile}`); const rawData = await fs.readFile(inputFile, "utf-8"); logger.success(`Loaded ${rawData.length} bytes from ${inputFile}`); // Step 2: Parse data logger.debug("Parsing JSON data"); const records: DataRecord[] = JSON.parse(rawData); logger.success(`Parsed ${records.length} records`); // Step 3: Validate data logger.debug("Validating data records"); const validRecords = records.filter((record) => { if (!record.id || !record.name || typeof record.value !== "number") { logger.warn(`Invalid record skipped: ${JSON.stringify(record)}`); return false; } return true; }); logger.info(`Valid records: ${validRecords.length}/${records.length}`); // Step 4: Transform data logger.debug("Transforming data"); const transformedRecords = validRecords.map((record) => ({ ...record, value: record.value * 1.1, processedAt: new Date().toISOString(), })); logger.success("Data transformation completed"); // Step 5: Calculate statistics logger.debug("Calculating statistics"); const totalValue = transformedRecords.reduce((sum, r) => sum + r.value, 0); const avgValue = totalValue / transformedRecords.length; logger.info(`Total value: ${totalValue.toFixed(2)}`); logger.info(`Average value: ${avgValue.toFixed(2)}`); // Step 6: Write output logger.debug(`Writing output to: ${outputFile}`); await fs.writeFile(outputFile, JSON.stringify(transformedRecords, null, 2)); logger.success(`Output written to ${outputFile}`); logger.success("Data pipeline completed successfully"); return { processed: transformedRecords.length, skipped: records.length - validRecords.length, totalValue, avgValue, }; } catch (error) { logger.error(`Pipeline failed: ${error.message}`); logger.error(`Stack trace: ${error.stack}`); throw error; } } // Execute pipeline processDataPipeline("input.json", "output.json") .then((stats) => { logger.success(`Pipeline stats: ${JSON.stringify(stats)}`); }) .catch((error) => { logger.error("Pipeline execution failed"); process.exit(1); }); ``` -------------------------------- ### Informational Logging with Pretty Logger Source: https://context7.com/millosaurs/prettylogs/llms.txt Outputs general status updates and informational messages with a cyan-colored badge. Used for routine application events and non-critical status information. This function takes a string message as input. ```typescript import { logger } from "@millosaurs/prettylogs"; // Basic informational logging logger.info("Server started on port 3000"); logger.info("Connected to MongoDB"); logger.info("User authentication initialized"); // Dynamic content logging const port = 8080; const env = "production"; logger.info(`Application running on port ${port} in ${env} mode`); // Request logging in Express middleware app.use((req, res, next) => { logger.info(`${req.method} ${req.path} - ${req.ip}`); next(); }); ``` -------------------------------- ### Debug Logging with Pretty Logger Source: https://context7.com/millosaurs/prettylogs/llms.txt Outputs detailed diagnostic information with an orange-colored badge. Ideal for development and troubleshooting scenarios where granular execution details are needed. This function takes a string message as input. ```typescript import { logger } from "@millosaurs/prettylogs"; // Function execution tracking function calculateTotal(items: Item[]) { logger.debug(`Calculating total for ${items.length} items`); const total = items.reduce((sum, item) => { logger.debug(`Processing item: ${item.name} - Price: $${item.price}`); return sum + item.price; }, 0); logger.debug(`Final total: $${total}`); return total; } // API data inspection async function fetchUsers() { logger.debug("Initiating user fetch from database"); const users = await db.users.find({}); logger.debug(`Retrieved ${users.length} users from database`); logger.debug(`User data: ${JSON.stringify(users)}`); return users; } // Cache operations tracking logger.debug("Checking cache for user:123"); logger.debug("Cache hit - retrieving from memory"); ``` -------------------------------- ### logger.success() - Log Success Messages Source: https://context7.com/millosaurs/prettylogs/llms.txt Displays success messages with a green badge. Used to confirm successful completion of operations and positive outcomes. This function provides clear visual confirmation of successful tasks. ```typescript import { logger } from "@millosaurs/prettylogs"; // Operation completion async function createUser(userData: UserData) { const user = await db.users.create(userData); logger.success(`User created successfully: ${user.email}`); return user; } // Multi-step process tracking async function deployApplication() { logger.info("Starting deployment process"); await buildApplication(); logger.success("Application built successfully"); await runTests(); logger.success("All tests passed"); await uploadToServer(); logger.success("Deployment completed successfully"); } // Data processing confirmation async function importData(file: string) { logger.info(`Starting data import from ${file}`); const records = await parseFile(file); logger.debug(`Parsed ${records.length} records`); await db.bulkInsert(records); logger.success(`Successfully imported ${records.length} records`); } // Server startup app.listen(3000, () => { logger.success("Server listening on port 3000"); logger.success("All services initialized"); }); ``` -------------------------------- ### Warning Messages with Pretty Logger Source: https://context7.com/millosaurs/prettylogs/llms.txt Displays warning messages with a yellow-colored badge. Used for potentially problematic situations that don't prevent execution but require awareness. This function takes a string message as input. ```typescript import { logger } from "@millosaurs/prettylogs"; // Resource warnings function processRequest(data: RequestData) { if (data.size > 1000000) { logger.warn("Request payload exceeds 1MB - performance may be impacted"); } if (!data.userId) { logger.warn("No userId provided - using anonymous user"); } // Process request... } // Deprecated feature warnings function legacyEndpoint(req, res) { logger.warn("This endpoint is deprecated and will be removed in v2.0"); logger.warn("Please migrate to /api/v2/users"); // Handle request... } // Cache miss scenarios async function getCachedData(key: string) { const cached = await cache.get(key); if (!cached) { logger.warn(`Cache miss for key: ${key} - fetching from database`); return await fetchFromDatabase(key); } return cached; } ``` -------------------------------- ### logger.error() - Log Error Messages Source: https://context7.com/millosaurs/prettylogs/llms.txt Outputs error messages with a red badge. Used for exceptions, failures, and critical issues. This function helps in debugging by clearly marking critical errors in the logs. It is often used within try-catch blocks. ```typescript import { logger } from "@millosaurs/prettylogs"; // Exception handling async function processData() { try { logger.info("Starting data processing"); await fetchData(); await transformData(); } catch (error) { logger.error(`Processing failed: ${error.message}`); logger.error(`Stack trace: ${error.stack}`); throw error; } } // Database connection failures async function connectToDatabase() { try { await mongoose.connect(connectionString); } catch (error) { logger.error("Database connection failed"); logger.error(`Error details: ${error.message}`); process.exit(1); } } // Validation errors function validateUser(user: User) { if (!user.email) { logger.error("Validation failed: email is required"); return false; } if (!user.email.includes("@")) { logger.error(`Invalid email format: ${user.email}`); return false; } return true; } // API request failures app.get("/api/data", async (req, res) => { try { const data = await fetchData(); res.json(data); } catch (error) { logger.error(`API request failed: ${req.path}`); logger.error(`Error: ${error.message}`); res.status(500).json({ error: "Internal server error" }); } }); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.