UNPKG

react-native-beautiful-logs

Version:

A beautiful, feature-rich logging library for React Native applications with colored output and file persistence

119 lines (118 loc) 5.26 kB
/** * @fileoverview Manages file system operations for logging. This includes * initializing the log directory and file for a session, writing log entries, * cleaning up old log files based on configured rules, and providing an * interface (`loggerInterface`) to access and manage these files. * @category File Management */ import { LoggerInterface, LogLevel } from './types'; /** * Initializes the file logging session. This function ensures: * 1. A writable log directory (`<baseDir>/logs/`) exists, attempting default and fallback locations. * 2. The log file for the current 2-day window (see {@link generateLogFilename}) exists or is created. * 3. A session start marker is written to the log file. * 4. Log cleanup (`cleanupOldLogs`) is triggered upon successful initialization. * * This is called automatically by the first `log()` call or can be invoked manually * early in the app lifecycle (recommended for predictability). Handles concurrent calls gracefully. * * @example Manually initializing early in your app (e.g., index.js or App.tsx) * ```typescript * import { initSessionLog } from 'react-native-beautiful-logs'; * * async function initializeApp() { * // ... other setup * console.log('Initializing logging session...'); * const logSessionReady = await initSessionLog(); * if (logSessionReady) { * console.log('File logging initialized successfully.'); * } else { * console.warn("File logging could not be initialized. Logs will only go to console."); * } * // ... rest of app startup * } * * initializeApp(); * ``` * * @returns {Promise<boolean>} A promise resolving to `true` if initialization was successful * (log directory and file are ready for writing), and `false` otherwise. * Detailed errors during the process are logged internally via `console.warn` or `console.error`. * @category Core * @async */ export declare const initSessionLog: () => Promise<boolean>; /** * Deletes old log files based on configured limits (count, age, size). * Called automatically after successful session initialization (`initSessionLog`) * and can also be invoked manually via `loggerInterface.cleanupOldLogs()` (though less common). * * Cleanup Rules (applied in order): * 1. **Count:** If total log files > `MAX_LOG_FILES`, delete oldest files until limit is met. * 2. **Age:** Delete remaining files (excluding current session) older than `MAX_LOG_AGE_DAYS`. * 3. **Size:** Delete remaining files (excluding current session) larger than `MAX_LOG_SIZE_MB`. * * @returns {Promise<void>} A promise that resolves when cleanup is complete. Errors during cleanup are logged internally but do not throw. * @category File Management * @see {@link MAX_LOG_FILES} * @see {@link MAX_LOG_AGE_DAYS} * @see {@link MAX_LOG_SIZE_MB} * @async */ export declare const cleanupOldLogs: () => Promise<void>; /** * Writes a prepared log entry (message content) to the current session file, * prepending timestamp and level. Handles session initialization automatically if needed. * Checks file size *after* writing and triggers session rollover for the *next* write if limit exceeded. * This is the primary function used by `log()` to persist messages to the filesystem. * * @param {string} message The plain text message content to write (should already be formatted, without colors). * @param {LogLevel} level The log level associated with the message ('debug', 'info', 'warn', 'error'). * @returns {Promise<void>} A promise that resolves when the write operation (including potential init) is attempted. Errors are handled internally. * @category Core * @async */ export declare const writeToFile: (message: string, level: LogLevel) => Promise<void>; /** * Provides methods for interacting with the generated log files. * Allows retrieving file lists, reading content, and deleting files. * Accessed via the `loggerInterface` export from the library's main entry point. * * @example Using the LoggerInterface * ```typescript * import { loggerInterface, LoggerInterface } from 'react-native-beautiful-logs'; * * async function manageLogs() { * try { * const files = await loggerInterface.getLogFiles(); * console.log("Available log files:", files); * * if (files.length > 0) { * const newestLogName = files[0]; // Files are sorted newest first * console.log(`Reading content of ${newestLogName}...`); * const content = await loggerInterface.readLogFile(newestLogName); * * if (content) { * console.log(`Content of ${newestLogName} (first 500 chars):\n`, content.substring(0, 500)); * // You could now upload content, display it, etc. * } else { * console.log(`Could not read or file empty: ${newestLogName}`); * } * } * * // Example: Delete all logs except the current one * // console.log("Deleting old logs..."); * // const deleted = await loggerInterface.deleteAllLogs(); * // console.log("Deletion successful:", deleted); * * } catch (error) { * console.error("Error managing logs:", error); * } * } * * manageLogs(); * ``` * * @category File Management */ export declare const loggerInterface: LoggerInterface;