npm package: @holix/logger
Description: Universal logger with 3 entry points: basic (for tools), main (Electron main with file logging), renderer (Electron renderer with IPC)
Author: zhaogongchengsi
Latest version: 0.1.0

# @holix/logger

Universal logger for Holix applications with support for Node.js, Browser, and Electron environments.

## Installation

```bash
pnpm add @holix/logger
```

## Features

- 🎨 **Colorful Output**: Beautiful colored console output
- 🏷️ **Tagged Messages**: Organize logs with tags
- ⚡ **Fast**: Built on top of consola
- 🔧 **Flexible**: Multiple log levels and formats
- 📦 **Type-safe**: Full TypeScript support
- 🌐 **Browser Support**: Works in browser environments
- 🖥️ **Electron Ready**: Special utilities for Electron processes

## Usage

### Basic Usage

```typescript
import { logger } from '@holix/logger'

// Different log levels
logger.info('Application started')
logger.success('Build completed successfully')
logger.warn('Configuration file not found')
logger.error('Failed to connect to database')
logger.debug('Debug information')

// Boxed message
logger.box('🚀 Holix Development Server')

// Start/Ready messages
logger.start('Building...')
logger.ready('Server is ready!')
```

### Creating Custom Logger

```typescript
import { createLogger } from '@holix/logger'

const myLogger = createLogger({
  tag: 'my-app',
  level: 3, // 0: silent, 1: error, 2: warn, 3: info, 4: debug, 5: trace
  fancy: true, // Enable colors and formatting
  timestamp: true, // Show timestamps
})

myLogger.info('Custom logger message')
```

### Child Loggers with Tags

```typescript
import { logger } from '@holix/logger'

// Create child logger with a new tag
const builderLogger = logger.withTag('builder')
builderLogger.info('Starting build process')

const routerLogger = logger.withTag('router')
routerLogger.success('Routes registered')
```

### Banner Messages

```typescript
import { banner } from '@holix/logger'

banner('🚀 Welcome to Holix')
```

### Colored Output

```typescript
import { colors } from '@holix/logger'

console.log(colors.red('Error message'))
console.log(colors.green('Success message'))
console.log(colors.yellow('Warning message'))
console.log(colors.blue('Info message'))
console.log(colors.bold('Bold text'))
console.log(colors.dim('Dimmed text'))
```

### Utility Functions

```typescript
import { withTag, withTimestamp } from '@holix/logger'

// Add timestamp to message
console.log(withTimestamp('Server started'))
// Output: [14:30:45] Server started

// Add tag to message
console.log(withTag('api', 'Request received'))
// Output: [api] Request received
```

### Browser Usage

Logger automatically detects browser environment and adjusts output:

```typescript
import { browser, logger } from '@holix/logger'

// Check if running in browser
if (browser.isBrowser()) {
  logger.info('Running in browser')
}

// Create browser-optimized logger
const browserLogger = browser.createBrowserLogger({
  tag: 'app',
  level: 3,
})

browserLogger.info('Application initialized')
browserLogger.warn('Session will expire soon')
```

### Electron Usage

Special loggers for different Electron processes:

```typescript
import { electron } from '@holix/logger'

// In Electron main process (Node.js environment)
const mainLogger = electron.createMainLogger()
mainLogger.info('Main process started')

// In Electron renderer process (Browser environment)
const rendererLogger = electron.createRendererLogger()
rendererLogger.info('Renderer process ready')

// In Electron preload script
const preloadLogger = electron.createPreloadLogger()
preloadLogger.info('Preload script loaded')
```

### Integration Examples

#### In Builder Package

```typescript
import { logger } from '@holix/logger'

const builderLogger = logger.withTag('builder')

export async function build() {
  builderLogger.start('Building application...')
  try {
    // Build logic
    builderLogger.success('Build completed!')
  }
  catch (error) {
    builderLogger.error('Build failed:', error)
  }
}
```

#### In Electron Package

```typescript
import { electron } from '@holix/logger'

const electronLogger = electron.createMainLogger()

app.on('ready', () => {
  electronLogger.ready('Electron app is ready')
})

app.on('window-all-closed', () => {
  electronLogger.info('All windows closed')
})
```

#### In CLI Package

```typescript
import { banner, logger } from '@holix/logger'

export async function runDev() {
  banner('🚀 Starting Holix Dev Server')

  logger.info('Root directory:', process.cwd())
  logger.start('Building...')

  // Build logic

  logger.success('✓ Build completed')
  logger.ready('Dev server ready at http://localhost:5173')
}
```

## API Reference

### `logger`

Default logger instance with tag `'holix'`.

### `createLogger(options?: LoggerOptions): Logger`

Create a new logger instance with custom options.

```typescript
interface LoggerOptions {
  tag?: string // Logger tag/prefix
  level?: LogLevel // Log level (0-5)
  fancy?: boolean // Enable fancy formatting (auto-detected for browser)
  timestamp?: boolean // Enable timestamps
  browser?: boolean // Force browser mode (auto-detected by default)
}
```

### `Logger` Interface

```typescript
interface Logger {
  info: (...args: any[]) => void
  success: (...args: any[]) => void
  warn: (...args: any[]) => void
  error: (...args: any[]) => void
  debug: (...args: any[]) => void
  trace: (...args: any[]) => void
  silent: (...args: any[]) => void
  verbose: (...args: any[]) => void
  start: (...args: any[]) => void
  ready: (...args: any[]) => void
  box: (...args: any[]) => void
  withTag: (tag: string) => Logger
  getConsola: () => ConsolaInstance
}
```

### Log Levels

- `0` - Silent: No logs
- `1` - Error: Only errors
- `2` - Warn: Warnings and errors
- `3` - Info: Info, warnings, and errors (default)
- `4` - Debug: Debug and all above
- `5` - Trace: All logs including trace

### `banner(msg: string): void`

Display a boxed banner message.

### `colors`

Color utilities:
- `red`, `green`, `yellow`, `blue`, `magenta`, `cyan`, `white`, `gray`
- `bold`, `dim`, `underline`

### `withTimestamp(message: string): string`

Format message with current timestamp.

### `withTag(tag: string, message: string): string`

Format message with a tag.

### `electron`

Electron-specific utilities:
- `createMainLogger()` - Logger for Electron main process
- `createRendererLogger()` - Logger for Electron renderer process (browser mode)
- `createPreloadLogger()` - Logger for Electron preload script

### `browser`

Browser-specific utilities:
- `createBrowserLogger(options?)` - Create browser-optimized logger
- `isBrowser()` - Check if running in browser environment

## Environment Detection

The logger automatically detects the environment:

- **Node.js**: Full fancy output with colors and formatting
- **Browser**: Simplified output optimized for browser console
- **Electron Renderer**: Browser mode with custom tags
- **Electron Main/Preload**: Node.js mode with custom tags

You can override the detection by setting the `browser` option:

```typescript
// Force browser mode
const logger = createLogger({ browser: true })

// Force Node.js mode
const logger = createLogger({ browser: false })
```

### `withTag(tag: string, message: string): string`

Format message with a tag prefix.

### `electron`

Electron-specific utilities:
- `createMainLogger()` - Logger for main process
- `createRendererLogger()` - Logger for renderer process
- `createPreloadLogger()` - Logger for preload script

## Environment Variables

You can control log level using `CONSOLA_LEVEL` environment variable:

```bash
CONSOLA_LEVEL=4 pnpm dev  # Enable debug logs
```

## License

MIT