-1

i have one question concerning the logging module. I actually try to create my own handler and when i'm formatting the strings using "Logging.Formatter()", i have the following problem :

The output should look like this :

[ WARNING ] Someething Not Expected Happened Or Indicative To Prospective Problems !
[  DEBUG  ] Diagnosing Supposes !
[  ERROR  ] Serious Problems !

The levelname should be centered quoted by brackets.

But i didn't worked out, how to do this without breaking the formatation.

My formatting string is :

logging.Formatter( f'[ %(levelname)s ] %(name)s | Method : %(funcName)s | Line : %(lineno)s | MSG : %(message)s' )

If i try to use the usual formatter like [{'WARNING':^9}], it doesn't work :/

Like :

[ "%(levelname)s":^9 ]

I hope you can help me solving this problem.

Best regards

NumeroUnoDE
  • 37
  • 1
  • 8

1 Answers1

1

In order to use center formatting, you need to switch to f-string (aka brace) formatting by specifying the format paramter:

logging.Formatter('[{levelname:^9}] {name} | Method : {funcName} | Line : {lineno} | MSG : {message}', style='{') 
Stef
  • 28,728
  • 2
  • 24
  • 52
  • Thanks Stef, that's exactly what i needed. You example above didn't work, maybe a typo, i don't know. :) Can i ask you a further question please ? I want to define a log handler for debug messages, that first prints the message to the console and afterwards writes it to file. How can i do this ? As soon as i define a 'logging.FileHandler()', a output to console is not possible anymore. – NumeroUnoDE Jul 04 '23 at 13:47
  • 1
    see https://docs.python.org/3/howto/logging-cookbook.html#logging-to-multiple-destinations – Stef Jul 04 '23 at 13:49
  • 1
    sorry, in my comment above, the format string start with an `f` which actually does the formatting, but we need to just define the format - so the leading `f` must be removed, as shown in the answer here. – Stef Jul 04 '23 at 13:51
  • Perfect, thanks a lot :)) – NumeroUnoDE Jul 04 '23 at 13:57
  • Sorry, but i have another questions. I know that if I set the level to e.g. 'logging.DEBUG' it will dump everything up to Critical. But I want to capture exactly only debug messages. Is this possible ? – NumeroUnoDE Jul 04 '23 at 14:18
  • see https://stackoverflow.com/questions/8162419/python-logging-specific-level-only – Stef Jul 04 '23 at 14:39
  • Sorry, but i don't get it :( Adding filters like 'handler1.addFilter(MyFilter(logging.DEBUG))' or using 'IsEnabledFor( )' Hasn't Worked. :( – NumeroUnoDE Jul 04 '23 at 15:03
  • FWIW: This question was also asked [here](https://stackoverflow.com/q/76614890/2648551). – colidyre Jul 04 '23 at 23:19