python logging config format
Question:
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.
Answers:
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.
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.
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.