0

I am using the python logging module with a configuration file. It is working but I would like to change the format of the output string. Currently in the config file I have a line

[formatter_fileFormatter]
format=[%(asctime)s] %(levelname)-8s %(name)-12s %(message)s 

which gives me output like this

[2022-12-14 11:21:50,247] INFO my_logger.mod1 This is an info log message from func1

I would like to remove the decimal seconds. How can I do it? Ideally I would like to use the f string method of formatting, which I have read is possible but cannot find an explanation anywhere which explains how.

1 Answer 1

1

To remove the decimal seconds you could try specifying a different time format in the format string for the formatter like shown below. This will use the datefmt parameter to specify the format of the time:

format=[%(asctime)s] %(levelname)-8s %(name)-12s %(message)s
datefmt=%Y-%m-%d %H:%M:%S

If you wish to use the f-string approach you could try something like this:

[formatter_fileFormatter]
class=logging.Formatter
format=f'[{asctime}] {levelname:8} {name:12} {message}'
datefmt=%Y-%m-%d %H:%M:%S

This will create a formatter using the logging.Formatter class and specify an f-string format string.

5
  • Thank you. I have spent ages looking for this :) Commented Dec 14, 2022 at 13:06
  • First suggestion works fine, just tried the f-string and it errors with ValueError: Invalid format 'f'[{asctime}] {levelname:8} {name:12} {message}'' for '%' style is there something else I need to add? Commented Dec 14, 2022 at 13:37
  • Try this: format='[{asctime}] {levelname:8} {name:12} {message}'.format datefmt='%Y-%m-%d %H:%M:%S'
    – Desmanado
    Commented Dec 14, 2022 at 13:42
  • That gives a similar message ValueError: Invalid format ''[{asctime}] {levelname:8} {name:12} {message}'.format datefmt='%Y-%m-%d %H:%M:%S'' for '%' style Commented Dec 14, 2022 at 14:15
  • For those who are getting "Invalid format [...] for '%' style", just add style={ to your logging config file.
    – Tyutyutyu
    Commented Jun 28, 2023 at 22:42

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.