Skip to content

Commit ed23ec4

Browse files
authored
Revert "bpo-34844: logging.Formatter enhancement - Ensure style and format string matches in logging.Formatter (GH-9703)"
This reverts commit 18fb1fb.
1 parent b63845b commit ed23ec4

File tree

6 files changed

+22
-403
lines changed

6 files changed

+22
-403
lines changed

Doc/library/logging.config.rst

Lines changed: 0 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -226,11 +226,6 @@ otherwise, the context is used to determine what to instantiate.
226226
(with defaults of ``None``) and these are used to construct a
227227
:class:`~logging.Formatter` instance.
228228

229-
.. versionchanged:: 3.8
230-
a ``validate`` key (with default of ``True``) can be added into
231-
the ``formatters`` section of the configuring dict, this is to
232-
validate the format.
233-
234229
* *filters* - the corresponding value will be a dict in which each key
235230
is a filter id and each value is a dict describing how to configure
236231
the corresponding Filter instance.

Doc/library/logging.rst

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -544,10 +544,6 @@ The useful mapping keys in a :class:`LogRecord` are given in the section on
544544
.. versionchanged:: 3.2
545545
The *style* parameter was added.
546546

547-
.. versionchanged:: 3.8
548-
The *validate* parameter was added. Incorrect or mismatched style and fmt
549-
will raise a ``ValueError``.
550-
For example: ``logging.Formatter('%(asctime)s - %(message)s', style='{')``.
551547

552548
.. method:: format(record)
553549

Lib/logging/__init__.py

