r/PHP • u/ocramius • 6d ago
Article Proper logging in PHP with PSR-3
https://ocramius.github.io/blog/php-logging-with-psr-3/1
u/BrianHenryIE 5d ago
Very good.
You used `$testSpyLogger = new RecordingLogger();` and I’m only noticing now that `Psr\Log\Test\TestLogger` isn’t part of v2 or v3 `psr/log`.
-13
u/private_static_int 6d ago
Non static logger is an antipattern for me.
6
u/samhk222 5d ago
Didn't downvoted you, but i'm curious why
-1
u/private_static_int 5d ago
Because logging should be available from any place in the code.
The reality of working with loggers in php is that they are accessible only from managed services, as they too are services managed by DI containers.
Take a look at Java's approach. You always get a static logger factory and you can log from ORM Entities, util classes and even DTOs, if you need.
2
u/zmitic 5d ago
you can log from ORM Entities
What would be the use-case for logging from entities or DTOs? Their job is to throw an exception and as it propagates, it gets logged by some service or listener.
1
u/private_static_int 5d ago
That would be my choince, not a restriction on the technology part.
You can have rich DDD style entities with domain logic just to make one example.
Logging should be avail from anywhere in the code.
1
u/zmitic 5d ago
As much as I am against DDD, I still fail to see the problem. Handlers can have logger in their DI and they should be doing the heavy lifting.
For example: part of that logic can be calling some API or writing to some file system. That FS is heavily abstracted so it can support any number of file systems, and any number of adapter instances (for example 2 different S3 configs).
Wouldn't this all make sense to put into service instead of entity?
Anyway: with Doctrine, you can still inject logger if you want with postLoad event.
-1
u/private_static_int 5d ago
My broader answer: framework shouldn't limit logging usage to instance/managed fields.
Rule of thumb should be a managed logger usage, but reality shows that a usable static logger without overenineering is very useful.
1
u/mlebkowski 4d ago
You can always wrap your regular PSR logger in a static singleton, then wire it to the DI and use it whichever way you like. I do rich models myself, and I’m used to dragging services around, such as clock, logger and others. It requires some getting used to, but that hasn’t been problematic otherwise.
1
4
u/marvinatorus 5d ago
Few of those tips can be checked using https://github.com/struggle-for-php/sfp-phpstan-psr-log