magiclogger - v0.1.0
    Preparing search index...

    Class SyncLogger

    Synchronous logger with blocking I/O for guaranteed delivery.

    All operations complete before returning, ensuring logs are written immediately. Perfect for security auditing, debugging, and crash-resilient logging at the cost of blocking application execution.

    SyncLogger

    const logger = new SyncLogger();
    logger.info('Step 1'); // Blocks until written
    logger.info('Step 2'); // Executes after Step 1 completes
    const audit = new SyncLogger({
    file: './audit.log',
    forceFlush: true, // fsync after each write
    useConsole: false
    });

    audit.info('User login', { userId: 123 });
    // Log guaranteed on disk before continuing
    Index

    Constructors

    • Creates a new synchronous logger instance.

      Parameters

      • Optionaloptions: LoggerOptions = {}

        Configuration options

        Configuration options for a MagicLogger instance. These settings control the logger's behavior, output format, identity, and destination.

        • Optionalcontext?: Record<string, unknown>

          Optional default context applied to all logs. Can include environment metadata, user data, etc. Individual log calls may override this.

          { env: 'staging', region: 'us-east-1' }
          
        • OptionalfallbackToSync?: boolean

          Fallback to synchronous logging when async buffers are full. Only applies when mode is 'async' or 'balanced'.

          true
          
        • Optionalfile?: string

          File path for log output (SyncLogger only). When provided, logs will be written to this file synchronously.

          './audit.log'
          
        • OptionalforceFlush?: boolean

          Force flush to disk after each write (SyncLogger only). Uses fsync to ensure data is written to disk.

          true
          
        • Optionalid?: string

          Unique identifier for the logger instance. Used for filtering logs across services or systems.

          'auth-service'
          
        • OptionalidGenerator?: () => string

          Custom ID generator function for log entries.

        • Optionallevel?: string

          Minimum log level to output. Messages below this level will be filtered out.

          'info' // Only info, warn, error, fatal will be logged
          
          'info'
          
        • OptionallogDir?: string

          Directory to store log files in (Node only).

          'logs'
          
        • OptionallogRetentionDays?: number

          Number of days to retain log files before pruning (Node only).

          30
          
        • OptionalmaxStoredLogs?: number

          Maximum number of log entries to keep in browser storage. Has no effect in Node.js environments.

          1000
          
        • Optionalmode?: "sync" | "async" | "auto" | "balanced"

          Logger performance mode configuration.

          • 'sync': Always synchronous (immediate output)
          • 'async': Always asynchronous (uses internal AsyncLogger)
          • 'auto': Smart detection based on environment
          • 'balanced': Micro-async buffer with sync fallback
          'sync'
          
        • Optionalperformance?: "features" | "balanced" | "speed"

          Performance target hint for auto mode detection.

          • 'features': Prioritize rich styling and features (sync)
          • 'speed': Prioritize throughput (async)
          • 'balanced': Balance between features and speed
          'balanced'
          
        • OptionalperformanceMode?: boolean

          Enable performance mode to disable styling for maximum throughput. When enabled, all styling is bypassed for 3x+ performance improvement.

          false
          
        • OptionalprettyPrint?: "json" | "inspect"

          Pretty-printing mode for non-string variadic args. 'inspect' uses util.inspect in Node (with colors when enabled); 'json' uses JSON.stringify; default is 'inspect'.

        • OptionalprintMetaInDebug?: boolean

          When true, and verbose mode is enabled, append a compact [meta] summary of selected keys after the printed message. Meta remains structured for transports. Default: false

        • OptionalqueueManager?: QueueManagerOptions | QueueManager

          Queue management configuration for handling backpressure. Can be a QueueManager instance or options to create one.

          // Using options
          queueManager: { maxSize: 10000, dropPolicy: 'tail', highWaterMark: 0.8 }

          // Using instance
          queueManager: new QueueManager({ maxSize: 5000, dropPolicy: 'priority' })
        • OptionalrateLimiter?: RateLimiterOptions | RateLimiter

          Rate limiting configuration for log throttling. Can be a RateLimiter instance or options to create one.

          // Using options
          rateLimiter: { max: 1000, window: 60000, strategy: 'sliding' }

          // Using instance
          rateLimiter: new RateLimiter({ max: 100, window: 10000 })
        • Optionalredactor?: RedactorOptions | Redactor

          PII and sensitive data redaction configuration. Can be a Redactor instance or options to create one.

          // Using preset
          redactor: { preset: 'strict' }

          // Using instance
          redactor: new Redactor({ preset: 'paranoid', auditTrail: true })
        • Optionalsampler?: SamplerOptions | Sampler

          Statistical sampling configuration for volume control. Can be a Sampler instance or options to create one.

          // Using options
          sampler: { rate: 0.1, strategy: 'adaptive', targetRate: 1000 }

          // Using instance
          sampler: createSamplerPreset('production')
        • OptionalstorageName?: string

          Name to use for browser storage (localStorage key or IndexedDB name). Has no effect in Node.js environments.

          'magiclogger-logs'
          
        • OptionalstoreInBrowser?: boolean

          Whether to store logs in browser storage when in browser environment. Has no effect in Node.js environments.

          false
          
        • OptionalstrictLevels?: boolean

          Enforces strict log level behavior. If true, unknown levels passed to .log() will throw. If false, unknown levels are treated as custom and passed to .custom().

          false
          
        • Optionaltags?: string[]

          Optional static tags applied to all logs from this logger. Helps group or filter logs by functional or organizational tag.

          ['api', 'auth']
          
        • Optionaltheme?: string | ThemeDefinition

          Theme used to style logger output. Can be a string (theme name from ThemeManager) or a full object.

          'dark'
          
          {
          * info: ['cyan', 'bold'],
          * error: ['brightRed', 'bold'],
          * header: ['brightWhite', 'bgBlue', 'bold']
          * }
        • OptionalthemeByTag?: Record<string, string>

          Optional mapping of tags to theme names. When provided, if a logger has any tag present in this map and no explicit theme is set, the mapped theme will be auto-applied. This enables brand/company-specific themes via tags.

          { acme: 'acme', contoso: 'contoso-dark' }
          
        • Optionaltransports?: Transport[]

          Array of transports to use for logging.

          []
          
        • OptionaluseColors?: boolean

          Enables or disables terminal or console color output.

          true
          
        • OptionaluseConsole?: boolean

          Whether to use console transport by default. Set to false to disable automatic console output.

          true
          
        • OptionaluseDefaultTransports?: boolean

          Whether to automatically create default transports.

          false
          
        • OptionaluseLocalStorage?: boolean

          Whether to use localStorage (true) or IndexedDB (false) for browser storage. Has no effect in Node.js environments.

          true
          
        • Optionalverbose?: boolean

          If enabled, debug-level logs will be shown.

          false
          
        • OptionalwriteToDisk?: boolean

          Writes logs to disk in timestamped .log files (Node only). Ignored in browsers.

          false
          

      Returns SyncLogger

      All operations are synchronous and block until complete. File output uses sync I/O with optional fsync for durability. Perfect for audit logging and scenarios requiring guaranteed delivery.

      const logger = new SyncLogger({
      file: './audit.log',
      forceFlush: true,
      useColors: false // Clean logs for parsing
      });

    Accessors

    • get s(): IStyleBuilder

      Gets the chainable style builder for formatting text.

      Returns IStyleBuilder

      The style builder instance

      Provides fluent API for applying colors and styles to text. Styles are applied synchronously when the chain is executed.

      const styled = logger.s.red.bold('Error!');
      logger.info(styled);
      // Styled text guaranteed written before continuing

    Methods

    • Prints text in a decorative box.

      Parameters

      • text: string

        Text to display in box

      • options: {
            border?: "single" | "double" | "rounded" | "heavy";
            borderColor?: string[];
            color?: string[];
            padding?: number;
        } = {}

        Box formatting options

      Returns void

      logger.box('Success!', {
      border: 'double',
      borderColor: ['green']
      });
    • Closes file handles and performs cleanup.

      Returns Promise<void>

      Always call this when done logging to:

      • Close file descriptors
      • Flush any pending writes
      • Free system resources
      const logger = new SyncLogger({ file: './app.log' });
      try {
      logger.info('Processing');
      } finally {
      logger.close(); // Always cleanup
      }
    • Colors specific parts of a message based on a color map.

      Parameters

      • message: string

        The message to log

      • colorMap: Record<string, ColorName[]>

        Map of text patterns to color arrays

      Returns string

      The styled message string

      logger.colorParts('User john_doe uploaded data.json', {
      'john_doe': ['cyan', 'bold'],
      'data.json': ['yellow']
      });
    • Counts occurrences with a label.

      Parameters

      • label: string = 'default'

        Counter label

      Returns void

      logger.count('api-calls'); // "api-calls: 1"
      logger.count('api-calls'); // "api-calls: 2"
    • Resets a counter.

      Parameters

      • label: string = 'default'

        Counter label to reset

      Returns void

    • Logs a custom styled message with optional prefix. Supports arbitrary color combinations and custom prefixes.

      Parameters

      • msg: string

        Message to log

      • colors: string[] = ...

        Array of color names to apply (default: ['white'])

      • prefix: string = 'LOG'

        Custom prefix for the message (default: 'LOG')

      Returns void

      logger.custom('Database connected', ['green', 'bold'], 'DB');
      logger.custom('API rate limit warning', ['yellow', 'italic'], 'RATE');
    • Logs a debug-level message synchronously.

      Parameters

      • message: string

        The debug message to log

      • Optionalmeta: LogEntryMeta

        Optional metadata object

      Returns void

      Only outputs when verbose mode is enabled. Blocks until written. Use for detailed diagnostic information during development.

      logger.debug('Processing item', {
      index: i,
      value: item,
      timestamp: Date.now()
      });
      // Debug info guaranteed written before next operation
    • Logs an error-level message synchronously with optional Error object.

      Parameters

      • message: string

        The error message

      • Optionalerror: Error | LogEntryMeta

        Error object or metadata

      • Optionalmeta: LogEntryMeta

        Additional metadata if error is an Error

      Returns void

      Blocks until written. Automatically extracts stack traces from Error objects. Critical for debugging as the error is guaranteed to be logged before continuing.

      try {
      dangerousOperation();
      } catch (err) {
      logger.error('Operation failed', err);
      // Error is guaranteed logged before cleanup
      }
    • Forces an fsync to ensure all data is written to disk.

      Returns void

      Usually not needed as SyncLogger flushes after each write by default. Use this if you disabled forceFlush in options but need to ensure a critical log is persisted.

      const logger = new SyncLogger({
      file: './app.log',
      forceFlush: false // Disabled for performance
      });

      logger.info('Normal log'); // May be buffered by OS
      logger.error('Critical error');
      logger.flush(); // Force critical error to disk
    • Formats text using template literal syntax with embedded styles.

      Parameters

      • strings: TemplateStringsArray

        Template literal strings

      • ...values: unknown[]

        Interpolated values

      Returns string

      The formatted string with styles applied

      Supports @-style tags for styling within template literals. Processing is synchronous and returns formatted string immediately.

      const msg = logger.fmt`@red{Error:} ${errorMessage} at @blue{${line}}`;
      logger.info(msg);
      // Formatted message guaranteed written
    • Gets the current log file path.

      Returns undefined | string

      The path to the log file, or undefined if not using file output

      const logger = new SyncLogger({ file: './app.log' });
      console.log(logger.getFilePath()); // './app.log'
    • Gets the number of writes to the file (for debugging).

      Returns number

    • Creates a log group (for API compatibility).

      Parameters

      • label: string

        Group label

      Returns void

    • Prints a formatted header with separators.

      Parameters

      • text: string

        The header text to display

      • Optionalstyles: string[]

        Optional array of color names to apply

      Returns void

      Creates a visually distinct header with separator lines. Output is written synchronously before method returns.

      logger.header('Configuration', ['blue', 'bold']);
      // Header guaranteed printed before next log
      logger.info('Config loaded');
    • Logs an info-level message synchronously.

      Parameters

      • message: string

        The message to log

      • Optionalmeta: LogEntryMeta

        Optional metadata object

      Returns void

      Blocks until the message is written to all outputs. Use for general informational messages.

      logger.info('Server started', { port: 3000 });
      // Execution pauses here until log is written
    • Prints a formatted list with bullets.

      Parameters

      • items: string[]

        Array of items to display

      • options: {
            bullet?: string;
            bulletColor?: string[];
            indent?: number;
            itemColor?: string[];
        } = {}

        List formatting options

      Returns void

      logger.list(['Item 1', 'Item 2', 'Item 3']);
      
    • Generic synchronous logging method with custom level.

      Parameters

      • message: string

        The message to log

      • Optionallevel: string = 'info'

        The severity level

      • Optionalmeta: LogEntryMeta

        Optional metadata object

      Returns void

      Blocks until written. Allows specifying any valid log level. Prefer using specific level methods (info, error, etc.) when possible.

      logger.log('Custom message', 'trace', {
      module: 'auth',
      action: 'validate'
      });
      // Custom level log guaranteed written
    • Displays a text-based progress bar.

      Parameters

      • percentage: number

        Progress percentage (0-100)

      • Optionalwidth: number = 40

        Width of the progress bar in characters

      • OptionalfillChar: string = '█'

        Character for filled portion

      • OptionalemptyChar: string = '░'

        Character for empty portion

      Returns void

      Renders a visual progress indicator synchronously. Useful for batch operations where each step must complete before continuing.

      for (let i = 0; i <= 100; i += 10) {
      logger.progressBar(i, 50);
      // Progress guaranteed displayed before next iteration
      processNextBatch();
      }
    • Prints a separator line.

      Parameters

      • Optionalchar: string = '-'

        Character to repeat for the separator

      • Optionallength: number = 60

        Length of the separator line

      Returns void

      Creates visual separation between log sections. Output is written synchronously.

      logger.info('Phase 1 complete');
      logger.separator('=', 80);
      logger.info('Starting Phase 2');
      // Separator guaranteed printed between phases
    • Logs a message with a predefined style preset.

      Parameters

      • msg: string

        Message to log

      • preset:
            | "info"
            | "success"
            | "warning"
            | "error"
            | "debug"
            | "important"
            | "highlight"
            | "muted"
            | "special"
            | "code"
            | "header"

        Style preset name

      Returns void

      logger.styled('Critical system failure', 'error');
      logger.styled('Operation completed', 'success');
    • Logs a success-level message synchronously.

      Parameters

      • message: string

        The success message to log

      • Optionalmeta: LogEntryMeta

        Optional metadata object

      Returns void

      Blocks until written. Use to indicate successful completion of operations. Typically displayed in green when colors enabled.

      await database.connect();
      logger.success('Database connected', {
      host: dbHost,
      port: dbPort
      });
      // Success guaranteed logged before proceeding
    • Displays data in a formatted table.

      Parameters

      • data: Record<string, unknown>[]

        Array of objects to display

      • options: {
            alignment?: "left" | "right" | "center";
            alternateRowColors?: boolean;
            border?: "none" | "single" | "double" | "rounded" | "heavy";
            borderColor?: string[];
            headerColor?: string[];
        } = {}

        Table formatting options

      Returns void

      logger.table([
      { name: 'Alice', role: 'Admin' },
      { name: 'Bob', role: 'User' }
      ]);
    • Starts a timer with the given label.

      Parameters

      • label: string

        Timer label

      Returns void

      logger.time('operation');
      // ... do work ...
      logger.timeEnd('operation');
    • Stops a timer and logs elapsed time.

      Parameters

      • label: string

        Timer label to stop

      Returns void

    • Logs a warning-level message synchronously.

      Parameters

      • message: string

        The warning message

      • Optionalmeta: LogEntryMeta

        Optional metadata

      Returns void

      Blocks until written. Use for potentially problematic situations that don't prevent operation but should be addressed.

      if (cacheSize > threshold) {
      logger.warn('Cache size exceeding threshold', {
      size: cacheSize,
      threshold
      });
      // Warning guaranteed logged before continuing
      }