Skip to content

Commit 8c6629e

Browse files
committed
Refactor logging components and remove unused file
- Modified config/logging.php: Updated configuration settings for logging channels and handlers. - Deleted invalidPath: Removed unused or invalid path from the project. - Modified src/Formatter/AbstractFormatter.php: Improved SRP compliance and refactored formatter handling. - Modified src/Handler/LoggerHandlerFactory.php: Refactored factory logic to enhance clarity and maintainability. - Modified src/LogRecord.php: Updated LogRecord to align with new formatter handling. - Modified src/Processor/IntrospectionProcessor.php: Improved semantics and logic for stack trace depth handling. - Modified tests/application.php: Updated tests to reflect changes in logging configuration and processing.
1 parent c036366 commit 8c6629e

File tree

7 files changed

+66
-207
lines changed

7 files changed

+66
-207
lines changed

config/logging.php

Lines changed: 2 additions & 178 deletions
Original file line numberDiff line numberDiff line change
@@ -1,184 +1,8 @@
11
<?php
22

3-
use KaririCode\Logging\Formatter\JsonFormatter;
43
use KaririCode\Logging\LogLevel;
54
use KaririCode\Logging\Util\ConfigHelper;
65

7-
// return [
8-
// 'default' => ConfigHelper::env('LOG_CHANNEL', 'file'),
9-
// 'channels' => [
10-
// 'file' => [
11-
// 'level' => ConfigHelper::env('LOG_LEVEL', 'debug'),
12-
// 'handlers' => ['file'],
13-
// ],
14-
// // 'slack' => [
15-
// // 'level' => ConfigHelper::env('LOG_LEVEL', 'critical'),
16-
// // 'handlers' => ['slack'],
17-
// // ],
18-
19-
// 'console' => [
20-
// 'level' => ConfigHelper::env('LOG_LEVEL', 'debug'),
21-
// 'handlers' => ['console'],
22-
// 'formatter' => ConfigHelper::env('LOG_STDERR_FORMATTER'),
23-
// 'processors' => [
24-
// 'introspection_processor',
25-
// // 'memory_usage_processor',
26-
// // 'execution_time_processor',
27-
// // 'cpu_usage_processor',
28-
// // 'web_processor'
29-
// ],
30-
// ],
31-
32-
// 'syslog' => [
33-
// 'level' => ConfigHelper::env('LOG_LEVEL', 'debug'),
34-
// 'handlers' => ['syslog'],
35-
36-
// ],
37-
38-
// 'custom' => [
39-
// 'handlers' => ['custom'],
40-
// ],
41-
// ],
42-
// 'async' => [
43-
// 'enabled' => ConfigHelper::env('ASYNC_LOG_ENABLED', true),
44-
// 'driver' => \KaririCode\Logging\Decorator\AsyncLogger::class,
45-
// 'batch_size' => 10,
46-
// ],
47-
48-
// 'emergency_logger' => [
49-
// 'path' => ConfigHelper::storagePath('logs/emergency.log'),
50-
// 'level' => LogLevel::EMERGENCY,
51-
// ],
52-
53-
// 'query_logger' => [
54-
// 'enabled' => ConfigHelper::env('QUERY_LOG_ENABLED', false),
55-
// 'channel' => ConfigHelper::env('QUERY_LOG_CHANNEL', 'file'),
56-
// 'threshold' => ConfigHelper::env('QUERY_LOG_THRESHOLD', 100), // in milliseconds
57-
// 'handlers' => ['console', 'file'],
58-
// 'with' => [
59-
// 'filePath' => ConfigHelper::storagePath('logs/query.log'),
60-
// ],
61-
// ],
62-
63-
// 'performance_logger' => [
64-
// 'enabled' => ConfigHelper::env('PERFORMANCE_LOG_ENABLED', false),
65-
// 'channel' => ConfigHelper::env('PERFORMANCE_LOG_CHANNEL', 'file'),
66-
// 'threshold' => ConfigHelper::env('PERFORMANCE_LOG_THRESHOLD', 1000), // in milliseconds
67-
// 'with' => [
68-
// 'filePath' => ConfigHelper::storagePath('logs/performance.log'),
69-
// ],
70-
// 'processors' => [
71-
// 'memory_usage_processor',
72-
// 'cpu_usage_processor',
73-
// 'execution_time_processor',
74-
// ],
75-
// ],
76-
77-
// 'error_logger' => [
78-
// 'enabled' => ConfigHelper::env('ERROR_LOG_ENABLED', true),
79-
// 'channel' => ConfigHelper::env('ERROR_LOG_CHANNEL', 'file'),
80-
// 'levels' => [
81-
// LogLevel::ERROR,
82-
// LogLevel::CRITICAL,
83-
// LogLevel::ALERT,
84-
// LogLevel::EMERGENCY
85-
// ],
86-
// ],
87-
88-
// 'log_cleaner' => [
89-
// 'enabled' => ConfigHelper::env('LOG_CLEANER_ENABLED', true),
90-
// 'keep_days' => ConfigHelper::env('LOG_CLEANER_KEEP_DAYS', 30),
91-
// 'channels' => ['single', 'file'],
92-
// ],
93-
94-
// 'handlers' => [
95-
// 'file' => [
96-
// 'class' => \KaririCode\Logging\Handler\FileHandler::class,
97-
// 'with' => [
98-
// 'filePath' => ConfigHelper::storagePath('logs/file.log'),
99-
// ],
100-
// ],
101-
// 'console' => [
102-
// 'class' => \KaririCode\Logging\Handler\ConsoleHandler::class,
103-
// 'with' => [
104-
// 'minLevel' => LogLevel::DEBUG,
105-
// 'useColors' => true,
106-
// ],
107-
// ],
108-
// // 'slack' => [
109-
// // 'class' => \KaririCode\Logging\Handler\SlackHandler::class,
110-
// // 'with' => [
111-
// // 'slackClient' => new SlackClient(
112-
// // 'webhookUrl' => ConfigHelper::env('LOG_SLACK_WEBHOOK_URL'),
113-
// // CircuitBreaker $circuitBreaker,
114-
// // Retry $retry,
115-
// // Fallback $fallback,
116-
// // CurlClient $curlClient
117-
// // ),
118-
// // LoggingLogLevel $minLevel = LogLevel::CRITICAL,
119-
// // ?LogFormatter $formatter = null
120-
121-
// // 'url' => ,
122-
// // 'username' => 'KaririCode Log',
123-
// // 'emoji' => ':boom:',
124-
// // 'bubble' => true,
125-
// // 'context' => ['from' => 'KaririCode'],
126-
// // 'channels' => ['alerts'],
127-
// // ],
128-
// // ],
129-
// 'syslog' => [
130-
// 'class' => \KaririCode\Logging\Handler\SyslogUdpHandler::class,
131-
// 'with' => [
132-
// 'host' => '',
133-
// 'port' => 0,
134-
// ],
135-
// ],
136-
// 'custom' => [
137-
// 'class' => \KaririCode\Logging\Handler\NullHandler::class,
138-
// ]
139-
// ],
140-
// 'processors' => [
141-
// 'introspection_processor' => [
142-
// 'class' => \KaririCode\Logging\Processor\IntrospectionProcessor::class,
143-
// 'level' => LogLevel::DEBUG,
144-
// ],
145-
// 'memory_usage_processor' => [
146-
// 'class' => \KaririCode\Logging\Processor\Metric\MemoryUsageProcessor::class,
147-
// 'level' => LogLevel::DEBUG,
148-
// ],
149-
// 'execution_time_processor' => [
150-
// 'class' => \KaririCode\Logging\Processor\Metric\ExecutionTimeProcessor::class,
151-
// 'level' => LogLevel::DEBUG,
152-
// ],
153-
// 'cpu_usage_processor' => [
154-
// 'class' => \KaririCode\Logging\Processor\Metric\CpuUsageProcessor::class,
155-
// 'level' => LogLevel::DEBUG,
156-
// ],
157-
// 'metrics_processor' => [
158-
// 'class' => \KaririCode\Logging\Processor\MetricsProcessor::class,
159-
// 'level' => LogLevel::DEBUG,
160-
// ],
161-
// 'web_processor' => [
162-
// 'class' => \KaririCode\Logging\Processor\WebProcessor::class,
163-
// 'level' => LogLevel::INFO,
164-
// ],
165-
// ],
166-
167-
// 'formatters' => [
168-
// 'line' => [
169-
// 'class' => \KaririCode\Logging\Formatter\LineFormatter::class,
170-
// 'format' => "[%datetime%] %channel%.%level_name%: %message% %context% %extra%\n",
171-
// 'date_format' => 'Y-m-d H:i:s',
172-
// ],
173-
// 'json' => [
174-
// 'class' => \KaririCode\Logging\Formatter\JsonFormatter::class,
175-
// 'include_stacktraces' => true,
176-
// ],
177-
// ],
178-
// ];
179-
180-
181-
1826
return [
1837
'default' => ConfigHelper::env('LOG_CHANNEL', 'file'),
1848
'channels' => [
@@ -241,8 +65,8 @@
24165
],
24266
'async' => [
24367
'enabled' => ConfigHelper::env('ASYNC_LOG_ENABLED', true),
244-
'driver' => \KaririCode\Logging\Decorator\AsyncLogger::class,
245-
'batch_size' => 10,
68+
'batch_size' => ConfigHelper::env('ASYNC_LOG_BATCH_SIZE', 10),
69+
'channel' => ConfigHelper::env('ASYNC_LOG_CHANNEL', 'file'),
24670
],
24771
'emergency' => [
24872
'path' => ConfigHelper::storagePath('logs/emergency.log'),

invalidPath

Whitespace-only changes.

src/Formatter/AbstractFormatter.php

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -37,12 +37,11 @@ public function getFormatter(): ImmutableValue
3737
return $this->formatter;
3838
}
3939

40-
// Implement the toArray method required by ImmutableValue interface
4140
public function toArray(): array
4241
{
4342
return [
4443
'dateFormat' => $this->dateFormat,
45-
'formatter' => $this->formatter instanceof ImmutableValue ? $this->formatter->toArray() : (string) $this->formatter,
44+
'formatter' => $this->formatter->toArray() ?? null,
4645
];
4746
}
4847
}

