react-native-beautiful-logs
Version:
A beautiful, feature-rich logging library for React Native applications with colored output and file persistence
111 lines (110 loc) • 5.77 kB
TypeScript
/**
* @fileoverview Utility functions supporting the logging library.
* Includes functions for formatting log messages for console output,
* handling dates for filename generation, manipulating strings (stripping ANSI codes),
* and formatting JavaScript objects/values into colorized JSON strings.
* @category Utilities
*/
import moment from 'moment';
import { LogLevel } from './types';
/**
* Calculates the "base date" used for determining the current log file session name.
* Log files cover a 2-day window based on odd/even days of the month to reduce
* file creation/churn exactly at midnight.
*
* - If the current day of the month is **odd** (1st, 3rd, 5th, ...), the base date is **today**.
* - If the current day of the month is **even** (2nd, 4th, 6th, ...), the base date is **yesterday**.
*
* This means logs generated on both the 1st and 2nd of the month go into the file
* named with the 1st's date (e.g., `session_YYYY-MM-01.txt`). Logs from the 3rd and 4th
* go into the file named with the 3rd's date (e.g., `session_YYYY-MM-03.txt`), and so on.
*
* @internal Used internally by {@link generateLogFilename}. Not intended for public use.
* @returns {moment.Moment} A Moment.js object representing the base date for the current log file window.
*/
export declare const getBaseLogDate: () => moment.Moment;
/**
* Generates the log filename for the current 2-day logging window based on the current date.
* The format is constructed using:
* - `LOG_FILE_PREFIX` (e.g., "session_")
* - The base date calculated by `getBaseLogDate()` formatted as 'YYYY-MM-DD'
* - `LOG_FILE_SUFFIX` (e.g., ".txt")
*
* @internal Used internally by `fileManager.ts` during session initialization (`initSessionLog`).
* @returns {string} The calculated log filename (e.g., `session_2024-01-15.txt`).
* @see {@link getBaseLogDate} - Calculates the date used in the filename.
* @see {@link LOG_FILE_PREFIX}
* @see {@link LOG_FILE_SUFFIX}
*/
export declare const generateLogFilename: () => string;
/**
* Formats a JavaScript value (object, array, primitive) into a colorized JSON string,
* suitable for printing to a terminal that supports ANSI color codes (like the RN Metro console).
* Uses colors defined in the `COLORS` constant for syntax highlighting.
* Handles basic types (string, number, boolean, null) and nested object/array structures.
* Gracefully handles `undefined` values and errors during `JSON.stringify`.
*
* @param obj - The value (object, array, primitive, null, undefined) to format. Accepts `unknown` type.
* @returns {string} A colorized string representation of the value for console output.
* Returns `'undefined'` (colored) for `undefined` input.
* Returns `'[Error formatting JSON]'` (colored) if `JSON.stringify` fails.
* @see {@link COLORS} - Contains the color definitions used.
* @see {@link formatConsoleMessage} - Uses this function to format object/array parts of log messages.
*
* @example
* ```typescript
* const myData = { name: "Example", count: 42, active: true, items: [1, null, 'test'] };
* const coloredJson = formatJSON(myData);
* console.log("Formatted Data:\n" + coloredJson);
* // Output (in a compatible terminal) will show the object with colored keys, strings, numbers, etc.
*
* console.log(formatJSON(undefined)); // Outputs colored 'undefined'
* ```
*/
export declare const formatJSON: (obj: unknown) => string;
/**
* Formats the complete log message string intended for console output.
* Includes:
* - Timestamp (HH:MM:SS.ms) with color.
* - Log level indicator (Symbol + Padded Level Name) with color.
* - Module name (if provided as `[ModuleName]` prefix) with color.
* - An arrow separator `→`.
* - The message parts, formatted appropriately:
* - Strings are included as-is.
* - Numbers/Booleans are colored.
* - `null`/`undefined` are represented and colored.
* - `Error` objects are formatted with name, message, and stack trace (colored and indented).
* - Other objects/arrays are formatted using `formatJSON` (colored and indented with a vertical bar).
*
* @param level - The log level (`'debug'`, `'info'`, `'warn'`, `'error'`).
* @param messageParts - An array of the original arguments passed to the `log` function (after potentially extracting the level). Should handle `unknown[]`.
* @param symbols - A map of log levels to their corresponding emoji symbols (from `SYMBOLS` constant).
* @returns {string} The fully formatted and colorized log string ready for `console.log`, `console.warn`, etc.
*
* @example Output Structure
* ```console
* 14:05:10.345 📱 INFO [Network] → Request successful: { response data... }
* 14:05:12.100 ❌ ERROR [AuthService] → Login failed:
* │ Error: Invalid credentials
* │ at loginUser (auth.js:42)
* │ at processRequest (server.js:101)
* ```
*/
export declare const formatConsoleMessage: (level: LogLevel, messageParts: unknown[], // Accept unknown[] for type safety
symbols: Record<LogLevel, string>) => string;
/**
* Removes ANSI escape codes (used for terminal colors and styles) from a string.
* This is essential for preparing console output for storage in plain text log files,
* ensuring readability without terminal control characters.
*
* @param message - The string that might contain ANSI escape codes (e.g., `\x1b[32mHello\x1b[0m`).
* @returns {string} The input string with all ANSI color/style codes stripped out (e.g., `Hello`).
*
* @example
* ```typescript
* const coloredMessage = "\x1b[31mError:\x1b[0m Something went wrong.";
* const plainTextMessage = stripAnsiCodes(coloredMessage);
* // plainTextMessage will be: "Error: Something went wrong."
* ```
*/
export declare const stripAnsiCodes: (message: string) => string;