File tree Expand file tree Collapse file tree 1 file changed +23
-0
lines changed
Expand file tree Collapse file tree 1 file changed +23
-0
lines changed Original file line number Diff line number Diff 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\r long\t String"
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.
You can’t perform that action at this time.
0 commit comments