[issue44884] logging Formatter behavior when using msecs and braces : '{'

francois-xavier callewaert report at bugs.python.org
Wed Aug 11 01:43:18 EDT 2021


New submission from francois-xavier callewaert <fxcallewaert at gmail.com>:

```
>>> import logging
>>> logging.getLogger().handlers[0].setFormatter(logging.Formatter(fmt='{asctime} {message}', style='{'))
>>> logging.error("hello")                                                                                                                                      
2021-08-11 01:04:54,972 hello  
```

Wait. I come from a place where we use '.' as a decimal separator ...


```
>>> logging.getLogger().handlers[0].setFormatter(logging.Formatter(fmt='{asctime}.{msecs:03.0f} {message}', style='{', datefmt="%Y-%m-%d %H:%M:%S"))                                                                                                                                                                          
>>> logging.error("hello")                                                             
2021-08-11 01:06:27.471 hello
```

All very reasonable. I know my date time formatting and my brace formatting so I'm good or am I ...

```
>>> import time, math
>>> for i in range(2500): a= (lambda : (time.sleep(0.0004), (logging.error("Whaaat!") )if math.modf(time.time())[0]>0.9995 else 0))()
... 
2021-08-11 01:26:40.1000 Whaaat!
```

You'll hopefully agree that formatting a msecs as 1000 is plain wrong.
Can I get around this ? the best / simplest, I've found is 

```
>>> logging.Formatter.default_msec_format = "%s.%03d"
>>> logging.getLogger().handlers[0].setFormatter(logging.Formatter(fmt='{asctime} {message}', style='{'))
>>> for i in range(2500): a= (lambda : (time.sleep(0.0004), (logging.error("Now that's ok") )if math.modf(time.time())[0]>0.9995 else 0))()
... 
2021-08-11 01:33:46.999 Now that's ok
```

Having to rely / teach /learn about "Old string formatting" in 2021 is not ideal.
Can you suggest something better ?

or would it be palatable to make a "careful" modification in logging/__init__.py (see below) ?

replace
```
self.msecs = (ct - int(ct)) * 1000
```
by
```
self.msecs = math.floor((ct - int(ct)) * 1000)   #requires importing math
```
or 
```
self.msecs = int((ct - int(ct)) * 1000) + 0.0
```

----------
components: Library (Lib)
messages: 399371
nosy: fxcallewaert
priority: normal
severity: normal
status: open
title: logging Formatter behavior when using msecs and braces : '{'
type: behavior
versions: Python 3.11

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue44884>
_______________________________________


More information about the Python-bugs-list mailing list