create-structured-logger

Generates Structured Logger for PHP 8.4. Creates PSR-3 structured logging setup with Monolog processors, correlation ID propagation, and context middleware. Includes unit tests.

59 stars

Best use case

create-structured-logger is best used when you need a repeatable AI agent workflow instead of a one-off prompt.

Generates Structured Logger for PHP 8.4. Creates PSR-3 structured logging setup with Monolog processors, correlation ID propagation, and context middleware. Includes unit tests.

Teams using create-structured-logger should expect a more consistent output, faster repeated execution, less prompt rewriting.

When to use this skill

  • You want a reusable workflow that can be run more than once with consistent structure.

When not to use this skill

  • You only need a quick one-off answer and do not need a reusable workflow.
  • You cannot install or maintain the underlying files, dependencies, or repository context.

Installation

Claude Code / Cursor / Codex

$curl -o ~/.claude/skills/create-structured-logger/SKILL.md --create-dirs "https://raw.githubusercontent.com/dykyi-roman/awesome-claude-code/main/skills/create-structured-logger/SKILL.md"

Manual Installation

  1. Download SKILL.md from GitHub
  2. Place it in .claude/skills/create-structured-logger/SKILL.md inside your project
  3. Restart your AI agent — it will auto-discover the skill

How create-structured-logger Compares

Feature / Agentcreate-structured-loggerStandard Approach
Platform SupportNot specifiedLimited / Varies
Context Awareness High Baseline
Installation ComplexityUnknownN/A

Frequently Asked Questions

What does this skill do?

Generates Structured Logger for PHP 8.4. Creates PSR-3 structured logging setup with Monolog processors, correlation ID propagation, and context middleware. Includes unit tests.

Where can I find the source code?

You can find the source code on GitHub using the link provided at the top of the page.

SKILL.md Source

# Structured Logger Generator

Creates structured logging infrastructure for observability and request tracing.

## When to Use

| Scenario | Example |
|----------|---------|
| Distributed tracing | Correlate logs across microservices |
| Request debugging | Track full request lifecycle |
| Audit logging | Structured records with context |
| Error investigation | Rich context in error logs |

## Component Characteristics

### CorrelationId
- Value Object wrapping UUIDv4
- Immutable, self-validating
- Propagated via `X-Request-ID` header

### CorrelationIdProcessor
- Monolog processor adding `correlation_id` to every record
- Reads from CorrelationIdHolder thread-local storage
- Zero-config: auto-enriches all log entries

### RequestContextProcessor
- Monolog processor adding request metadata
- Captures method, URI, IP, user-agent
- Enables filtering logs by request attributes

### CorrelationIdMiddleware
- PSR-15 middleware extracting or generating X-Request-ID
- Stores in CorrelationIdHolder for downstream use
- Adds correlation ID to response headers

### CorrelationIdHolder
- Static thread-local storage for correlation ID
- Set once per request, available globally
- Reset after request completes

---

## Generation Process

### Step 1: Generate Core Components

**Path:** `src/Infrastructure/Logging/`

1. `CorrelationId.php` — Value Object with UUID validation
2. `CorrelationIdHolder.php` — Thread-local correlation ID storage

### Step 2: Generate Monolog Processors

**Path:** `src/Infrastructure/Logging/Processor/`

1. `CorrelationIdProcessor.php` — Adds correlation_id to log records
2. `RequestContextProcessor.php` — Adds request context to log records

### Step 3: Generate Middleware

**Path:** `src/Infrastructure/Logging/`

1. `CorrelationIdMiddleware.php` — PSR-15 middleware for correlation ID

### Step 4: Generate Tests

1. `CorrelationIdTest.php` — Value Object tests
2. `CorrelationIdProcessorTest.php` — Processor enrichment tests
3. `CorrelationIdMiddlewareTest.php` — Middleware behavior tests

---

## File Placement

| Component | Path |
|-----------|------|
| Core Classes | `src/Infrastructure/Logging/` |
| Processors | `src/Infrastructure/Logging/Processor/` |
| Unit Tests | `tests/Unit/Infrastructure/Logging/` |

---

## Naming Conventions

| Component | Pattern | Example |
|-----------|---------|---------|
| Value Object | `CorrelationId` | `CorrelationId` |
| Holder | `CorrelationIdHolder` | `CorrelationIdHolder` |
| Processor | `{Context}Processor` | `CorrelationIdProcessor` |
| Middleware | `CorrelationIdMiddleware` | `CorrelationIdMiddleware` |
| Test | `{ClassName}Test` | `CorrelationIdTest` |

---

## Quick Template Reference

### CorrelationId

