Skip to content

Commit 7c3c1f4

Browse files
committed
add hint
1 parent ff37eb2 commit 7c3c1f4

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed

docs/8-CODEREVIEW_UTILS.md

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -185,6 +185,29 @@ for value in ["", " "]:
185185
print("FALSE")
186186
```
187187

188+
* For the module `logging`, there is a difference between the `%s` and `%r` in the log message template:
189+
* `%s` uses `str(obj)` ([documentation](https://docs.python.org/3/library/stdtypes.html#str)).
190+
* `%r` uses `repr(obj)` ([documentation](https://docs.python.org/3/library/functions.html#repr)) .
191+
* When applied against a **string** value:
192+
* `%s` renders the string as-is.
193+
* `%r` shows escape characters and quotes, making **invisible characters visible**.
194+
* Therefore `%r` is privilegied to prevent exposure to log forging when a string value need to be logged.
195+
196+
```python
197+
import logging
198+
logging.basicConfig(level=logging.INFO)
199+
text = "My\n\rlong\tString"
200+
logging.info("===> Using %%s: %s", text)
201+
logging.info("===> Using %%r: %r", text)
202+
```
203+
204+
```bash
205+
# Result of the execution of the code above
206+
INFO:root:===> Using %s: My
207+
long String
208+
INFO:root:===> Using %r: 'My\n\rlong\tString'
209+
```
210+
188211
## Automated review using SemGrep
189212

190213
> 💡 This [dedicated toolbox](https://github.com/righettod/toolbox-codescan) can be used.

0 commit comments

Comments
 (0)