PHPackages                             tiny-blocks/logger - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Logging &amp; Monitoring](/categories/logging)
4. /
5. tiny-blocks/logger

ActiveLibrary[Logging &amp; Monitoring](/categories/logging)

tiny-blocks/logger
==================

Provides structured logging with support for correlation tracking and configurable sensitive data redaction.

1.2.0(2mo ago)143↓67.9%1MITPHPPHP ^8.5CI passing

Since Feb 21Pushed 2mo agoCompare

[ Source](https://github.com/tiny-blocks/logger)[ Packagist](https://packagist.org/packages/tiny-blocks/logger)[ Docs](https://github.com/tiny-blocks/logger)[ RSS](/packages/tiny-blocks-logger/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (4)Dependencies (12)Versions (8)Used By (1)

Logger
======

[](#logger)

[![License](https://camo.githubusercontent.com/f8df3091bbe1149f398a5369b2c39e896766f9f6efba3477c63e9b4aa940ef14/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4d49542d677265656e)](LICENSE)

- [Overview](#overview)
- [Installation](#installation)
- [How to use](#how-to-use)
    - [Basic logging](#basic-logging)
    - [Correlation tracking](#correlation-tracking)
    - [Sensitive data redaction](#sensitive-data-redaction)
    - [Custom log template](#custom-log-template)
- [License](#license)
- [Contributing](#contributing)

Overview
--------

[](#overview)

Provides structured logging with support for correlation tracking and configurable sensitive data redaction.

Built on top of [PSR-3](https://www.php-fig.org/psr/psr-3), the library can be used anywhere a `LoggerInterface` is expected.

Installation
------------

[](#installation)

```
composer require tiny-blocks/logger
```

How to use
----------

[](#how-to-use)

### Basic logging

[](#basic-logging)

Create a logger with `StructuredLogger::create()` and use the fluent builder to configure it. All PSR-3 log levels are supported: `debug`, `info`, `notice`, `warning`, `error`, `critical`, `alert`, and `emergency`.

```
use TinyBlocks\Logger\StructuredLogger;

$logger = StructuredLogger::create()
    ->withComponent(component: 'order-service')
    ->build();

$logger->info(message: 'order.placed', context: ['orderId' => 42]);
```

Output (default template, written to `STDERR`):

```
2026-02-21T16:00:00+00:00 component=order-service correlation_id= level=INFO key=order.placed data={"orderId":42}

```

### Correlation tracking

[](#correlation-tracking)

A correlation ID can be attached at creation time or derived later using `withContext`. The original instance is never mutated.

#### At creation time

[](#at-creation-time)

```
use TinyBlocks\Logger\LogContext;
use TinyBlocks\Logger\StructuredLogger;

$logger = StructuredLogger::create()
    ->withContext(context: LogContext::from(correlationId: 'req-abc-123'))
    ->withComponent(component: 'payment-service')
    ->build();

$logger->info(message: 'payment.started', context: ['amount' => 100.50]);
```

#### Derived from an existing logger

[](#derived-from-an-existing-logger)

```
use TinyBlocks\Logger\LogContext;
use TinyBlocks\Logger\StructuredLogger;

$logger = StructuredLogger::create()
    ->withComponent(component: 'payment-service')
    ->build();

$contextual = $logger->withContext(context: LogContext::from(correlationId: 'req-abc-123'));

$contextual->info(message: 'payment.started', context: ['amount' => 100.50]);
```

### Sensitive data redaction

[](#sensitive-data-redaction)

Redaction is optional and configurable. Built-in redaction strategies are provided for common sensitive fields. Each strategy accepts multiple field name variations and a configurable masking length.

#### Document redaction

[](#document-redaction)

Masks all characters except the last N (default: 3).

```
use TinyBlocks\Logger\StructuredLogger;
use TinyBlocks\Logger\Redactions\DocumentRedaction;

$logger = StructuredLogger::create()
    ->withComponent(component: 'kyc-service')
    ->withRedactions(DocumentRedaction::default())
    ->build();

$logger->info(message: 'kyc.verified', context: ['document' => '12345678900']);
# document → "********900"
```

With custom fields and visible length:

```
use TinyBlocks\Logger\Redactions\DocumentRedaction;

DocumentRedaction::from(fields: ['cpf', 'cnpj'], visibleSuffixLength: 5);
# cpf "12345678900"     → "******78900"
# cnpj "12345678000199" → "*********00199"
```

#### Email redaction

[](#email-redaction)

Preserves the first N characters of the local part (default: 2) and the full domain.

```
use TinyBlocks\Logger\StructuredLogger;
use TinyBlocks\Logger\Redactions\EmailRedaction;

$logger = StructuredLogger::create()
    ->withComponent(component: 'user-service')
    ->withRedactions(EmailRedaction::default())
    ->build();

$logger->info(message: 'user.registered', context: ['email' => 'john@example.com']);
# email → "jo**@example.com"
```

With custom fields:

```
use TinyBlocks\Logger\Redactions\EmailRedaction;

EmailRedaction::from(fields: ['email', 'contact_email', 'recoveryEmail'], visiblePrefixLength: 2);
```

#### Phone redaction

[](#phone-redaction)

Masks all characters except the last N (default: 4).

```
use TinyBlocks\Logger\StructuredLogger;
use TinyBlocks\Logger\Redactions\PhoneRedaction;

$logger = StructuredLogger::create()
    ->withComponent(component: 'notification-service')
    ->withRedactions(PhoneRedaction::default())
    ->build();

$logger->info(message: 'sms.sent', context: ['phone' => '+5511999887766']);
# phone → "**********7766"
```

With custom fields:

```
use TinyBlocks\Logger\Redactions\PhoneRedaction;

PhoneRedaction::from(fields: ['phone', 'mobile', 'whatsapp'], visibleSuffixLength: 4);
```

#### Password redaction

[](#password-redaction)

Masks the entire value with a fixed-length mask (default: 8 characters). The original value's length is never revealed in the output, preventing information leakage about password size.

```
use TinyBlocks\Logger\StructuredLogger;
use TinyBlocks\Logger\Redactions\PasswordRedaction;

$logger = StructuredLogger::create()
    ->withComponent(component: 'auth-service')
    ->withRedactions(PasswordRedaction::default())
    ->build();

$logger->info(message: 'login.attempt', context: ['password' => 's3cr3t!']);
# password → "********"

$logger->info(message: 'login.attempt', context: ['password' => '123']);
# password → "********" (same mask regardless of length)
```

With custom fields and fixed mask length:

```
use TinyBlocks\Logger\Redactions\PasswordRedaction;

PasswordRedaction::from(fields: ['password', 'secret', 'token'], fixedMaskLength: 12);
# "s3cr3t!"       → "************"
# "ab"            → "************"
# "long_password" → "************"
```

#### Name redaction

[](#name-redaction)

Preserves the first N characters (default: 2) and masks the rest.

```
use TinyBlocks\Logger\StructuredLogger;
use TinyBlocks\Logger\Redactions\NameRedaction;

$logger = StructuredLogger::create()
    ->withComponent(component: 'user-service')
    ->withRedactions(NameRedaction::default())
    ->build();

$logger->info(message: 'user.created', context: ['name' => 'Gustavo']);
# name → "Gu*****"
```

With custom fields and visible length:

```
use TinyBlocks\Logger\Redactions\NameRedaction;

NameRedaction::from(fields: ['name', 'full_name', 'firstName'], visiblePrefixLength: 3);
# "Gustavo"       → "Gus****"
# "Gustavo Freze" → "Gus**********"
# "Maria"         → "Mar**"
```

#### Composing multiple redactions

[](#composing-multiple-redactions)

```
use TinyBlocks\Logger\StructuredLogger;
use TinyBlocks\Logger\Redactions\DocumentRedaction;
use TinyBlocks\Logger\Redactions\EmailRedaction;
use TinyBlocks\Logger\Redactions\NameRedaction;
use TinyBlocks\Logger\Redactions\PasswordRedaction;
use TinyBlocks\Logger\Redactions\PhoneRedaction;

$logger = StructuredLogger::create()
    ->withComponent(component: 'user-service')
    ->withRedactions(
        DocumentRedaction::default(),
        EmailRedaction::default(),
        PhoneRedaction::default(),
        PasswordRedaction::default(),
        NameRedaction::default()
    )
    ->build();

$logger->info(message: 'user.registered', context: [
    'document' => '12345678900',
    'email'    => 'john@example.com',
    'phone'    => '+5511999887766',
    'password' => 's3cr3t!',
    'name'     => 'John',
    'status'   => 'active'
]);
# document → "********900"
# email    → "jo**@example.com"
# phone    → "**********7766"
# password → "*******"
# name     → "Jo**"
# status   → "active" (unchanged)
```

#### Custom redaction

[](#custom-redaction)

Implement the `Redaction` interface to create your own strategy:

```
use TinyBlocks\Logger\Redaction;

final readonly class TokenRedaction implements Redaction
{
    public function redact(array $data): array
    {
        foreach ($data as $key => $value) {
            if (is_array($value)) {
                $data[$key] = $this->redact(data: $value);
                continue;
            }

            if ($key === 'token' && is_string($value)) {
                $data[$key] = '***REDACTED***';
            }
        }

        return $data;
    }
}
```

Then add it to the logger:

```
use TinyBlocks\Logger\StructuredLogger;

$logger = StructuredLogger::create()
    ->withComponent(component: 'auth-service')
    ->withRedactions(new TokenRedaction())
    ->build();

$logger->info(message: 'user.logged_in', context: ['token' => 'abc123']);
# token → "***REDACTED***"
```

### Custom log template

[](#custom-log-template)

The default output template is:

```
%s component=%s correlation_id=%s level=%s key=%s data=%s

```

You can replace it with any `sprintf` compatible template that accepts six string arguments (timestamp, component, correlationId, level, key, data):

```
use TinyBlocks\Logger\StructuredLogger;

$logger = StructuredLogger::create()
    ->withComponent(component: 'custom-service')
    ->withTemplate(template: "[%s] %s | %s | %s | %s | %s\n")
    ->build();

$logger->info(message: 'custom.event', context: ['value' => 42]);
# [2026-02-21T16:00:00+00:00] custom-service |  | INFO | custom.event | {"value":42}
```

License
-------

[](#license)

Logger is licensed under [MIT](LICENSE).

Contributing
------------

[](#contributing)

Please follow the [contributing guidelines](https://github.com/tiny-blocks/tiny-blocks/blob/main/CONTRIBUTING.md) to contribute to the project.

###  Health Score

43

—

FairBetter than 91% of packages

Maintenance84

Actively maintained with recent releases

Popularity12

Limited adoption so far

Community13

Small or concentrated contributor base

Maturity56

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 83.3% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~1 days

Total

4

Last Release

82d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/b00a83241d2af272255f1755bf6aff48e77821c59ef623520176d9e828977241?d=identicon)[gustavofreze](/maintainers/gustavofreze)

---

Top Contributors

[![gustavofreze](https://avatars.githubusercontent.com/u/22873481?v=4)](https://github.com/gustavofreze "gustavofreze (5 commits)")[![dependabot[bot]](https://avatars.githubusercontent.com/in/29110?v=4)](https://github.com/dependabot[bot] "dependabot[bot] (1 commits)")

---

Tags

correlation-idloggerloggingobfuscationpsrpsr-3redactionstructured-loggingtiny-blockspsrpsr-3loggingloggerobfuscationcorrelation-idtiny-blocksredactionstructured-logging

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Code StylePHP\_CodeSniffer

Type Coverage Yes

### Embed Badge

![Health badge](/badges/tiny-blocks-logger/health.svg)

```
[![Health](https://phpackages.com/badges/tiny-blocks-logger/health.svg)](https://phpackages.com/packages/tiny-blocks-logger)
```

###  Alternatives

[analog/analog

Fast, flexible, easy PSR-3-compatible PHP logging package with dozens of handlers.

3451.5M24](/packages/analog-analog)[apix/log

Minimalist, thin and fast PSR-3 compliant (multi-bucket) logger.

511.0M18](/packages/apix-log)[inpsyde/wonolog

Monolog-based logging package for WordPress.

183617.9k7](/packages/inpsyde-wonolog)[markrogoyski/simplelog-php

Powerful PSR-3 logging. So easy, it's simple.

2818.1k4](/packages/markrogoyski-simplelog-php)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