```php
final readonly class CorrelationId
{
    public function __construct(public string $value)
    {
        // Validates UUID v4 format
    }

    public static function generate(): self;
    public function toString(): string;
}
```

### CorrelationIdProcessor

```php
final readonly class CorrelationIdProcessor
{
    public function __invoke(LogRecord $record): LogRecord;
}
```

### CorrelationIdMiddleware

```php
final readonly class CorrelationIdMiddleware implements MiddlewareInterface
{
    public function process(
        ServerRequestInterface $request,
        RequestHandlerInterface $handler
    ): ResponseInterface;
}
```

---

## Usage Example

```php
// Middleware extracts or generates correlation ID
$middleware = new CorrelationIdMiddleware(headerName: 'X-Request-ID');

// Monolog processor auto-enriches every log entry
$logger->pushProcessor(new CorrelationIdProcessor());
$logger->pushProcessor(new RequestContextProcessor($request));

// Log entry output:
// {"message":"Order created","correlation_id":"550e8400-...","method":"POST","uri":"/orders"}
```

---

## Log Flow

```
Request ──→ CorrelationIdMiddleware
                │
         Extract/Generate X-Request-ID
                │
         Store in CorrelationIdHolder
                │
         CorrelationIdProcessor ──→ Adds correlation_id to every log
         RequestContextProcessor ──→ Adds method, URI, IP to every log
                │
         Response ──→ Add X-Request-ID header
```

---

## Anti-patterns to Avoid

| Anti-pattern | Problem | Solution |
|--------------|---------|----------|
| Manual correlation IDs | Inconsistent, easy to forget | Auto-enrich via processor |
| Unstructured logs | Cannot query or filter | Use structured JSON format |
| No request context | Cannot trace request flow | Add request processor |
| Global mutable logger | Thread safety issues | Use holder with request scope |
| Missing response header | Client cannot correlate | Return X-Request-ID in response |
| No holder cleanup | Memory leak between requests | Reset holder after request |

---

## References

For complete PHP templates and examples, see:
- `references/templates.md` — CorrelationId, Processors, Middleware, Holder templates
- `references/examples.md` — Service integration examples and tests

Related Skills

create-visitor

59
from dykyi-roman/awesome-claude-code

Generates Visitor pattern for PHP 8.4. Creates operations on object structures without modifying element classes, with visitor interface, concrete visitors, and visitable elements. Includes unit tests.

create-value-object

59
from dykyi-roman/awesome-claude-code

Generates DDD Value Objects for PHP 8.4. Creates immutable, self-validating objects with equality comparison. Includes unit tests.

create-use-case

59
from dykyi-roman/awesome-claude-code

Generates Application Use Cases for PHP 8.4. Creates orchestration services that coordinate domain objects, handle transactions, and dispatch events. Includes unit tests.

create-unit-test

59
from dykyi-roman/awesome-claude-code

Generates PHPUnit unit tests for PHP 8.4. Creates isolated tests with AAA pattern, proper naming, attributes, and one behavior per test. Supports Value Objects, Entities, Services.

create-unit-of-work

59
from dykyi-roman/awesome-claude-code

Generates Unit of Work pattern components for PHP 8.4. Creates transactional consistency infrastructure with aggregate tracking, flush/rollback, domain event collection, and unit tests.

create-timeout

59
from dykyi-roman/awesome-claude-code

Generates Timeout pattern components for PHP 8.4. Creates execution time limit infrastructure with configurable timeouts, fallback support, stream timeouts, and unit tests.

create-test-double

59
from dykyi-roman/awesome-claude-code

Generates test doubles (Mocks, Stubs, Fakes, Spies) for PHP 8.4. Creates appropriate double type based on testing needs with PHPUnit MockBuilder patterns.

create-test-builder

59
from dykyi-roman/awesome-claude-code

Generates Test Data Builder and Object Mother patterns for PHP 8.4. Creates fluent builders with sensible defaults and factory methods for test data creation.

create-template-method

59
from dykyi-roman/awesome-claude-code

Generates Template Method pattern for PHP 8.4. Creates abstract algorithm skeleton with customizable steps, allowing subclasses to override specific parts without changing structure. Includes unit tests.

create-strategy

59
from dykyi-roman/awesome-claude-code

Generates Strategy pattern for PHP 8.4. Creates interchangeable algorithm families with context class, strategy interface, and concrete implementations. Includes unit tests.

create-state

59
from dykyi-roman/awesome-claude-code

Generates State pattern for PHP 8.4. Creates state machines with context, state interface, and concrete states for behavior changes. Includes unit tests.

create-specification

59
from dykyi-roman/awesome-claude-code

Generates DDD Specification for PHP 8.4. Creates reusable business rule objects for validation, filtering, and querying with composite pattern support. Includes unit tests.