Lines changed: 5 additions & 63 deletions
Original file line numberDiff line numberDiff line change
@@ -23,11 +23,9 @@
2323
To use, simply 'import logging' and log away!
2424
"""
2525

26-
import sys, os, time, io, re, traceback, warnings, weakref, collections.abc
26+
import sys, os, time, io, traceback, warnings, weakref, collections.abc
2727

2828
from string import Template
29-
from string import Formatter as StrFormatter
30-
3129

3230
__all__ = ['BASIC_FORMAT', 'BufferingFormatter', 'CRITICAL', 'DEBUG', 'ERROR',
3331
'FATAL', 'FileHandler', 'Filter', 'Formatter', 'Handler', 'INFO',
@@ -415,71 +413,33 @@ def makeLogRecord(dict):
415413
rv.__dict__.update(dict)
416414
return rv
417415

418-
419416
#---------------------------------------------------------------------------
420417
# Formatter classes and functions
421418
#---------------------------------------------------------------------------
422-
_str_formatter = StrFormatter()
423-
del StrFormatter
424-
425419

426420
class PercentStyle(object):
427421

428422
default_format = '%(message)s'
429423
asctime_format = '%(asctime)s'
430424
asctime_search = '%(asctime)'
431-
validation_pattern = re.compile(r'%\(\w+\)[#0+ -]*(\*|\d+)?(\.(\*|\d+))?[diouxefgcrsa%]', re.I)
432425

433426
def __init__(self, fmt):
434427
self._fmt = fmt or self.default_format
435428

436429
def usesTime(self):
437430
return self._fmt.find(self.asctime_search) >= 0
438431

439-
def validate(self):
440-
"""Validate the input format, ensure it matches the correct style"""
441-
if not self.validation_pattern.search(self._fmt):
442-
raise ValueError("Invalid format '%s' for '%s' style" % (self._fmt, self.default_format[0]))
443-
444-
def _format(self, record):
445-
return self._fmt % record.__dict__
446-
447432
def format(self, record):
448-
try:
449-
return self._format(record)
450-
except KeyError as e:
451-
raise ValueError('Formatting field not found in record: %s' % e)
452-
433+
return self._fmt % record.__dict__
453434

454435
class StrFormatStyle(PercentStyle):
455436
default_format = '{message}'
456437
asctime_format = '{asctime}'
457438
asctime_search = '{asctime'
458439

459-
fmt_spec = re.compile(r'^(.?[<>=^])?[+ -]?#?0?(\d+|{\w+})?[,_]?(\.(\d+|{\w+}))?[bcdefgnosx%]?$', re.I)
460-
field_spec = re.compile(r'^(\d+|\w+)(\.\w+|\[[^]]+\])*$')
461-
462-
def _format(self, record):
440+
def format(self, record):
463441
return self._fmt.format(**record.__dict__)
464442

465-
def validate(self):
466-
"""Validate the input format, ensure it is the correct string formatting style"""
467-
fields = set()
468-
try:
469-
for _, fieldname, spec, conversion in _str_formatter.parse(self._fmt):
470-
if fieldname:
471-
if not self.field_spec.match(fieldname):
472-
raise ValueError('invalid field name/expression: %r' % fieldname)
473-
fields.add(fieldname)
474-
if conversion and conversion not in 'rsa':
475-
raise ValueError('invalid conversion: %r' % conversion)
476-
if spec and not self.fmt_spec.match(spec):
477-
raise ValueError('bad specifier: %r' % spec)
478-
except ValueError as e:
479-
raise ValueError('invalid format: %s' % e)
480-
if not fields:
481-
raise ValueError('invalid format: no fields')
482-
483443

484444
class StringTemplateStyle(PercentStyle):
485445
default_format = '${message}'
@@ -494,24 +454,9 @@ def usesTime(self):
494454
fmt = self._fmt
495455
return fmt.find('$asctime') >= 0 or fmt.find(self.asctime_format) >= 0
496456

497-
def validate(self):
498-
pattern = Template.pattern
499-
fields = set()
500-
for m in pattern.finditer(self._fmt):
501-
d = m.groupdict()
502-
if d['named']:
503-
fields.add(d['named'])
504-
elif d['braced']:
505-
fields.add(d['braced'])
506-
elif m.group(0) == '$':
507-
raise ValueError('invalid format: bare \'$\' not allowed')
508-
if not fields:
509-
raise ValueError('invalid format: no fields')
510-
511-
def _format(self, record):
457+
def format(self, record):
512458
return self._tpl.substitute(**record.__dict__)
513459

514-
515460
BASIC_FORMAT = "%(levelname)s:%(name)s:%(message)s"
516461

517462
_STYLES = {
@@ -565,7 +510,7 @@ class Formatter(object):
565510

566511
converter = time.localtime
567512

568-
def __init__(self, fmt=None, datefmt=None, style='%', validate=True):
513+
def __init__(self, fmt=None, datefmt=None, style='%'):
569514
"""
570515
Initialize the formatter with specified format strings.
571516
@@ -585,9 +530,6 @@ def __init__(self, fmt=None, datefmt=None, style='%', validate=True):
585530
raise ValueError('Style must be one of: %s' % ','.join(
586531
_STYLES.keys()))
587532
self._style = _STYLES[style][0](fmt)
588-
if validate:
589-
self._style.validate()
590-
591533
self._fmt = self._style._fmt
592534
self.datefmt = datefmt
593535

Lib/logging/config.py

Lines changed: 1 addition & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -666,19 +666,11 @@ def configure_formatter(self, config):
666666
dfmt = config.get('datefmt', None)
667667
style = config.get('style', '%')
668668
cname = config.get('class', None)
669-
670669
if not cname:
671670
c = logging.Formatter
672671
else:
673672
c = _resolve(cname)
674-
675-
# A TypeError would be raised if "validate" key is passed in with a formatter callable
676-
# that does not accept "validate" as a parameter
677-
if 'validate' in config: # if user hasn't mentioned it, the default will be fine
678-
result = c(fmt, dfmt, style, config['validate'])
679-
else:
680-
result = c(fmt, dfmt, style)
681-
673+
result = c(fmt, dfmt, style)
682674
return result
683675

684676
def configure_filter(self, config):

0 commit comments

Comments
 (0)