Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Psr3 Message Assertions Laravel Package

fr3d/psr3-message-assertions

PHPUnit helper to assert your application’s PSR-3 log messages follow the Logger spec. Use the included TestLogger as a logger dependency during tests to validate message formatting and context placeholders. Composer-installable, BSD-2-Clause.

View on GitHub
Deep Wiki
Context7

Technical Evaluation

Architecture Fit

  • PSR-3 Compliance Enforcement: The package enforces PSR-3 log message standards (e.g., non-null messages, string type, no exceptions in log context), aligning with Laravel’s logging best practices (PSR-3 compliant by default via Monolog).
  • Test-Driven Validation: Ideal for CI/CD pipelines or pre-commit hooks to catch log message violations early, reducing runtime issues.
  • Minimal Overhead: Lightweight (~100 LOC) with no runtime impact—only active during testing.

Integration Feasibility

  • Laravel Compatibility: Works with any PSR-3 logger (Laravel’s Log:: facade uses Monolog under the hood, which is PSR-3 compliant). No Laravel-specific dependencies.
  • PHPUnit Dependency: Requires PHPUnit for assertions, but Laravel’s testing stack already includes it.
  • Mocking Logger: Replaces the logger dependency in tests with TestLogger, ensuring compliance without modifying production code.

Technical Risk

  • False Positives/Negatives: PSR-3 rules may conflict with custom logging formats (e.g., structured JSON logs). Requires alignment with team conventions.
  • Test Coverage Gap: Only validates messages, not log levels or context structure (e.g., PSR-3 allows arrays in context, but Laravel may enforce stricter rules).
  • Deprecation Risk: Last release in 2020; may need forks or maintenance if PSR-3 evolves.

Key Questions

  1. Logging Standards: Does the team enforce additional rules beyond PSR-3 (e.g., log level usage, context formatting)?
  2. CI/CD Integration: Where should assertions run (unit tests, feature tests, or a dedicated "log compliance" test suite)?
  3. Performance Impact: Will adding this to all test suites slow down CI?
  4. False Positives: Are there legitimate use cases for non-string messages (e.g., debug dumps) that should be excluded?
  5. Maintenance: Is the team willing to monitor for package updates or fork if needed?

Integration Approach

Stack Fit

  • Laravel Ecosystem: Seamlessly integrates with Laravel’s Log:: facade and PHPUnit test suite.
  • Monolog Backend: Works with Laravel’s default Monolog setup without configuration changes.
  • Testing Tools: Compatible with Laravel’s tests/Feature or tests/Unit directories.

Migration Path

  1. Phase 1: Proof of Concept
    • Add to a single test file (e.g., tests/Unit/LoggingTest.php) to validate compliance.
    • Example:
      use Fr3d\Psr3MessageAssertions\PhpUnit\TestLogger;
      
      public function test_log_messages_comply_with_psr3()
      {
          $logger = new TestLogger();
          Log::useTestLogger($logger); // Hypothetical; may require dependency injection.
          Log::error("Non-compliant: " . new stdClass()); // Should fail.
      }
      
  2. Phase 2: CI/CD Enforcement
    • Add to phpunit.xml as a dedicated test suite or pre-commit hook (e.g., via Laravel Pint or custom script).
    • Example phpunit.xml snippet:
      <testsuites>
          <testsuite name="PSR-3 Compliance">
              <directory>./tests/Compliance</directory>
          </testsuite>
      </testsuites>
      
  3. Phase 3: Full Integration
    • Replace logger dependencies in all test classes with TestLogger (requires refactoring).
    • Use Laravel’s service container to bind TestLogger during testing:
      $this->app->bind(\Psr\Log\LoggerInterface::class, function () {
          return new TestLogger();
      });
      

Compatibility

  • Laravel Versions: Compatible with Laravel 5.5+ (PSR-3 support introduced in 5.5).
  • PHP Versions: Requires PHP 7.1+ (PHPUnit 8+ compatibility).
  • Logger Backends: Works with any PSR-3 logger, but may need adjustments for custom handlers.

Sequencing

  1. Dependency Installation:
    composer require --dev fr3d/psr3-message-assertions phpunit/phpunit
    
  2. Test Setup:
    • Create a base test class or trait to inject TestLogger.
    • Example trait:
      use Fr3d\Psr3MessageAssertions\PhpUnit\TestLogger;
      
      trait UsesTestLogger
      {
          protected function getTestLogger(): TestLogger
          {
              return new TestLogger();
          }
      }
      
  3. Incremental Adoption:
    • Start with critical paths (e.g., API controllers, job classes).
    • Gradually migrate remaining tests.

Operational Impact

Maintenance

  • Low Effort: No runtime maintenance; only affects test suites.
  • Dependency Management: Monitor for updates or fork if the package stagnates.
  • Rule Updates: If PSR-3 evolves, may need to extend TestLogger or replace the package.

Support

  • Debugging: Assertion failures provide clear PSR-3 violation details (e.g., "Message must be a string").
  • Onboarding: Document the compliance rules for new developers to avoid common pitfalls (e.g., logging objects directly).
  • Tooling: Integrate with IDE plugins (e.g., PHPStorm) to highlight non-compliant log statements.

Scaling

  • Performance: Negligible impact on production; only active in test environments.
  • Test Suite Growth: May increase test execution time (~5–10% for large suites). Mitigate by running compliance tests in parallel or as a separate phase.
  • Distributed Systems: Useful for microservices to enforce consistent logging standards across teams.

Failure Modes

  • False Rejections: Custom logging formats (e.g., debug dumps) may trigger unnecessary failures. Solution: Whitelist specific test classes or log messages.
  • Test Flakiness: If TestLogger is not properly injected, logs may bypass validation. Solution: Use Laravel’s service container or DI container.
  • Package Abandonment: Risk of unmaintained dependencies. Solution: Fork and maintain internally if needed.

Ramp-Up

  • Developer Training:
    • Add a section to the team’s testing guidelines on PSR-3 compliance.
    • Example:

      "All log messages must be strings. Avoid logging objects directly; use json_encode() or custom formatters."

  • Documentation:
    • Update README.md or CONTRIBUTING.md with logging standards.
    • Example:
      ## Logging Standards
      - Use `Log::error("User {id} failed login", ['id' => $userId])` (string + context).
      - Avoid: `Log::error($exception)` (non-string message).
      
  • Onboarding Checklist:
    • New hires must pass a "logging compliance" test in their first PR.
    • Pair with a senior dev to review log statements in critical paths.
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
emuniq/filament-browser-notifications
syriable/filament-translator
hungnm28/livewire-form
wenprise/eloquent
crudly/encrypted
fadion/bouncy
cuci/prototurk-sdk
gos/pubsub-router-bundle
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui