# Audit Logging

Entity Builder provides comprehensive audit logging with a two-tier architecture.

## Two-Tier Architecture

### Session Level (EbLog)

Each apply/rollback/import creates an `EbLog` record:

| Field | Description |
|-------|-------------|
| `label` | Human-readable description |
| `definition_id` | Source definition |
| `action` | apply, rollback, import |
| `status` | pending, success, partial, failed |
| `operation_count` | Total operations |
| `success_count` | Successful operations |
| `failure_count` | Failed operations |
| `started` | Start timestamp |
| `completed` | End timestamp |
| `uid` | User who performed action |

### Operation Level (Watchdog)

Each individual operation is logged to Drupal's watchdog:

- **Label**: Short operation name
- **Details**: Key identifiers
- **JSON Data**: Full operation configuration
- **Messages**: Contextual information

## Viewing Logs

### Via UI

1. Navigate to **Configuration > Development > Entity Builder > Log**
2. Click on a log entry to see details
3. Click **Show** to see individual operations

### Operation Details View

The "Show" page displays operations as collapsible fieldsets:

```
┌─────────────────────────────────────────┐
│ ▼ Create Field: field_body              │
│   Timestamp: 2024-01-15 10:30:00        │
│   Severity: Info                        │
│                                         │
│   ▶ Operation Data                      │
│     {                                   │
│       "operation": "create_field",      │
│       "entity_type": "node",            │
│       "bundle": "article",              │
│       ...                               │
│     }                                   │
└─────────────────────────────────────────┘
```

### Via Drush

```bash
# View recent watchdog entries for Entity Builder
drush watchdog:show --filter=eb

# View with more context
drush watchdog:show --filter=eb --count=50
```

## Log Status

| Status | Meaning |
|--------|---------|
| `pending` | In progress |
| `success` | All operations succeeded |
| `partial` | Some operations failed |
| `failed` | All operations failed |

## What Gets Logged

### Apply Operations

```
[INFO] Apply: my_definition started
[INFO] Create Bundle: Article - Created successfully
[INFO] Create Field: field_body - Created successfully
[INFO] Create Field: field_image - Created successfully
[INFO] Configure Widget: field_body - Configured successfully
[INFO] Apply: my_definition completed (4/4 successful)
```

### Rollback Operations

```
[INFO] Rollback: my_definition started
[INFO] Delete Field: field_image - Deleted
[INFO] Delete Field: field_body - Deleted
[INFO] Delete Bundle: Article - Deleted
[INFO] Rollback: my_definition completed
```

### Import Operations

```
[INFO] Import: definition.yml started
[INFO] Parsed: 2 bundles, 5 fields
[INFO] Saved: my_definition
[INFO] Import: definition.yml completed
```

## Log Retention

By default, logs are kept for 30 days.

### Configure Retention

In **Configuration > Development > Entity Builder > Settings**:

```yaml
eb.settings:
  import_history_retention_days: 30
```

### Manual Cleanup

```bash
# Purge logs older than 30 days (default)
drush php-eval "\Drupal::service('eb.eb_log_manager')->purge();"

# Purge logs older than 7 days
drush php-eval "\Drupal::service('eb.eb_log_manager')->purge(7);"
```

## Debug Mode

Enable debug mode for verbose logging:

**Settings:**
```yaml
eb.settings:
  debug_mode: true
```

**Debug output includes:**

- Dependency resolution steps
- Change detection results
- Validation details
- Operation data before/after

## Querying Logs

### By Definition

```php
$logs = \Drupal::service('eb.eb_log_manager')
    ->getByDefinitionId('my_definition');
```

### By User

```php
$logs = \Drupal::service('eb.eb_log_manager')
    ->loadLogs($account, ['limit' => 50]);
```

### Recent Logs

```php
$logs = \Drupal::service('eb.eb_log_manager')
    ->loadLogs(NULL, [
        'limit' => 20,
        'action' => 'apply',
    ]);
```

## Integration with Watchdog

Entity Builder uses `logger.channel.eb` for watchdog logging:

```php
$this->logger->info('Created field: @field', [
    '@field' => $fieldName,
]);

$this->logger->error('Failed to create field: @message', [
    '@message' => $exception->getMessage(),
]);
```

### Log Severity Levels

| Level | Usage |
|-------|-------|
| `emergency` | System unusable |
| `alert` | Action required immediately |
| `critical` | Critical conditions |
| `error` | Operation failed |
| `warning` | Warning conditions |
| `notice` | Normal but significant |
| `info` | Informational (most operations) |
| `debug` | Debug information |

## Best Practices

1. **Review logs** after major applies
2. **Keep retention** long enough for audits
3. **Enable debug mode** when troubleshooting
4. **Check partial failures** for root cause
5. **Monitor log size** on busy sites
