Installation Add the package via Composer:
composer require dayspring-tech/logging-bundle
Publish the config (if needed):
php artisan vendor:publish --provider="DayspringTech\LoggingBundle\LoggingServiceProvider"
Basic Usage
Inject the LoggingContext class into your service/controller:
use DayspringTech\LoggingBundle\LoggingContext;
class UserController extends Controller
{
public function __construct(private LoggingContext $loggingContext) {}
public function store(Request $request)
{
$this->loggingContext->addContext('user_id', auth()->id());
// Logs will now include this context
\Log::info('User created', ['request_data' => $request->all()]);
}
}
Default Context
Check config/logging-bundle.php for predefined context keys (e.g., user_id, request_id).
Request Scoping: Use middleware to auto-add context (e.g., request_id, ip_address):
public function handle(Request $request, Closure $next)
{
$loggingContext->addContext('request_id', $request->header('X-Request-ID'));
return $next($request);
}
Service-Level Context:
class OrderService {
public function __construct(private LoggingContext $loggingContext) {}
public function createOrder(Order $order) {
$this->loggingContext->addContext('order_id', $order->id);
// All logs in this method will include `order_id`
}
}
Conditional Context:
if ($user->isAdmin()) {
$loggingContext->addContext('user_role', 'admin');
}
Temporary Context (scoped to a block):
$loggingContext->pushContext(['scope' => 'temporary']);
try {
// Logs here include `scope: temporary`
} finally {
$loggingContext->popContext();
}
ProcessorInterface to inject context:
$processor = new class implements ProcessorInterface {
public function __invoke(array $record): array {
$record['extra']['context'] = $loggingContext->getAll();
return $record;
}
};
$logger->pushProcessor($processor);
'monolog' => [
'handlers' => [
'stack' => [
'formatter' => \Monolog\Formatter\JsonFormatter::class,
],
],
],
Memory Leaks
$loggingContext->clear(); // Reset after heavy operations
Overhead
Thread Safety
dispatch(function () use ($loggingContext) {
$loggingContext->clear(); // Reset for new job
});
\Log::debug('Current context', ['context' => $loggingContext->getAll()]);
Custom Context Providers Register a service to auto-populate context:
$this->app->bind(ContextProviderInterface::class, function () {
return new class implements ContextProviderInterface {
public function get(): array {
return ['custom_key' => 'value'];
}
};
});
Override Default Keys
Modify config/logging-bundle.php to exclude/include keys:
'default_context' => [
'exclude' => ['password'], // Never log passwords
],
Log Levels
debug, info, error, etc.). Filter selectively if needed:
if (\Log::shouldLog(Logger::DEBUG)) {
$loggingContext->addContext('debug_only', true);
}
How can I help you explore Laravel packages today?