From: Miss Islington (bot) <31488909+miss-islington@users.noreply.github.com> Date: Wed, 9 Jul 2025 08:00:07 +0000 (+0200) Subject: [3.13] gh-94503: Update logging cookbook example with info on addressing log injectio... X-Git-Tag: v3.13.6~113 X-Git-Url: http://git.ipfire.org/gitweb.cgi?a=commitdiff_plain;h=301c89ced83684d854388eec4ef02cff200b7433;p=thirdparty%2FPython%2Fcpython.git [3.13] gh-94503: Update logging cookbook example with info on addressing log injection. (GH-136446) (GH-136450) Co-authored-by: Vinay Sajip Co-authored-by: Stan Ulbrych <89152624+StanFromIreland@users.noreply.github.com> --- diff --git a/Doc/howto/logging-cookbook.rst b/Doc/howto/logging-cookbook.rst index 8ca26e44fe90..c53be94a7400 100644 --- a/Doc/howto/logging-cookbook.rst +++ b/Doc/howto/logging-cookbook.rst @@ -4127,6 +4127,42 @@ The script, when run, prints something like: 2025-07-02 13:54:47,234 DEBUG fool me ... 2025-07-02 13:54:47,234 DEBUG can't get fooled again +If, on the other hand, you are concerned about `log injection +`_, you can use a +formatter which escapes newlines, as per the following example: + +.. code-block:: python + + import logging + + logger = logging.getLogger(__name__) + + class EscapingFormatter(logging.Formatter): + def format(self, record): + s = super().format(record) + return s.replace('\n', r'\n') + + if __name__ == '__main__': + h = logging.StreamHandler() + h.setFormatter(EscapingFormatter('%(asctime)s %(levelname)-9s %(message)s')) + logging.basicConfig(level=logging.DEBUG, handlers = [h]) + logger.debug('Single line') + logger.debug('Multiple lines:\nfool me once ...') + logger.debug('Another single line') + logger.debug('Multiple lines:\n%s', 'fool me ...\ncan\'t get fooled again') + +You can, of course, use whatever escaping scheme makes the most sense for you. +The script, when run, should produce output like this: + +.. code-block:: text + + 2025-07-09 06:47:33,783 DEBUG Single line + 2025-07-09 06:47:33,783 DEBUG Multiple lines:\nfool me once ... + 2025-07-09 06:47:33,783 DEBUG Another single line + 2025-07-09 06:47:33,783 DEBUG Multiple lines:\nfool me ...\ncan't get fooled again + +Escaping behaviour can't be the stdlib default , as it would break backwards +compatibility. .. patterns-to-avoid: