I am using the Monolog LineFormatter as follows:
$output = "[%datetime%] %level_name% %channel%: %message%n";
$stream_handler->setFormatter(new LineFormatter($output));
This results in the following log lines:
[2023-07-03T05:30:31.327443+02:00] DEBUG test: This is a debug message.
[2023-07-03T05:30:31.327555+02:00] INFO test: This is an info level message.
[2023-07-03T05:30:31.327683+02:00] WARNING test: This is a warning level message.
[2023-07-03T05:30:31.327806+02:00] ERROR test: This is an error level message.
How would you set the %level% width (like padding in printf)?
I am trying to get this output:
[2023-07-03T05:30:31.327443+02:00] DEBUG test: This is a debug message.
[2023-07-03T05:30:31.327555+02:00] INFO test: This is an info level message.
[2023-07-03T05:30:31.327683+02:00] WARNING test: This is a warning level message.
[2023-07-03T05:30:31.327806+02:00] ERROR test: This is an error level message.
I tried adding "-10s " to the $output %-10s level_name% but this just added the literal text -10s to the log lines.
Thanks in advance.
2
Answers
I don't understand how to do
Set %level_name%: field width in MonologFormatterLineFormatter (PHP)
The class LineFormatter or its parent NormalizerFormatter does not appear to have a set method.
I am pretty new to PHP. I tried extending LineFormatter but ran into a fatal string error using the new class.
I tried searching for how to add custom formatting to the $output fields, but nothing seemed to fit what I am trying to do.
I did the following hack to pad the level_name. Any detailed suggestions how to this this correctly would be great.
Now I see the expected padding:
Here is the complete test file:
To set the width (padding) for the
%level_name%
placeholder in Monolog’sLineFormatter
, you can use the%-10s
format specifier. However, you need to make sure you pass it as a string to theLineFormatter
constructor.Here’s the modified code to achieve the desired output:
By using
%-10s
, you indicate that%level_name%
should be left-aligned with a width of10
characters. The padding will be added after the log level name to reach the desired width.