CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-wdio--logger

A helper utility for logging of WebdriverIO packages with enhanced features like progress logging and masking patterns for secure logging

Pending
Overview
Eval results
Files

browser.mddocs/

Browser Support

Browser-compatible logger implementation that adapts console methods for consistent API across environments. This provides a simplified logging interface for web applications while maintaining compatibility with the Node.js API.

Capabilities

Browser Logger Factory

Creates a browser-compatible logger that wraps native console methods with component prefixing.

/**
 * Creates a browser-compatible logger using native console methods
 * @param component - Component name used as prefix for all log messages
 * @returns Console object with prefixed logging methods
 */
function getLogger(component: string): Console;

Available Methods: The returned Console object includes all available browser console methods with the component name as prefix:

  • error(message?: any, ...optionalParams: any[]): void
  • warn(message?: any, ...optionalParams: any[]): void
  • info(message?: any, ...optionalParams: any[]): void
  • debug(message?: any, ...optionalParams: any[]): void
  • trace(message?: any, ...optionalParams: any[]): void

Usage Examples:

import logger from '@wdio/logger';

// Create browser logger
const log = logger('MyApp');

// Use standard logging methods
log.info('Application started');           // Output: "MyApp: Application started"
log.warn('This is a warning');            // Output: "MyApp: This is a warning"
log.error('An error occurred');           // Output: "MyApp: An error occurred"
log.debug('Debug information');           // Output: "MyApp: Debug information"

// Multiple loggers with different prefixes
const apiLog = logger('API');
const uiLog = logger('UI');

apiLog.info('Making request to /users');  // Output: "API: Making request to /users"
uiLog.warn('Button click failed');        // Output: "UI: Button click failed"

// Works with objects and multiple arguments
log.info('User data:', { id: 1, name: 'John' });
// Output: "MyApp: User data: {id: 1, name: 'John'}"

Compatibility Methods

No-operation methods that provide API compatibility with the Node.js version but have no effect in the browser environment.

/**
 * No-op method for browser compatibility with Node.js API
 * Does nothing in browser environment
 */
function setLevel(): void;

/**
 * No-op method for browser compatibility with Node.js API
 * Does nothing in browser environment
 */
function setLogLevelsConfig(): void;

/**
 * No-op method for browser compatibility with Node.js API
 * Does nothing in browser environment
 */
function setMaskingPatterns(): void;

/**
 * No-op method for browser compatibility with Node.js API
 * Does nothing in browser environment
 */
function waitForBuffer(): void;

/**
 * No-op method for browser compatibility with Node.js API
 * Does nothing in browser environment
 */
function clearLogger(): void;

Usage Examples:

import logger from '@wdio/logger';

// These methods can be called but have no effect in browser
logger.setLevel('debug');                 // No-op in browser
logger.setLogLevelsConfig({ 'api': 'warn' }); // No-op in browser
logger.setMaskingPatterns('password=([^ ]*)'); // No-op in browser

// This allows the same code to work in both Node.js and browser
const log = logger('universal');

// Configure for Node.js (ignored in browser)
logger.setLevel('debug');
logger.setMaskingPatterns('/token=([^ ]*)/');

// Use logger (works in both environments)
log.info('This works everywhere');

Exported Constants

Browser version exports the same masking constant for API consistency.

/**
 * String constant used to replace masked sensitive data
 * Available for consistency with Node.js API
 */
const SENSITIVE_DATA_REPLACER: "**MASKED**";

Usage Examples:

import { SENSITIVE_DATA_REPLACER } from '@wdio/logger';

// Use in browser-specific masking logic
function safeBrowserLog(message: string) {
  // Simple client-side masking example
  const masked = message.replace(/password=\w+/gi, `password=${SENSITIVE_DATA_REPLACER}`);
  console.log(masked);
}

// Check for masked content
if (logMessage.includes(SENSITIVE_DATA_REPLACER)) {
  console.log('Message contains sensitive data');
}

Browser-Specific Behavior

Console Method Availability

The browser logger only includes console methods that are actually available in the current browser environment:

// Method mapping based on availability
const availableMethods = ['error', 'warn', 'info', 'debug', 'trace', 'silent'];

// Only methods that exist on console are added to the logger
const browserLogger = availableMethods.reduce((acc, method) => {
  if (console[method]) {
    acc[method] = console[method].bind(console, `${component}:`);
  }
  return acc;
}, {});

Differences from Node.js Version

FeatureNode.jsBrowser
Log LevelsFull support with numeric levelsUses browser console levels
File LoggingSupports file output via WDIO_LOG_PATHNot available
Progress LoggingSpecial TTY-aware progress methodNot available
MaskingFull regex-based masking systemNot implemented
ColorizationChalk-based terminal colorsBrowser console styling
ConfigurationFull configuration systemNo-op methods only

Import Handling

The package automatically serves the browser version when imported in a browser environment:

// package.json exports configuration handles this automatically
{
  "exports": {
    ".": {
      "browserSource": "./src/browser.ts",
      "browser": "./build/browser.js",      // <- Used in browser
      "types": "./build/index.d.ts",
      "import": "./build/index.js",         // <- Used in Node.js
      "require": "./build/index.cjs"
    }
  }
}

Usage Examples:

// Same import works in both environments
import logger from '@wdio/logger';

// Environment detection
const isNode = typeof process !== 'undefined' && process.versions?.node;
const isBrowser = typeof window !== 'undefined';

if (isBrowser) {
  // Browser-specific setup
  const browserLog = logger('WebApp');
  browserLog.info('Running in browser environment');
} else if (isNode) {
  // Node.js-specific setup
  const nodeLog = logger('NodeApp');
  logger.setLevel('debug');
  logger.setMaskingPatterns('/password=([^ ]*)/i');
  nodeLog.info('Running in Node.js environment');
}

Universal Usage Patterns

Write code that works in both Node.js and browser environments:

import logger from '@wdio/logger';

class UniversalService {
  private log = logger('UniversalService');

  constructor() {
    // Configuration methods are safe to call (no-op in browser)
    logger.setLevel('debug');
    logger.setMaskingPatterns('/api[_-]?key=([^ ]*)/i');
  }

  async performOperation() {
    this.log.info('Starting operation');
    
    try {
      const result = await this.doWork();
      this.log.info('Operation completed successfully');
      return result;
    } catch (error) {
      this.log.error('Operation failed:', error);
      throw error;
    }
  }

  private async doWork() {
    this.log.debug('Performing work...');
    // Implementation here
  }
}

// Works in both Node.js and browser
const service = new UniversalService();
service.performOperation();

Install with Tessl CLI

npx tessl i tessl/npm-wdio--logger

docs

browser.md

configuration.md

core-logging.md

index.md

masking.md

tile.json