Laravel logger: Difference between revisions
From AWVVO
Jump to navigationJump to search
Created page with "== Custom logger == <syntaxhighlight lang="php" copy line highlight="0"> <?php namespace App\Util; use Illuminate\Support\Facades\Log; class Logger { public static function info(...$args): void { $trace = collect(debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS)) ->first(fn ($t) => isset($t['file']) && str_contains($t['file'], base_path('app'))); $location = $trace ? basename($trace['file']) . ':' . ($trace['line'] ?? '') ...." |
|||
Line 33: | Line 33: | ||
Logger::info('aaa', 123); | Logger::info('aaa', 123); | ||
Logger::info('aaa', 123, true, Carbon::now(), ['a' => 'aaa', 'b' => 123]); | Logger::info('aaa', 123, true, Carbon::now(), ['a' => 'aaa', 'b' => 123]); | ||
// output | |||
// [2025-03-29 16:38:56] local.INFO: [IndexController.php:16 -> info] aaa | |||
// [2025-03-29 16:38:56] local.INFO: [IndexController.php:17 -> info] aaa | 123 | |||
// [2025-03-29 16:38:56] local.INFO: [IndexController.php:18 -> info] aaa | 123 | 1 | "2025-03-29T16:38:56.142370Z" | {"a":"aaa","b":123} | |||
</syntaxhighlight> | </syntaxhighlight> |
Latest revision as of 16:39, 29 March 2025
Custom logger
<?php
namespace App\Util;
use Illuminate\Support\Facades\Log;
class Logger
{
public static function info(...$args): void
{
$trace = collect(debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS))
->first(fn ($t) => isset($t['file']) && str_contains($t['file'], base_path('app')));
$location = $trace
? basename($trace['file']) . ':' . ($trace['line'] ?? '') . ' -> ' . ($trace['function'] ?? '')
: 'unknown location';
$message = collect($args)->map(function ($arg) {
return is_scalar($arg) ? $arg : json_encode($arg);
})->implode(' | ');
Log::info("[$location] $message");
}
}
Examples
Logger::info('aaa');
Logger::info('aaa', 123);
Logger::info('aaa', 123, true, Carbon::now(), ['a' => 'aaa', 'b' => 123]);
// output
// [2025-03-29 16:38:56] local.INFO: [IndexController.php:16 -> info] aaa
// [2025-03-29 16:38:56] local.INFO: [IndexController.php:17 -> info] aaa | 123
// [2025-03-29 16:38:56] local.INFO: [IndexController.php:18 -> info] aaa | 123 | 1 | "2025-03-29T16:38:56.142370Z" | {"a":"aaa","b":123}