src/Handler/LoggerHandlerFactory.php

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
use KaririCode\Contract\Logging\LogHandler;
88
use KaririCode\Logging\Contract\Logging\LoggerConfigurableFactory;
99
use KaririCode\Logging\LoggerConfiguration;
10+
use KaririCode\Logging\LogLevel;
1011
use KaririCode\Logging\Util\ReflectionFactoryTrait;
1112

1213
class LoggerHandlerFactory implements LoggerConfigurableFactory
@@ -78,7 +79,10 @@ private function createHandler(string $handlerName, array $handlerOptions): LogH
7879
$handlerClass = $this->getClassFromMap($this->handlerMap, $handlerName);
7980
$handlerConfig = $this->getHandlerConfig($handlerName, $handlerOptions);
8081

81-
return $this->createInstance($handlerClass, $handlerConfig);
82+
$channelConfig = $this->config->get("channels.$handlerName", []);
83+
$levelConfig = ['minLevel' => $channelConfig['level'] ?? LogLevel::DEBUG];
84+
85+
return $this->createInstance($handlerClass, $handlerConfig, $levelConfig);
8286
}
8387

8488
private function getHandlerConfig(string $handlerName, array $handlerOptions): array

src/LogRecord.php

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,6 @@ public function __construct(
1414
public readonly string|\Stringable $message,
1515
public readonly array $context = [],
1616
public readonly \DateTimeImmutable $datetime = new \DateTimeImmutable(),
17-
public readonly array $extra = []
1817
) {
1918
}
2019

