# Logging Helper

> Стратегия логирования, форматы, уровни, отладка через логи, поиск edge cases и багов. Триггеры: «добавь логи», «логирование», «trace», «отслеживай баг», «edge case», «найди причину», «почему упало», «что тут произошло», «логирование в продакшене».

- **Type:** Skill
- **Install:** `agentstack add skill-kissrosecicd-hub-agents-evolution-logging-helper`
- **Verified:** Yes — security-reviewed for prompt injection and unsafe behavior
- **Seller:** [kissrosecicd-hub](https://agentstack.voostack.com/s/kissrosecicd-hub)
- **Installs:** 0
- **Category:** [Agent Skills](https://agentstack.voostack.com/c/agent-skills)
- **Latest version:** 0.1.0
- **License:** MIT
- **Upstream author:** [kissrosecicd-hub](https://github.com/kissrosecicd-hub)
- **Source:** https://github.com/kissrosecicd-hub/agents-evolution/tree/main/.agents/skills/logging-helper

## Install

```sh
agentstack add skill-kissrosecicd-hub-agents-evolution-logging-helper
```

Requires the [AgentStack CLI](https://agentstack.voostack.com/docs/cli). Works with Claude Code, Cursor, and any MCP-compatible agent.

## About

# Logging Helper — логирование как инструмент отладки

## Контекст

Логи — первый инструмент отладки, не костыль. Логгируй везде: вход/выход функций, ключевые состояния, ошибки, тайминги, неочевидные ветки. Помогают находить баги и edge cases до того, как пользователь заметит.

## Стратегия

### Что логировать
- Входные параметры функций (валидация)
- Возвращаемые значения (особенно при неочевидных результатах)
- Исключения и стектрейсы
- Переходы между состояниями
- Edge cases (пустые массивы, null, boundary values)
- Тайминги критичных операций (DB queries, API calls, heavy computations)
- Retry-попытки и fallback-ветки

### Уровни логирования
| Уровень | Когда | Пример |
|---------|-------|--------|
| `error` | Критичные сбои, требующие вмешательства | DB connection lost, API timeout |
| `warn` | Подозрительное, но система работает | Deprecated API, cache miss > 50% |
| `info` | Ключевые события бизнес-логики | User logged in, order created |
| `debug` | Детальная трассировка для отладки | Function entry/exit, intermediate values |

### Формат
```
[TIMESTAMP] [LEVEL] [MODULE] message — context: {key: value}
```
- Машина-читаемо (парсится локи)
- Человек-читаемо (понятно без декодера)
- ISO 8601 для timestamp
- JSON для context — удобно для grep/jq

## Алгоритм отладки через логи

1. **Добавь логи** в подозрительные места
2. **Воспроизведи** проблему
3. **Проанализируй** вывод — найди аномалию
4. **Убери лишнее**, оставь ключевые точки контроля
5. Зафиксируй edge case в тесте

## Логирование в продакшене

Логи → Мониторинг → Алерты

- Не надейся на «проверю руками»
- Критичные error-логи → алерт (email, Slack, Telegram)
- Паттерны ошибок → дашборд
- Ротация логой — не забивай диск

## Триггеры

«добавь логи», «логирование», «trace», «отслеживай баг», «edge case», «найди причину», «почему упало», «что тут произошло», «логирование в продакшене»

## Примеры

✅ **Правильно:**
```typescript
async function processOrder(order: Order) {
  log.debug('[ORDER] processing start', { orderId: order.id, items: order.items.length });
  
  try {
    const result = await validateOrder(order);
    if (!result.valid) {
      log.warn('[ORDER] validation failed', { orderId: order.id, reasons: result.errors });
      return { status: 'rejected', errors: result.errors };
    }
    
    log.info('[ORDER] processed successfully', { orderId: order.id });
    return { status: 'ok' };
  } catch (err) {
    log.error('[ORDER] unexpected error', { orderId: order.id, error: err.message, stack: err.stack });
    throw err;
  }
}
```

❌ **Неправильно:**
```typescript
async function processOrder(order: Order) {
  // а что тут случилось? никто не знает
  const result = await validateOrder(order);
  return result; // вернул — и ладно
}
```

❌ **Секреты в логах (НИКОГДА):**
```typescript
log.info('auth', { token: user.token, password: user.password }); // СЕКРЕТЫ!
```

✅ **Маскирование:**
```typescript
log.info('auth attempt', { email: user.email, apiKey: mask(user.apiKey) });
// apiKey: 'sk-****abcd'
```

## Ссылки
- AGENTS.md правило #19

## Source & license

This open-source skill is cataloged on AgentStack and links to its original source — we do not rehost the code.

- **Author:** [kissrosecicd-hub](https://github.com/kissrosecicd-hub)
- **Source:** [kissrosecicd-hub/agents-evolution](https://github.com/kissrosecicd-hub/agents-evolution)
- **License:** MIT

Install and usage instructions live in the source repository linked above.

## Pricing

- **Free** — Free

## Security capabilities

Automated source analysis of v0.1.0 — what this tool can access:

- **Network access:** no
- **Filesystem access:** no
- **Shell / process execution:** no
- **Environment & secrets:** no
- **Dynamic code execution:** no

*"Yes" means the capability is present in the source — more access means more to trust, not that it is unsafe.*


## Versions

- **0.1.0** — security scan: passed — Imported from the upstream source.

## Links

- Listing page: https://agentstack.voostack.com/l/skill-kissrosecicd-hub-agents-evolution-logging-helper
- Seller: https://agentstack.voostack.com/s/kissrosecicd-hub
- Browse the marketplace: https://agentstack.voostack.com/browse

---
Listed on AgentStack — the marketplace for AI agent skills and MCP servers. Every listing is security-reviewed. Creators keep 70%.
