# Smart Logs

A utility package for intelligent logging with debug namespaces, JSON output, log dumping, and color control.

## Types of logs

- **Debug logs** - Instrumented through code, sit inert until `DEBUG` is set. Useful in dev and prod.
- **Runtime user facing logs** - Show to users unless `--silent` is set
- **Programmatic logs** - CLIs can pipe to downstream programs or AI tools via `--json`

## Installation

```bash
npm install @davidwells/smart-log
```

## Usage

### Basic Logging

```javascript
const { _console, log } = require('@davidwells/smart-log')

// Basic logging (respects --silent and --json flags)
_console.log('Hello world')
_console.error('Error message')
_console.warn('Warning')
_console.info('Info')

// Direct functions
log('Hello world')
```

### Debug Namespaces

```javascript
const { debug } = require('@davidwells/smart-log')

const logger = debug('myapp:http')
const dbLogger = debug('myapp:db')

logger('request received')
dbLogger('query executed')

// Enable via flag or env:
// node app.js --debug "myapp:*"
// DEBUG=myapp:* node app.js
```

### JSON Logging

```javascript
const { _console, logJson } = require('@davidwells/smart-log')

const data = { foo: 'bar', baz: 123 }

// Logs JSON only when --json flag is present
_console.json(data, 'Data:')

// Force JSON logging regardless of flags
logJson(data, 'Data:', true)
```

### Console Patching

```javascript
const { patchConsole } = require('@davidwells/smart-log')

// Patch global console to route through smart-log
const restore = patchConsole()

console.log('This goes through smart-log')
console.error('So does this')

// Restore original console
restore()
```

### Runtime Toggling

```javascript
const { setSilent, setJson, setDebug } = require('@davidwells/smart-log')

// Toggle at runtime
setSilent(true)   // Suppress output
setJson(true)     // Enable JSON mode
setDebug('app:*') // Enable debug pattern
```

## Command Line Flags

| Flag | Description |
|------|-------------|
| `--silent` | Suppress all logging output |
| `--json` | Output logs in JSON format to stderr |
| `--debug [pattern]` | Enable scoped debug logging (default: `*`) |
| `--dump [file]` | Dump logs to file, ANSI stripped (default: `_debug.log`) |
| `--out [file]` | Dump logs to file, ANSI preserved (default: `_debug.log`) |
| `--no-color` | Strip ANSI colors from console AND dump output |
| `--clear` | Clear dump file before writing (vs append) |

## Environment Variables

| Variable | Description |
|----------|-------------|
| `SILENT` | Enable silent mode |
| `JSON` | Enable JSON output |
| `DEBUG` | Debug namespace pattern |
| `DUMP` | Dump file path (ANSI stripped) |
| `OUT` | Dump file path (ANSI preserved) |
| `NO_COLOR` | Strip ANSI from all output ([standard](https://no-color.org/)) |
| `CLEAR` | Clear dump file before write |

Flag names can be customized via env vars (e.g., `SILENT_FLAG=--quiet`).

## API

### Console Object

```javascript
const { _console, Console } = require('@davidwells/smart-log')

_console.log(message, ...args)    // Log to stdout (stderr if --json)
_console.error(message, ...args)  // Log error
_console.warn(message, ...args)   // Log warning
_console.info(message, ...args)   // Log info
_console.debug(message, ...args)  // Log debug
_console.trace(message, ...args)  // Log trace
_console.json(data, label, bypass) // Log JSON
```

### Direct Functions

```javascript
const {
  log,           // Same as _console.log
  logError,      // Same as _console.error
  logWarn,       // Same as _console.warn
  logInfo,       // Same as _console.info
  logTrace,      // Same as _console.trace
  logJson,       // Same as _console.json
  logToStdErr,   // Direct stderr write
  logToStdOut,   // Direct stdout write
  deepLog,       // Pretty print objects
  debug,         // Debug namespace factory
} = require('@davidwells/smart-log')
```

### State & Constants

```javascript
const {
  // Flag constants
  SILENT_FLAG,    // '--silent'
  JSON_FLAG,      // '--json'
  DEBUG_FLAG,     // '--debug'
  DUMP_FLAG,      // '--dump'

  // Flag detection
  HAS_SILENT_FLAG,
  HAS_JSON_FLAG,
  HAS_DEBUG_FLAG,
  HAS_DUMP_FLAG,

  // Current state (getters)
  SILENT_ENABLED,
  JSON_ENABLED,
  DEBUG_ENABLED,
  DEBUG_VALUE,
  DUMP_ENABLED,
  DUMP_VALUE,

  // Dump info
  LOG_FILE_PATH,
  logBuffer,
} = require('@davidwells/smart-log')
```

### Runtime Control

```javascript
const { setSilent, setJson, setDebug } = require('@davidwells/smart-log')

setSilent(true)      // Enable/disable silent mode
setJson(true)        // Enable/disable JSON mode
setDebug('app:*')    // Set debug pattern (false to disable)
```

## Log Dumping

Capture all logs to a file for debugging:

```bash
# Dump to file, ANSI stripped (clean text)
node app.js --dump

# Dump to file, ANSI preserved (raw output)
node app.js --out

# Custom file path
node app.js --dump=logs/debug.json
node app.js --out=logs/raw.json

# Clear file each run (vs append)
node app.js --dump --clear
```

Dump file format (JSON lines):
```json
{"__Init":true,"timestamp":"...","cwd":"/path","command":"node app.js --dump"}
{"timestamp":"...","type":"stdout","level":"log","message":"Hello"}
{"timestamp":"...","type":"stderr","level":"debug","message":"debug output"}
```

## License

MIT

## See Also

- [debug-logfmt](https://github.com/Kikobeats/debug-logfmt/) - Structured debug output
- [fast-redact](https://github.com/davidmarkclements/fast-redact) - Redact sensitive data
- [mikrolog](https://github.com/mikaelvesavuori/mikrolog) - Structured logging
- https://github.com/DavidWells/redact-logs
- Defer logs https://www.npmjs.com/package/console-watch