22
33namespace CCR ;
44
5+
56use Monolog \Formatter \LineFormatter ;
7+ use Monolog \Formatter \NormalizerFormatter ;
68
79class 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