@@ -25,7 +24,6 @@ public function toArray(): array
2524
'message' => $this->message,
2625
'context' => $this->context,
2726
'datetime' => $this->datetime,
28-
'extra' => $this->extra,
2927
];
3028
}
3129
}

src/Processor/IntrospectionProcessor.php

Lines changed: 56 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -5,39 +5,73 @@
55
namespace KaririCode\Logging\Processor;
66

77
use KaririCode\Contract\ImmutableValue;
8+
use KaririCode\Logging\LogLevel;
89
use KaririCode\Logging\LogRecord;
910

1011
class IntrospectionProcessor extends AbstractProcessor
1112
{
12-
public function __construct(private int $stackDepth = 6)
13+
public function __construct(private readonly int $stackDepth = 6)
1314
{
1415
}
1516

1617
public function process(ImmutableValue $record): ImmutableValue
1718
{
18-
$trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 7);
19-
20-
$context = [];
21-
22-
if (!empty($trace) && isset($trace[$this->stackDepth])) {
23-
$frame = $trace[$this->stackDepth];
24-
if ($this->hasValidContext($frame)) {
25-
$context = array_merge(
26-
$record->context,
27-
$context = [
28-
'file' => $frame['file'],
29-
'line' => $frame['line'],
30-
'class' => $frame['class'],
31-
'function' => $frame['function'],
32-
]
33-
);
34-
}
19+
if ($this->shouldTrack($record->level)) {
20+
$trace = $this->getDebugBacktrace();
21+
$maxDepth = $this->getMaxDepth($trace);
22+
23+
$context = $this->isValidTraceDepth($trace, $maxDepth)
24+
? $this->createContext($trace[$maxDepth], $record->context)
25+
: $record->context;
26+
27+
return new LogRecord(
28+
$record->level,
29+
$record->message,
30+
$context,
31+
$record->datetime
32+
);
3533
}
3634

37-
return new LogRecord(
38-
$record->level,
39-
$record->message,
40-
$context
35+
return $record;
36+
}
37+
38+
private function getDebugBacktrace(): array
39+
{
40+
return debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
41+
}
42+
43+
private function getMaxDepth(array $trace): int
44+
{
45+
return min($this->stackDepth, count($trace) - 1);
46+
}
47+
48+
private function isValidTraceDepth(array $trace, int $depth): bool
49+
{
50+
return isset($trace[$depth]);
51+
}
52+
53+
private function createContext(array $frame, array $originalContext): array
54+
{
55+
return array_merge(
56+
$originalContext,
57+
[
58+
'file' => $frame['file'] ?? null,
59+
'line' => $frame['line'] ?? null,
60+
'class' => $frame['class'] ?? null,
61+
'function' => $frame['function'] ?? null,
62+
]
4163
);
4264
}
65+
66+
private function shouldTrack(LogLevel $level): bool
67+
{
68+
$levelsToTrack = [
69+
LogLevel::ERROR,
70+
LogLevel::CRITICAL,
71+
LogLevel::ALERT,
72+
LogLevel::EMERGENCY,
73+
];
74+
75+
return in_array($level, $levelsToTrack, true);
76+
}
4377
}

tests/application.php

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@
2727
$serviceProvider->register();
2828

2929
$defaultLogger = $loggerRegistry->getLogger('file');
30-
$defaultLogger->debug('This is a debug message', ['context' => 'debug']);
30+
$defaultLogger->debug('This is a debug message');
3131
$defaultLogger->info('This is an info message');
3232
$defaultLogger->notice('This is a notice message', ['context' => 'notice']);
3333
$defaultLogger->warning('This is a warning message', ['context' => 'warning']);
@@ -38,7 +38,7 @@
3838

3939
$asyncLogger = $loggerRegistry->getLogger('async');
4040
if ($asyncLogger) {
41-
for ($i = 0; $i < 2; ++$i) {
41+
for ($i = 0; $i < 3; ++$i) {
4242
$asyncLogger->info("Async log message {$i}", ['context' => "batch {$i}"]);
4343
}
4444
}

0 commit comments

Comments
 (0)