Skip to content

Commit f556d3b

Browse files
committed
Initial changes to support actual PSR3 style logging
1 parent a767f39 commit f556d3b

File tree

1 file changed

+67
-0
lines changed

1 file changed

+67
-0
lines changed

classes/CCR/CCRLineFormatter.php

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,26 @@
22

33
namespace CCR;
44

5+
56
use Monolog\Formatter\LineFormatter;
7+
use Monolog\Formatter\NormalizerFormatter;
68

79
class CCRLineFormatter extends LineFormatter
810
{
11+
12+
private NormalizerFormatter $normalizerFormatter;
13+
14+
public function __construct($format = null, $dateFormat = null, $allowInlineLineBreaks = false, $ignoreEmptyContextAndExtra = false)
15+
{
16+
if (!str_contains($format, '%context%')) {
17+
// first strip newlines from the format, then we'll add one at the end.
18+
$format = str_replace(["\n", "\r\n", "\r",], '', $format);
19+
$format = "$format %context%\n";
20+
}
21+
$this->normalizerFormatter = new NormalizerFormatter($dateFormat);
22+
parent::__construct($format, $dateFormat, $allowInlineLineBreaks, $ignoreEmptyContextAndExtra);
23+
}
24+
925
/**
1026
* We've overridden this function so that we can customize the way that arrays of data are displayed from the
1127
* standard `{"key" => "value", ...}` to `(key: value)`
@@ -29,4 +45,55 @@ protected function toJson($data, $ignoreErrors = false): string
2945

3046
return implode(' ', $parts);
3147
}
48+
49+
public function format(array $record)
50+
{
51+
$vars = $this->normalizerFormatter->format($record);
52+
53+
$output = $this->format;
54+
55+
foreach ($vars['extra'] as $var => $val) {
56+
if (false !== strpos($output, '%extra.'.$var.'%')) {
57+
$output = str_replace('%extra.'.$var.'%', $this->stringify($val), $output);
58+
unset($vars['extra'][$var]);
59+
}
60+
}
61+
62+
63+
foreach ($vars['context'] as $var => $val) {
64+
if (false !== strpos($output, '%context.'.$var.'%')) {
65+
$output = str_replace('%context.'.$var.'%', $this->stringify($val), $output);
66+
unset($vars['context'][$var]);
67+
}
68+
}
69+
70+
if ($this->ignoreEmptyContextAndExtra) {
71+
if (empty($vars['context'])) {
72+
unset($vars['context']);
73+
$output = str_replace('%context%', '', $output);
74+
}
75+
76+
if (empty($vars['extra'])) {
77+
unset($vars['extra']);
78+
$output = str_replace('%extra%', '', $output);
79+
}
80+
}
81+
82+
foreach ($vars as $var => $val) {
83+
if (false !== strpos($output, '%'.$var.'%')) {
84+
$output = str_replace('%'.$var.'%', $this->stringify($val), $output);
85+
}
86+
}
87+
88+
if (false !== strpos($output, '%context%')) {
89+
$output = str_replace($output, '%context%', $this->toJson($vars['context']));
90+
}
91+
92+
// remove leftover %extra.xxx% and %context.xxx% if any
93+
if (false !== strpos($output, '%')) {
94+
$output = preg_replace('/%(?:extra|context)\..+?%/', '', $output);
95+
}
96+
97+
return $output;
98+
}
3299
}

0 commit comments

Comments
 (0)