npm package: @letmein_by10/arc-logger
Description: Logging utility for JavaScript/TypeScript
Author: pizle0210
Latest version: 1.0.2

# @letmein_by10/arc-logger

A powerful, flexible TypeScript logging utility designed for both Node.js and browser environments. Features colorized output, multiple log levels, caller information, and environment-aware logging.

## Features

- 🎨 **Colorized Output**: Beautiful colored logs with customizable colors
- 📊 **Multiple Log Levels**: Debug, Info, Warn, Error with level filtering
- 🔍 **Caller Information**: Automatic function and file tracking
- ⏰ **Timestamps**: Configurable timestamp formatting
- 🌐 **Universal**: Works in Node.js and browsers
- 🔧 **Configurable**: Highly customizable logger instances
- 📱 **Environment Aware**: Development/production mode support
- 🎯 **TypeScript First**: Full type safety and IntelliSense support
- 📦 **Zero Dependencies**: Lightweight and fast

## Installation

```bash
npm install @letmein_by10/arc-logger
# or
yarn add @letmein_by10/arc-logger
# or
pnpm add @letmein_by10/arc-logger
```

## Quick Start

```typescript
import { logger, ArcLogger, LogLevel } from '@letmein_by10/arc-logger';

// Use the default logger
logger.info('Hello, world!');
logger.error('Something went wrong!');
logger.success('Task completed successfully!');

// Create a custom logger
const customLogger = new ArcLogger({
  level: LogLevel.DEBUG,
  prefix: '🚀 MyApp',
  enableColors: true
});

customLogger.debug('Debug information');
```

## API Reference

### Default Logger Instance

The package exports a pre-configured logger instance ready to use:

```typescript
import { logger } from '@letmein_by10/arc-logger';

logger.debug('Debug message');    // Gray color
logger.info('Info message');      // Blue color  
logger.success('Success message'); // Green color
logger.warn('Warning message');   // Yellow color
logger.error('Error message');    // Red color
```

### ArcLogger Class

Create custom logger instances with specific configurations:

```typescript
import { ArcLogger, LogLevel } from '@letmein_by10/arc-logger';

const logger = new ArcLogger({
  level: LogLevel.INFO,           // Minimum log level
  enableColors: true,             // Enable colored output
  enableTimestamp: true,          // Include timestamps
  enableCaller: true,             // Include caller info
  prefix: '🚀',                   // Log prefix
  outputStream: 'console',        // Output stream
  fileName: 'app.log'             // File name (if file output)
});
```

### Configuration Options

```typescript
interface LoggerConfig {
  level?: LogLevel;                    // Minimum log level to output
  enableColors?: boolean;              // Enable colored output  
  enableTimestamp?: boolean;           // Include timestamps
  enableCaller?: boolean;              // Include caller information
  prefix?: string;                     // Prefix for all messages
  outputStream?: 'console' | 'file';   // Output destination
  fileName?: string;                   // Log file name
}

enum LogLevel {
  DEBUG = 0,    // Most verbose
  INFO = 1,     // General information  
  WARN = 2,     // Warning messages
  ERROR = 3,    // Error messages
  SILENT = 4    // No output
}
```

## Advanced Features

### Performance Timing

```typescript
import { logger } from '@letmein_by10/arc-logger';

logger.time('api-call');
// ... some async operation
logger.timeEnd('api-call'); // Logs: ⏱️  api-call: 1234.56ms
```

### Grouped Logging

```typescript
logger.group('User Registration Process');
logger.info('Validating user input...');
logger.info('Creating user record...');
logger.success('User registered successfully!');
logger.groupEnd();
```

### Table Logging

```typescript
const users = [
  { id: 1, name: 'John', email: 'john@example.com' },
  { id: 2, name: 'Jane', email: 'jane@example.com' }
];

logger.table(users); // Displays data in table format
```

### Environment-Aware Logging

```typescript
// Only logs in development
logger.dev('This only appears in development mode');

// Only logs in production  
logger.prod('This only appears in production mode');
```

### Child Loggers

Create child loggers with modified configurations:

```typescript
const childLogger = logger.child({
  prefix: '🔧 Database',
  level: LogLevel.DEBUG
});

childLogger.info('Connected to database'); // Uses child config
```

## Examples

### Basic Usage

```typescript
import { logger } from '@letmein_by10/arc-logger';

// Simple logging
logger.info('Application started');
logger.warn('Low memory warning');
logger.error('Database connection failed');

// Logging objects
logger.info({ userId: 123, action: 'login' });

// Success messages
logger.success('User registration completed');
```

### Custom Logger Configuration

```typescript
import { ArcLogger, LogLevel } from '@letmein_by10/arc-logger';

const apiLogger = new ArcLogger({
  level: LogLevel.INFO,
  prefix: '🌐 API',
  enableTimestamp: true,
  enableCaller: true,
  enableColors: true
});

apiLogger.info('API server started on port 3000');
apiLogger.error('Failed to connect to database');
```

### Express.js Middleware Example

```typescript
import express from 'express';
import { ArcLogger, LogLevel } from '@letmein_by10/arc-logger';

const app = express();
const requestLogger = new ArcLogger({
  prefix: '📝 REQUEST',
  level: LogLevel.INFO
});

app.use((req, res, next) => {
  requestLogger.info(`${req.method} ${req.path}`);
  next();
});
```

### React Component Example

```typescript
import React, { useEffect } from 'react';
import { logger } from '@letmein_by10/arc-logger';

const UserProfile: React.FC = () => {
  useEffect(() => {
    logger.info('UserProfile component mounted');
    
    return () => {
      logger.info('UserProfile component unmounted');
    };
  }, []);

  const handleSave = () => {
    try {
      // Save logic here
      logger.success('User profile saved successfully');
    } catch (error) {
      logger.error('Failed to save user profile:', error);
    }
  };

  return <div>User Profile Component</div>;
};
```

## Dynamic Configuration

```typescript
const logger = new ArcLogger();

// Change log level at runtime
logger.setLevel(LogLevel.DEBUG);

// Toggle features
logger.setColors(false);
logger.setTimestamp(true);
logger.setCaller(false);

// Change prefix
logger.setPrefix('🔄 Updated');
```

## Best Practices

1. **Use appropriate log levels**: Debug for development, Info for general information, Warn for potential issues, Error for actual problems.

2. **Structure your log messages**: Include relevant context and make messages searchable.

3. **Use child loggers**: Create specialized loggers for different parts of your application.

4. **Performance-aware logging**: Use `dev()` for debug information that shouldn't appear in production.

## Browser vs Node.js

The logger automatically detects the environment and adapts:

- **Node.js**: Uses ANSI color codes for terminal output
- **Browser**: Uses CSS styling for console output  
- **Caller information**: Works in both environments with proper stack trace parsing

## TypeScript Support

Full TypeScript support with complete type definitions:

```typescript
// Type-safe configuration
const logger = new ArcLogger({
  level: LogLevel.INFO, // ✅ Enum values
  enableColors: true,   // ✅ Boolean
  prefix: '🚀'         // ✅ String
});

// Type inference for messages
logger.info('Hello'); // ✅ Accepts any type
logger.info(42);      // ✅ Accepts any type  
logger.info({ a: 1 }); // ✅ Accepts any type
```

## License

MIT © [pizle0210](mailto:fajobiadedoyin@hotmail.com)