pax_global_header00006660000000000000000000000064146006235750014522gustar00rootroot0000000000000052 comment=663065643e6f0d5347ab80744664ec7d221c0fec python-pythonjsonlogger-3.0.0/000077500000000000000000000000001460062357500164545ustar00rootroot00000000000000python-pythonjsonlogger-3.0.0/.github/000077500000000000000000000000001460062357500200145ustar00rootroot00000000000000python-pythonjsonlogger-3.0.0/.github/workflows/000077500000000000000000000000001460062357500220515ustar00rootroot00000000000000python-pythonjsonlogger-3.0.0/.github/workflows/test-suite.yml000066400000000000000000000024231460062357500247030ustar00rootroot00000000000000name: Test python-json-logger on: push: branches: - main pull_request: branches: - main jobs: lint: name: "Python Lint" runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: actions/setup-python@v5 with: python-version: "3.12" - name: Install dependencies run: | python -m pip install --upgrade pip pip install tox - name: Lint with tox run: tox -e lint test: name: "Python Test ${{matrix.python-version}} ${{ matrix.os }}" needs: [lint] runs-on: "${{ matrix.os }}" strategy: matrix: python-version: - "pypy-3.7" - "pypy-3.8" - "pypy-3.9" - "pypy-3.10" - "3.7" - "3.8" - "3.9" - "3.10" - "3.11" - "3.12" os: - ubuntu-latest - windows-latest - macos-latest steps: - uses: actions/checkout@v4 - uses: actions/setup-python@v5 with: python-version: ${{ matrix.python-version }} - name: Install dependencies run: | python -m pip install --upgrade pip pip install tox tox-gh-actions - name: Test with tox run: tox python-pythonjsonlogger-3.0.0/.gitignore000066400000000000000000000002011460062357500204350ustar00rootroot00000000000000*.pyc *.swp build dist *.egg-info # Tests and validation .tox/ .mypy_cache # Python's venv .env .venv env # IDE .vscode .idea python-pythonjsonlogger-3.0.0/CHANGELOG.md000066400000000000000000000061311460062357500202660ustar00rootroot00000000000000# Changelog All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). ## [2.0.7] - 2023-02-21 ### Changed - Fix inclusion of py.typed in pip packages - @sth - Added pytest support with test file rename. Migrated to assertEqual ## [2.0.6] - 2023-02-14 ### Changed - Parameter `rename_fields` in merge_record_extra is now optional - @afallou ## [2.0.5] - 2023-02-12 ### Added - Allow reserved attrs to be renamed - @henkhogan - Support added for Python 3.11 - Now verifying builds in Pypy 3.9 as well - Type annotations are now in the package - @louis-jaris ### Changed - Fix rename_fields for exc_info - @guilhermeferrari - Cleaned up test file for PEP8 - @lopagela - Cleaned up old Python 2 artifacts - @louis-jaris - Dropped Python 3.5 support - @idomozes - Moved type check via tox into 3.11 run only - Added test run in Python3.6 (will keep for a little while longer, but it's EOL so upgrade) ## [2.0.4] - 2022-07-11 ### Changed - Fix too strict regex for percentage style logging - @aberres - ## [2.0.3] - 2022-07-08 ### Added - Add PEP 561 marker/basic mypy configuration. - @bringhurst - Workaround logging.LogRecord.msg type of string. - @bringhurst ### Changed - Changed a link archive of the reference page in case it's down. - @ahonnecke - Removed unnecessary try-except around OrderedDict usage - @sozofaan - Update documentation link to json module + use https - @deronnax - Dropped 3.5 support. - @bringhurst ## [2.0.2] - 2021-07-27 ### Added - Officially supporting 3.9 - @felixonmars. - You can now add static fields to log objects - @cosimomeli. ### Changed - Dropped 3.4 support. - Dropped Travis CI for Github Actions. - Wheel should build for python 3 instead of just 3.4 now. ## [2.0.1] - 2020-10-12 ### Added - Support Pypi long descripton - @ereli-cb ### Changed - You can now rename output fields - @schlitzered ## [2.0.0] - 2020-09-26 ### Added - New Changelog - Added timezone support to timestamps - @lalten - Refactored log record to function - @georgysavva - Add python 3.8 support - @tommilligan ### Removed - Support for Python 2.7 - Debian directory ## [0.1.11] - 2019-03-29 ### Added - Support for Python 3.7 ### Changed - 'stack_info' flag in logging calls is now respected in JsonFormatter by [@ghShu](https://github.com/ghShu) [2.0.7]: https://github.com/madzak/python-json-logger/compare/v2.0.6...v2.0.7 [2.0.6]: https://github.com/madzak/python-json-logger/compare/v2.0.5...v2.0.6 [2.0.5]: https://github.com/madzak/python-json-logger/compare/v2.0.4...v2.0.5 [2.0.4]: https://github.com/madzak/python-json-logger/compare/v2.0.3...v2.0.4 [2.0.3]: https://github.com/madzak/python-json-logger/compare/v2.0.2...v2.0.3 [2.0.2]: https://github.com/madzak/python-json-logger/compare/v2.0.1...v2.0.2 [2.0.1]: https://github.com/madzak/python-json-logger/compare/v2.0.0...v2.0.1 [2.0.0]: https://github.com/madzak/python-json-logger/compare/v0.1.11...v2.0.0 [0.1.11]: https://github.com/madzak/python-json-logger/compare/v0.1.10...v0.1.11 python-pythonjsonlogger-3.0.0/LICENSE000066400000000000000000000024611460062357500174640ustar00rootroot00000000000000Copyright (c) 2011, Zakaria Zajac and the python-json-logger Contributors All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. python-pythonjsonlogger-3.0.0/MANIFEST.in000066400000000000000000000000771460062357500202160ustar00rootroot00000000000000include LICENSE include README.md recursive-include tests *.py python-pythonjsonlogger-3.0.0/README.md000066400000000000000000000141061460062357500177350ustar00rootroot00000000000000![Build Status](https://github.com/nhairs/python-json-logger/actions/workflows/test-suite.yml/badge.svg) [![License](https://img.shields.io/pypi/l/python-json-logger.svg)](https://pypi.python.org/pypi/python-json-logger/) [![Version](https://img.shields.io/pypi/v/python-json-logger.svg)](https://pypi.python.org/pypi/python-json-logger/) # Python JSON Logger This library is provided to allow standard python logging to output log data as json objects. With JSON we can make our logs more readable by machines and we can stop writing custom parsers for syslog type records. ### 🚨 Important 🚨 This repository is a maintained fork of [madzak/python-json-logger](https://github.com/madzak/python-json-logger) pending [a PEP 541 request](https://github.com/pypi/support/issues/3607) for the PyPI package. The future direction of the project is being discussed [here](https://github.com/nhairs/python-json-logger/issues/1). ## Installation ### Install via pip / PyPI Until the PEP 541 request is complete you will need to use one of the alternative methods below. ### Install from GitHub ```shell pip install 'python-json-logger@git+https://github.com/nhairs/python-json-logger.git' ``` To install a specific version: ```shell pip install 'python-json-logger@git+https://github.com/nhairs/python-json-logger.git@v2.0.7' ``` ### Install from Source ```shell git clone https://github.com/nhairs/python-json-logger.git cd python-json-logger pip install -e . ``` ## Usage ### Integrating with Python's logging framework Json outputs are provided by the JsonFormatter logging formatter. You can add the custom formatter like below: **Please note: version 0.1.0 has changed the import structure, please update to the following example for proper importing** ```python import logging from pythonjsonlogger import jsonlogger logger = logging.getLogger() logHandler = logging.StreamHandler() formatter = jsonlogger.JsonFormatter() logHandler.setFormatter(formatter) logger.addHandler(logHandler) ``` ### Customizing fields The fmt parser can also be overidden if you want to have required fields that differ from the default of just `message`. These two invocations are equivalent: ```python class CustomJsonFormatter(jsonlogger.JsonFormatter): def parse(self): return self._fmt.split(';') formatter = CustomJsonFormatter('one;two') # is equivalent to: formatter = jsonlogger.JsonFormatter('%(one)s %(two)s') ``` You can also add extra fields to your json output by specifying a dict in place of message, as well as by specifying an `extra={}` argument. Contents of these dictionaries will be added at the root level of the entry and may override basic fields. You can also use the `add_fields` method to add to or generally normalize the set of default set of fields, it is called for every log event. For example, to unify default fields with those provided by [structlog](http://www.structlog.org/) you could do something like this: ```python class CustomJsonFormatter(jsonlogger.JsonFormatter): def add_fields(self, log_record, record, message_dict): super(CustomJsonFormatter, self).add_fields(log_record, record, message_dict) if not log_record.get('timestamp'): # this doesn't use record.created, so it is slightly off now = datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%S.%fZ') log_record['timestamp'] = now if log_record.get('level'): log_record['level'] = log_record['level'].upper() else: log_record['level'] = record.levelname formatter = CustomJsonFormatter('%(timestamp)s %(level)s %(name)s %(message)s') ``` Items added to the log record will be included in *every* log message, no matter what the format requires. ### Adding custom object serialization For custom handling of object serialization you can specify default json object translator or provide a custom encoder ```python def json_translate(obj): if isinstance(obj, MyClass): return {"special": obj.special} formatter = jsonlogger.JsonFormatter(json_default=json_translate, json_encoder=json.JSONEncoder) logHandler.setFormatter(formatter) logger.info({"special": "value", "run": 12}) logger.info("classic message", extra={"special": "value", "run": 12}) ``` ### Using a Config File To use the module with a config file using the [`fileConfig` function](https://docs.python.org/3/library/logging.config.html#logging.config.fileConfig), use the class `pythonjsonlogger.jsonlogger.JsonFormatter`. Here is a sample config file. ```ini [loggers] keys = root,custom [logger_root] handlers = [logger_custom] level = INFO handlers = custom qualname = custom [handlers] keys = custom [handler_custom] class = StreamHandler level = INFO formatter = json args = (sys.stdout,) [formatters] keys = json [formatter_json] format = %(message)s class = pythonjsonlogger.jsonlogger.JsonFormatter ``` ## Example Output Sample JSON with a full formatter (basically the log message from the unit test). Every log message will appear on 1 line like a typical logger. ```json { "threadName": "MainThread", "name": "root", "thread": 140735202359648, "created": 1336281068.506248, "process": 41937, "processName": "MainProcess", "relativeCreated": 9.100914001464844, "module": "tests", "funcName": "testFormatKeys", "levelno": 20, "msecs": 506.24799728393555, "pathname": "tests/tests.py", "lineno": 60, "asctime": ["12-05-05 22:11:08,506248"], "message": "testing logging format", "filename": "tests.py", "levelname": "INFO", "special": "value", "run": 12 } ``` ## License This project is licensed under the BSD 2 Clause License - see [`LICENSE`](https://github.com/nhairs/python-json-logger/blob/main/LICENSE) ## Authors and Maintainers This project was originally authored by [Zakaria Zajac](https://github.com/madzak) and our wonderful [contributors](https://github.com/nhairs/python-json-logger/graphs/contributors) It is currently maintained by: - [Nicholas Hairs](https://github.com/nhairs) - [nicholashairs.com](https://www.nicholashairs.com) python-pythonjsonlogger-3.0.0/SECURITY.md000066400000000000000000000004061460062357500202450ustar00rootroot00000000000000# Security Policy ## Supported Versions **TLDR**: Security support is provided for Python versions `>=3.7`. ## Reporting a Vulnerability Please report vulnerabilties using GitHub [here](https://github.com/nhairs/python-json-logger/security/advisories/new). python-pythonjsonlogger-3.0.0/mypy.ini000066400000000000000000000000661460062357500201550ustar00rootroot00000000000000[mypy] [mypy-orjson.*] ignore_missing_imports = True python-pythonjsonlogger-3.0.0/pylintrc000066400000000000000000000373211460062357500202510ustar00rootroot00000000000000[MASTER] # A comma-separated list of package or module names from where C extensions may # be loaded. Extensions are loading into the active Python interpreter and may # run arbitrary code. extension-pkg-whitelist= # Add files or directories to the blacklist. They should be base names, not # paths. ignore=CVS # Add files or directories matching the regex patterns to the blacklist. The # regex matches against base names, not paths. ignore-patterns= # Python code to execute, usually for sys.path manipulation such as # pygtk.require(). #init-hook= # Use multiple processes to speed up Pylint. Specifying 0 will auto-detect the # number of processors available to use. jobs=0 # Control the amount of potential inferred values when inferring a single # object. This can help the performance when dealing with large functions or # complex, nested conditions. limit-inference-results=100 # List of plugins (as comma separated values of python module names) to load, # usually to register additional checkers. load-plugins= # Pickle collected data for later comparisons. persistent=yes # Specify a configuration file. #rcfile= # When enabled, pylint would attempt to guess common misconfiguration and emit # user-friendly hints instead of false-positive error messages. suggestion-mode=yes # Allow loading of arbitrary C extensions. Extensions are imported into the # active Python interpreter and may run arbitrary code. unsafe-load-any-extension=no [MESSAGES CONTROL] # Only show warnings with the listed confidence levels. Leave empty to show # all. Valid levels: HIGH, INFERENCE, INFERENCE_FAILURE, UNDEFINED. confidence= # Disable the message, report, category or checker with the given id(s). You # can either give multiple identifiers separated by comma (,) or put this # option multiple times (only on the command line, not in the configuration # file where it should appear only once). You can also use "--disable=all" to # disable everything first and then reenable specific checks. For example, if # you want to run only the similarities checker, you can use "--disable=all # --enable=similarities". If you want to run only the classes checker, but have # no Warning level messages displayed, use "--disable=all --enable=classes # --disable=W". disable=raw-checker-failed, bad-inline-option, locally-disabled, file-ignored, suppressed-message, useless-suppression, deprecated-pragma, use-symbolic-message-instead, ## General Changes # Explicit is better than implicit so allow bare returns useless-return, # pylint and black sometimes disagree - we always prefer black in these # cases. Disable rules that can cause conflicts line-too-long, # Module docstrings are not required missing-module-docstring ## Project Disables # Enable the message, report, category or checker with the given id(s). You can # either give multiple identifier separated by comma (,) or put this option # multiple time (only on the command line, not in the configuration file where # it should appear only once). See also the "--disable" option for examples. enable=c-extension-no-member [REPORTS] # Python expression which should return a score less than or equal to 10. You # have access to the variables 'error', 'warning', 'refactor', and 'convention' # which contain the number of messages in each category, as well as 'statement' # which is the total number of statements analyzed. This score is used by the # global evaluation report (RP0004). evaluation=10.0 - ((float(5 * error + warning + refactor + convention) / statement) * 10) # Template used to display messages. This is a python new-style format string # used to format the message information. See doc for all details. #msg-template= # Set the output format. Available formats are text, parseable, colorized, json # and msvs (visual studio). You can also give a reporter class, e.g. # mypackage.mymodule.MyReporterClass. output-format=text # Tells whether to display a full report or only the messages. reports=no # Activate the evaluation score. score=yes [REFACTORING] # Maximum number of nested blocks for function / method body max-nested-blocks=5 # Complete name of functions that never returns. When checking for # inconsistent-return-statements if a never returning function is called then # it will be considered as an explicit return statement and no message will be # printed. never-returning-functions=sys.exit [LOGGING] # Format style used to check logging format string. `old` means using % # formatting, `new` is for `{}` formatting,and `fstr` is for f-strings. logging-format-style=old # Logging modules to check that the string format arguments are in logging # function parameter format. logging-modules=logging [VARIABLES] # List of additional names supposed to be defined in builtins. Remember that # you should avoid defining new builtins when possible. additional-builtins= # Tells whether unused global variables should be treated as a violation. allow-global-unused-variables=yes # List of strings which can identify a callback function by name. A callback # name must start or end with one of those strings. callbacks=cb_, _cb # A regular expression matching the name of dummy variables (i.e. expected to # not be used). dummy-variables-rgx=_+$|(_[a-zA-Z0-9_]*[a-zA-Z0-9]+?$)|dummy|^ignored_|^unused_ # Argument names that match this expression will be ignored. Default to name # with leading underscore. ignored-argument-names=_.*|^ignored_|^unused_ # Tells whether we should check for unused import in __init__ files. init-import=no # List of qualified module names which can have objects that can redefine # builtins. redefining-builtins-modules=six.moves,past.builtins,future.builtins,builtins,io [BASIC] # Naming style matching correct argument names. argument-naming-style=snake_case # Regular expression matching correct argument names. Overrides argument- # naming-style. #argument-rgx= # Naming style matching correct attribute names. attr-naming-style=snake_case # Regular expression matching correct attribute names. Overrides attr-naming- # style. #attr-rgx= # Bad variable names which should always be refused, separated by a comma. bad-names=foo, bar, baz, toto, tutu, tata # Naming style matching correct class attribute names. class-attribute-naming-style=any # Regular expression matching correct class attribute names. Overrides class- # attribute-naming-style. #class-attribute-rgx= # Naming style matching correct class names. class-naming-style=PascalCase # Regular expression matching correct class names. Overrides class-naming- # style. #class-rgx= # Naming style matching correct constant names. const-naming-style=UPPER_CASE # Regular expression matching correct constant names. Overrides const-naming- # style. #const-rgx= # Minimum line length for functions/classes that require docstrings, shorter # ones are exempt. docstring-min-length=-1 # Naming style matching correct function names. function-naming-style=snake_case # Regular expression matching correct function names. Overrides function- # naming-style. #function-rgx= # Good variable names which should always be accepted, separated by a comma. good-names=i, j, k, ex, Run, _, e, r, id, f, # Include a hint for the correct naming format with invalid-name. include-naming-hint=no # Naming style matching correct inline iteration names. inlinevar-naming-style=any # Regular expression matching correct inline iteration names. Overrides # inlinevar-naming-style. #inlinevar-rgx= # Naming style matching correct method names. method-naming-style=snake_case # Regular expression matching correct method names. Overrides method-naming- # style. #method-rgx= # Naming style matching correct module names. module-naming-style=snake_case # Regular expression matching correct module names. Overrides module-naming- # style. #module-rgx= # Colon-delimited sets of names that determine each other's naming style when # the name regexes allow several styles. name-group= # Regular expression which should only match function or class names that do # not require a docstring. no-docstring-rgx=^_ # List of decorators that produce properties, such as abc.abstractproperty. Add # to this list to register other decorators that produce valid properties. # These decorators are taken in consideration only for invalid-name. property-classes=abc.abstractproperty # Naming style matching correct variable names. variable-naming-style=snake_case # Regular expression matching correct variable names. Overrides variable- # naming-style. #variable-rgx= [TYPECHECK] # List of decorators that produce context managers, such as # contextlib.contextmanager. Add to this list to register other decorators that # produce valid context managers. contextmanager-decorators=contextlib.contextmanager # List of members which are set dynamically and missed by pylint inference # system, and so shouldn't trigger E1101 when accessed. Python regular # expressions are accepted. generated-members= # Tells whether missing members accessed in mixin class should be ignored. A # mixin class is detected if its name ends with "mixin" (case insensitive). ignore-mixin-members=yes # Tells whether to warn about missing members when the owner of the attribute # is inferred to be None. ignore-none=yes # This flag controls whether pylint should warn about no-member and similar # checks whenever an opaque object is returned when inferring. The inference # can return multiple potential results while evaluating a Python object, but # some branches might not be evaluated, which results in partial inference. In # that case, it might be useful to still emit no-member and other checks for # the rest of the inferred objects. ignore-on-opaque-inference=yes # List of class names for which member attributes should not be checked (useful # for classes with dynamically set attributes). This supports the use of # qualified names. ignored-classes=optparse.Values,thread._local,_thread._local # List of module names for which member attributes should not be checked # (useful for modules/projects where namespaces are manipulated during runtime # and thus existing member attributes cannot be deduced by static analysis). It # supports qualified module names, as well as Unix pattern matching. ignored-modules= # Show a hint with possible names when a member name was not found. The aspect # of finding the hint is based on edit distance. missing-member-hint=yes # The minimum edit distance a name should have in order to be considered a # similar match for a missing member name. missing-member-hint-distance=1 # The total number of similar names that should be taken in consideration when # showing a hint for a missing member. missing-member-max-choices=1 # List of decorators that change the signature of a decorated function. signature-mutators= [STRING] # This flag controls whether the implicit-str-concat-in-sequence should # generate a warning on implicit string concatenation in sequences defined over # several lines. check-str-concat-over-line-jumps=no [SIMILARITIES] # Ignore comments when computing similarities. ignore-comments=yes # Ignore docstrings when computing similarities. ignore-docstrings=yes # Ignore imports when computing similarities. ignore-imports=no # Minimum lines number of a similarity. min-similarity-lines=4 [SPELLING] # Limits count of emitted suggestions for spelling mistakes. max-spelling-suggestions=4 # Spelling dictionary name. Available dictionaries: none. To make it work, # install the python-enchant package. spelling-dict= # List of comma separated words that should not be checked. spelling-ignore-words= # A path to a file that contains the private dictionary; one word per line. spelling-private-dict-file= # Tells whether to store unknown words to the private dictionary (see the # --spelling-private-dict-file option) instead of raising a message. spelling-store-unknown-words=no [FORMAT] # Expected format of line ending, e.g. empty (any line ending), LF or CRLF. expected-line-ending-format=LF # Force UNIX style new lines # Regexp for a line that is allowed to be longer than the limit. ignore-long-lines=^\s*(# )??$ # Number of spaces of indent required inside a hanging or continued line. indent-after-paren=4 # String used as indentation unit. This is usually " " (4 spaces) or "\t" (1 # tab). indent-string=' ' # Maximum number of characters on a single line. max-line-length=100 # Maximum number of lines in a module. max-module-lines=1000 # Allow the body of a class to be on the same line as the declaration if body # contains single statement. single-line-class-stmt=no # Allow the body of an if to be on the same line as the test if there is no # else. single-line-if-stmt=no [MISCELLANEOUS] # List of note tags to take in consideration, separated by a comma. notes=FIXME, XXX [IMPORTS] # List of modules that can be imported at any level, not just the top level # one. allow-any-import-level= # Allow wildcard imports from modules that define __all__. allow-wildcard-with-all=no # Analyse import fallback blocks. This can be used to support both Python 2 and # 3 compatible code, which means that the block might have code that exists # only in one or another interpreter, leading to false positives when analysed. analyse-fallback-blocks=no # Deprecated modules which should not be used, separated by a comma. deprecated-modules=optparse,tkinter.tix # Create a graph of external dependencies in the given file (report RP0402 must # not be disabled). ext-import-graph= # Create a graph of every (i.e. internal and external) dependencies in the # given file (report RP0402 must not be disabled). import-graph= # Create a graph of internal dependencies in the given file (report RP0402 must # not be disabled). int-import-graph= # Force import order to recognize a module as part of the standard # compatibility libraries. known-standard-library= # Force import order to recognize a module as part of a third party library. known-third-party=enchant # Couples of modules and preferred modules, separated by a comma. preferred-modules= [CLASSES] # List of method names used to declare (i.e. assign) instance attributes. defining-attr-methods=__init__, __new__, setUp, __post_init__ # List of member names, which should be excluded from the protected access # warning. exclude-protected=_asdict, _fields, _replace, _source, _make # List of valid names for the first argument in a class method. valid-classmethod-first-arg=cls # List of valid names for the first argument in a metaclass class method. valid-metaclass-classmethod-first-arg=cls [DESIGN] # Maximum number of arguments for function / method. max-args=10 # Maximum number of attributes for a class (see R0902). max-attributes=15 # Maximum number of boolean expressions in an if statement (see R0916). max-bool-expr=5 # Maximum number of branch for function / method body. max-branches=12 # Maximum number of locals for function / method body. max-locals=15 # Maximum number of parents for a class (see R0901). max-parents=7 # Maximum number of public methods for a class (see R0904). max-public-methods=20 # Maximum number of return / yield for function / method body. max-returns=10 # Maximum number of statements in function / method body. max-statements=50 # Minimum number of public methods for a class (see R0903). min-public-methods=1 [EXCEPTIONS] # Exceptions that will emit a warning when being caught. Defaults to # "BaseException, Exception". overgeneral-exceptions=builtins.BaseException, builtins.Exception python-pythonjsonlogger-3.0.0/pyproject.toml000066400000000000000000000033731460062357500213760ustar00rootroot00000000000000[build-system] requires = ["setuptools"] build-backend = "setuptools.build_meta" [project] name = "python-json-logger" version = "3.0.0" description = "JSON Log Formatter for the Python Logging Package" authors = [ {name = "Zakaria Zajac", email = "zak@madzak.com"}, ] maintainers = [ {name = "Nicholas Hairs", email = "info+python-json-logger@nicholashairs.com"}, ] # Dependency Information requires-python = ">=3.7" # dependencies = [] # Extra information readme = "README.md" license = {text = "BSD-2-Clause License"} classifiers = [ "Development Status :: 6 - Mature", "Intended Audience :: Developers", "License :: OSI Approved :: BSD License", "Operating System :: OS Independent", "Programming Language :: Python :: 3 :: Only", "Programming Language :: Python :: 3.7", "Programming Language :: Python :: 3.8", "Programming Language :: Python :: 3.9", "Programming Language :: Python :: 3.10", "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Topic :: System :: Logging", "Typing :: Typed", ] [project.urls] # homepage = "https://nhairs.github.io/python-json-logger/latest/" GitHub = "https://github.com/nhairs/python-json-logger" [project.optional-dependencies] lint = [ "validate-pyproject[all]", "black", "pylint", "mypy", ] test = [ "pytest", ] #docs = [ # "black", # "mkdocs", # "mkdocs-material>=8.5", # "mkdocs-awesome-pages-plugin", # "mdx_truly_sane_lists", # "mkdocstrings[python]", # "mkdocs-gen-files", # "mkdocs-literate-nav", # "mike", #] [tool.setuptools.packages.find] where = ["src"] include = ["pythonjsonlogger*"] [tool.setuptools.package-data] pythonjsonlogger = ["py.typed"] [tool.black] line-length = 100 python-pythonjsonlogger-3.0.0/requirements/000077500000000000000000000000001460062357500211775ustar00rootroot00000000000000python-pythonjsonlogger-3.0.0/requirements/ci.txt000066400000000000000000000000741460062357500223340ustar00rootroot00000000000000coverage pylint unittest-xml-reporting wheel setuptools tox python-pythonjsonlogger-3.0.0/setup.cfg000066400000000000000000000021031460062357500202710ustar00rootroot00000000000000[mypy] # For details on each flag, please see the mypy documentation at: # https://mypy.readthedocs.io/en/stable/config_file.html#config-file # Import Discovery mypy_path = src namespace_packages = true # Disallow dynamic typing disallow_any_unimported = true disallow_any_expr = false disallow_any_decorated = true disallow_any_explicit = false disallow_any_generics = false disallow_subclassing_any = true # Untyped definitions and calls disallow_untyped_calls = false disallow_untyped_defs = false disallow_incomplete_defs = true check_untyped_defs = true disallow_untyped_decorators = true # None and Optional handling no_implicit_optional = true # Configuring warnings warn_redundant_casts = true warn_unused_ignores = true warn_no_return = true warn_return_any = true warn_unreachable = true # Miscellaneous strictness flags implicit_reexport = true strict_equality = true # Configuring error messages show_error_context = true show_column_numbers = true show_error_codes = true pretty = true show_absolute_path = true # Miscellaneous warn_unused_configs = true verbosity = 0 python-pythonjsonlogger-3.0.0/src/000077500000000000000000000000001460062357500172435ustar00rootroot00000000000000python-pythonjsonlogger-3.0.0/src/pythonjsonlogger/000077500000000000000000000000001460062357500226565ustar00rootroot00000000000000python-pythonjsonlogger-3.0.0/src/pythonjsonlogger/__init__.py000066400000000000000000000000001460062357500247550ustar00rootroot00000000000000python-pythonjsonlogger-3.0.0/src/pythonjsonlogger/jsonlogger.py000066400000000000000000000257671460062357500254220ustar00rootroot00000000000000""" This library is provided to allow standard python logging to output log data as JSON formatted strings """ import logging import json import re import traceback import importlib from datetime import date, datetime, time, timezone import sys from typing import Any, Callable, Dict, List, Optional, Tuple, Union from inspect import istraceback from collections import OrderedDict # skip natural LogRecord attributes # http://docs.python.org/library/logging.html#logrecord-attributes # Changed in 3.0.0, is now list[str] instead of tuple[str, ...] RESERVED_ATTRS: List[str] = [ "args", "asctime", "created", "exc_info", "exc_text", "filename", "funcName", "levelname", "levelno", "lineno", "module", "msecs", "message", "msg", "name", "pathname", "process", "processName", "relativeCreated", "stack_info", "thread", "threadName", ] if sys.version_info >= (3, 12): # taskName added in python 3.12 RESERVED_ATTRS.append("taskName") RESERVED_ATTRS.sort() OptionalCallableOrStr = Optional[Union[Callable, str]] def merge_record_extra( record: logging.LogRecord, target: Dict, reserved: Union[Dict, List], rename_fields: Optional[Dict[str, str]] = None, ) -> Dict: """ Merges extra attributes from LogRecord object into target dictionary :param record: logging.LogRecord :param target: dict to update :param reserved: dict or list with reserved keys to skip :param rename_fields: an optional dict, used to rename field names in the output. Rename levelname to log.level: {'levelname': 'log.level'} """ if rename_fields is None: rename_fields = {} for key, value in record.__dict__.items(): # this allows to have numeric keys if key not in reserved and not (hasattr(key, "startswith") and key.startswith("_")): target[rename_fields.get(key, key)] = value return target class JsonEncoder(json.JSONEncoder): """ A custom encoder extending the default JSONEncoder """ def default(self, o: Any) -> Any: if isinstance(o, (date, datetime, time)): return self.format_datetime_obj(o) if istraceback(o): return "".join(traceback.format_tb(o)).strip() # pylint: disable=unidiomatic-typecheck if type(o) == Exception or isinstance(o, Exception) or type(o) == type: return str(o) try: return super().default(o) except TypeError: try: return str(o) except Exception: # pylint: disable=broad-exception-caught return None def format_datetime_obj(self, o): """Format datetime objects found in self.default This allows subclasses to change the datetime format without understanding the internals of the default method. """ return o.isoformat() class JsonFormatter(logging.Formatter): """ A custom formatter to format logging records as json strings. Extra values will be formatted as str() if not supported by json default encoder """ # pylint: disable=too-many-arguments def __init__( self, *args: Any, json_default: OptionalCallableOrStr = None, json_encoder: OptionalCallableOrStr = None, json_serialiser: Union[Callable, str] = json.dumps, json_indent: Optional[Union[int, str]] = None, json_ensure_ascii: bool = True, prefix: str = "", rename_fields: Optional[dict] = None, static_fields: Optional[dict] = None, reserved_attrs: Union[Tuple[str, ...], List[str], None] = None, timestamp: Union[bool, str] = False, **kwargs: Any, ) -> None: """ :param json_default: a function for encoding non-standard objects as outlined in https://docs.python.org/3/library/json.html :param json_encoder: optional custom encoder :param json_serializer: a :meth:`json.dumps`-compatible callable that will be used to serialize the log record. :param json_indent: indent parameter for json.dumps :param json_ensure_ascii: ensure_ascii parameter for json.dumps :param prefix: an optional string prefix added at the beginning of the formatted string :param rename_fields: an optional dict, used to rename field names in the output. Rename message to @message: {'message': '@message'} :param static_fields: an optional dict, used to add fields with static values to all logs :param reserved_attrs: an optional list of fields that will be skipped when outputting json log record. Defaults to all log record attributes: http://docs.python.org/library/logging.html#logrecord-attributes :param timestamp: an optional string/boolean field to add a timestamp when outputting the json log record. If string is passed, timestamp will be added to log record using string as key. If True boolean is passed, timestamp key will be "timestamp". Defaults to False/off. """ self.json_default = self._str_to_fn(json_default) self.json_encoder = self._str_to_fn(json_encoder) self.json_serializer = self._str_to_fn(json_serialiser) self.json_indent = json_indent self.json_ensure_ascii = json_ensure_ascii self.prefix = prefix self.rename_fields = rename_fields or {} self.static_fields = static_fields or {} if reserved_attrs is None: reserved_attrs = RESERVED_ATTRS self.reserved_attrs = dict(zip(reserved_attrs, reserved_attrs)) self.timestamp = timestamp # super(JsonFormatter, self).__init__(*args, **kwargs) logging.Formatter.__init__(self, *args, **kwargs) if not self.json_encoder and not self.json_default: self.json_encoder = JsonEncoder self._required_fields = self.parse() self._skip_fields = dict(zip(self._required_fields, self._required_fields)) self._skip_fields.update(self.reserved_attrs) return def _str_to_fn(self, fn_as_str): """ If the argument is not a string, return whatever was passed in. Parses a string such as package.module.function, imports the module and returns the function. :param fn_as_str: The string to parse. If not a string, return it. """ if not isinstance(fn_as_str, str): return fn_as_str path, _, function = fn_as_str.rpartition(".") module = importlib.import_module(path) return getattr(module, function) def parse(self) -> List[str]: """ Parses format string looking for substitutions This method is responsible for returning a list of fields (as strings) to include in all log messages. """ if isinstance(self._style, logging.StringTemplateStyle): formatter_style_pattern = re.compile(r"\$\{(.+?)\}", re.IGNORECASE) elif isinstance(self._style, logging.StrFormatStyle): formatter_style_pattern = re.compile(r"\{(.+?)\}", re.IGNORECASE) # PercentStyle is parent class of StringTemplateStyle and StrFormatStyle so # it needs to be checked last. elif isinstance(self._style, logging.PercentStyle): formatter_style_pattern = re.compile(r"%\((.+?)\)", re.IGNORECASE) else: raise ValueError(f"Invalid format: {self._fmt!r}") if self._fmt: return formatter_style_pattern.findall(self._fmt) return [] def add_fields( self, log_record: Dict[str, Any], record: logging.LogRecord, message_dict: Dict[str, Any], ) -> None: """ Override this method to implement custom logic for adding fields. """ for field in self._required_fields: log_record[field] = record.__dict__.get(field) log_record.update(self.static_fields) log_record.update(message_dict) merge_record_extra( record, log_record, reserved=self._skip_fields, rename_fields=self.rename_fields, ) if self.timestamp: # TODO: Can this use isinstance instead? # pylint: disable=unidiomatic-typecheck key = self.timestamp if type(self.timestamp) == str else "timestamp" log_record[key] = datetime.fromtimestamp(record.created, tz=timezone.utc) self._perform_rename_log_fields(log_record) return def _perform_rename_log_fields(self, log_record: Dict[str, Any]) -> None: for old_field_name, new_field_name in self.rename_fields.items(): log_record[new_field_name] = log_record[old_field_name] del log_record[old_field_name] return def process_log_record(self, log_record: Dict[str, Any]) -> Dict[str, Any]: """ Override this method to implement custom logic on the possibly ordered dictionary. """ return log_record def jsonify_log_record(self, log_record: Dict[str, Any]) -> str: """Returns a json string of the log record.""" return self.json_serializer( log_record, default=self.json_default, cls=self.json_encoder, indent=self.json_indent, ensure_ascii=self.json_ensure_ascii, ) def serialize_log_record(self, log_record: Dict[str, Any]) -> str: """Returns the final representation of the log record.""" return self.prefix + self.jsonify_log_record(log_record) def format(self, record: logging.LogRecord) -> str: """Formats a log record and serializes to json""" message_dict: Dict[str, Any] = {} # TODO: logging.LogRecord.msg and logging.LogRecord.message in typeshed # are always type of str. We shouldn't need to override that. if isinstance(record.msg, dict): message_dict = record.msg record.message = "" else: record.message = record.getMessage() # only format time if needed if "asctime" in self._required_fields: record.asctime = self.formatTime(record, self.datefmt) # Display formatted exception, but allow overriding it in the # user-supplied dict. if record.exc_info and not message_dict.get("exc_info"): message_dict["exc_info"] = self.formatException(record.exc_info) if not message_dict.get("exc_info") and record.exc_text: message_dict["exc_info"] = record.exc_text # Display formatted record of stack frames # default format is a string returned from :func:`traceback.print_stack` if record.stack_info and not message_dict.get("stack_info"): message_dict["stack_info"] = self.formatStack(record.stack_info) log_record: Dict[str, Any] = OrderedDict() self.add_fields(log_record, record, message_dict) log_record = self.process_log_record(log_record) return self.serialize_log_record(log_record) python-pythonjsonlogger-3.0.0/src/pythonjsonlogger/py.typed000066400000000000000000000001201460062357500243460ustar00rootroot00000000000000# PEP-561 marker. https://mypy.readthedocs.io/en/latest/installed_packages.html python-pythonjsonlogger-3.0.0/tests/000077500000000000000000000000001460062357500176165ustar00rootroot00000000000000python-pythonjsonlogger-3.0.0/tests/__init__.py000066400000000000000000000000001460062357500217150ustar00rootroot00000000000000python-pythonjsonlogger-3.0.0/tests/test_jsonlogger.py000066400000000000000000000263541460062357500234120ustar00rootroot00000000000000import datetime import logging from io import StringIO import json import random import sys import traceback import unittest import unittest.mock sys.path.append("src/python-json-logger") from pythonjsonlogger import jsonlogger class TestJsonLogger(unittest.TestCase): def setUp(self): self.log = logging.getLogger(f"logging-test-{random.randint(1, 101)}") self.log.setLevel(logging.DEBUG) self.buffer = StringIO() self.log_handler = logging.StreamHandler(self.buffer) self.log.addHandler(self.log_handler) def test_default_format(self): fr = jsonlogger.JsonFormatter() self.log_handler.setFormatter(fr) msg = "testing logging format" self.log.info(msg) log_json = json.loads(self.buffer.getvalue()) self.assertEqual(log_json["message"], msg) def test_percentage_format(self): fr = jsonlogger.JsonFormatter( # All kind of different styles to check the regex "[%(levelname)8s] %(message)s %(filename)s:%(lineno)d %(asctime)" ) self.log_handler.setFormatter(fr) msg = "testing logging format" self.log.info(msg) log_json = json.loads(self.buffer.getvalue()) self.assertEqual(log_json["message"], msg) self.assertEqual(log_json.keys(), {"levelname", "message", "filename", "lineno", "asctime"}) def test_rename_base_field(self): fr = jsonlogger.JsonFormatter(rename_fields={"message": "@message"}) self.log_handler.setFormatter(fr) msg = "testing logging format" self.log.info(msg) log_json = json.loads(self.buffer.getvalue()) self.assertEqual(log_json["@message"], msg) def test_rename_nonexistent_field(self): fr = jsonlogger.JsonFormatter(rename_fields={"nonexistent_key": "new_name"}) self.log_handler.setFormatter(fr) stderr_watcher = StringIO() sys.stderr = stderr_watcher self.log.info("testing logging rename") self.assertTrue("KeyError: 'nonexistent_key'" in stderr_watcher.getvalue()) def test_add_static_fields(self): fr = jsonlogger.JsonFormatter(static_fields={"log_stream": "kafka"}) self.log_handler.setFormatter(fr) msg = "testing static fields" self.log.info(msg) log_json = json.loads(self.buffer.getvalue()) self.assertEqual(log_json["log_stream"], "kafka") self.assertEqual(log_json["message"], msg) def test_format_keys(self): supported_keys = [ "asctime", "created", "filename", "funcName", "levelname", "levelno", "lineno", "module", "msecs", "message", "name", "pathname", "process", "processName", "relativeCreated", "thread", "threadName", ] log_format = lambda x: [f"%({i:s})s" for i in x] custom_format = " ".join(log_format(supported_keys)) fr = jsonlogger.JsonFormatter(custom_format) self.log_handler.setFormatter(fr) msg = "testing logging format" self.log.info(msg) log_msg = self.buffer.getvalue() log_json = json.loads(log_msg) for supported_key in supported_keys: if supported_key in log_json: self.assertTrue(True) def test_unknown_format_key(self): fr = jsonlogger.JsonFormatter("%(unknown_key)s %(message)s") self.log_handler.setFormatter(fr) msg = "testing unknown logging format" try: self.log.info(msg) except Exception: self.assertTrue(False, "Should succeed") def test_log_adict(self): fr = jsonlogger.JsonFormatter() self.log_handler.setFormatter(fr) msg = {"text": "testing logging", "num": 1, 5: "9", "nested": {"more": "data"}} self.log.info(msg) log_json = json.loads(self.buffer.getvalue()) self.assertEqual(log_json.get("text"), msg["text"]) self.assertEqual(log_json.get("num"), msg["num"]) self.assertEqual(log_json.get("5"), msg[5]) self.assertEqual(log_json.get("nested"), msg["nested"]) self.assertEqual(log_json["message"], "") def test_log_extra(self): fr = jsonlogger.JsonFormatter() self.log_handler.setFormatter(fr) extra = {"text": "testing logging", "num": 1, 5: "9", "nested": {"more": "data"}} self.log.info("hello", extra=extra) log_json = json.loads(self.buffer.getvalue()) self.assertEqual(log_json.get("text"), extra["text"]) self.assertEqual(log_json.get("num"), extra["num"]) self.assertEqual(log_json.get("5"), extra[5]) self.assertEqual(log_json.get("nested"), extra["nested"]) self.assertEqual(log_json["message"], "hello") def test_json_default_encoder(self): fr = jsonlogger.JsonFormatter() self.log_handler.setFormatter(fr) msg = { "adate": datetime.datetime(1999, 12, 31, 23, 59), "otherdate": datetime.date(1789, 7, 14), "otherdatetime": datetime.datetime(1789, 7, 14, 23, 59), "otherdatetimeagain": datetime.datetime(1900, 1, 1), } self.log.info(msg) log_json = json.loads(self.buffer.getvalue()) self.assertEqual(log_json.get("adate"), "1999-12-31T23:59:00") self.assertEqual(log_json.get("otherdate"), "1789-07-14") self.assertEqual(log_json.get("otherdatetime"), "1789-07-14T23:59:00") self.assertEqual(log_json.get("otherdatetimeagain"), "1900-01-01T00:00:00") @unittest.mock.patch("time.time", return_value=1500000000.0) def test_json_default_encoder_with_timestamp(self, time_mock): fr = jsonlogger.JsonFormatter(timestamp=True) self.log_handler.setFormatter(fr) self.log.info("Hello") self.assertTrue(time_mock.called) log_json = json.loads(self.buffer.getvalue()) self.assertEqual(log_json.get("timestamp"), "2017-07-14T02:40:00+00:00") def test_json_custom_default(self): def custom(o): return "very custom" fr = jsonlogger.JsonFormatter(json_default=custom) self.log_handler.setFormatter(fr) msg = {"adate": datetime.datetime(1999, 12, 31, 23, 59), "normal": "value"} self.log.info(msg) log_json = json.loads(self.buffer.getvalue()) self.assertEqual(log_json.get("adate"), "very custom") self.assertEqual(log_json.get("normal"), "value") def test_json_custom_logic_adds_field(self): class CustomJsonFormatter(jsonlogger.JsonFormatter): def process_log_record(self, log_record): log_record["custom"] = "value" # Old Style "super" since Python 2.6's logging.Formatter is old # style return jsonlogger.JsonFormatter.process_log_record(self, log_record) self.log_handler.setFormatter(CustomJsonFormatter()) self.log.info("message") log_json = json.loads(self.buffer.getvalue()) self.assertEqual(log_json.get("custom"), "value") def get_traceback_from_exception_followed_by_log_call(self) -> str: try: raise Exception("test") except Exception: self.log.exception("hello") str_traceback = traceback.format_exc() # Formatter removes trailing new line if str_traceback.endswith("\n"): str_traceback = str_traceback[:-1] return str_traceback def test_exc_info(self): fr = jsonlogger.JsonFormatter() self.log_handler.setFormatter(fr) expected_value = self.get_traceback_from_exception_followed_by_log_call() log_json = json.loads(self.buffer.getvalue()) self.assertEqual(log_json.get("exc_info"), expected_value) def test_exc_info_renamed(self): fr = jsonlogger.JsonFormatter("%(exc_info)s", rename_fields={"exc_info": "stack_trace"}) self.log_handler.setFormatter(fr) expected_value = self.get_traceback_from_exception_followed_by_log_call() log_json = json.loads(self.buffer.getvalue()) self.assertEqual(log_json.get("stack_trace"), expected_value) self.assertEqual(log_json.get("exc_info"), None) def test_ensure_ascii_true(self): fr = jsonlogger.JsonFormatter() self.log_handler.setFormatter(fr) self.log.info("Привет") msg = self.buffer.getvalue().split('"message": "', 1)[1].split('"', 1)[0] self.assertEqual(msg, r"\u041f\u0440\u0438\u0432\u0435\u0442") def test_ensure_ascii_false(self): fr = jsonlogger.JsonFormatter(json_ensure_ascii=False) self.log_handler.setFormatter(fr) self.log.info("Привет") msg = self.buffer.getvalue().split('"message": "', 1)[1].split('"', 1)[0] self.assertEqual(msg, "Привет") def test_custom_object_serialization(self): def encode_complex(z): if isinstance(z, complex): return (z.real, z.imag) else: type_name = z.__class__.__name__ raise TypeError(f"Object of type '{type_name}' is no JSON serializable") formatter = jsonlogger.JsonFormatter( json_default=encode_complex, json_encoder=json.JSONEncoder ) self.log_handler.setFormatter(formatter) value = { "special": complex(3, 8), } self.log.info(" message", extra=value) msg = self.buffer.getvalue() self.assertEqual(msg, '{"message": " message", "special": [3.0, 8.0]}\n') def test_rename_reserved_attrs(self): log_format = lambda x: [f"%({i:s})s" for i in x] reserved_attrs_map = { "exc_info": "error.type", "exc_text": "error.message", "funcName": "log.origin.function", "levelname": "log.level", "module": "log.origin.file.name", "processName": "process.name", "threadName": "process.thread.name", "msg": "log.message", } custom_format = " ".join(log_format(reserved_attrs_map.keys())) reserved_attrs = [ _ for _ in jsonlogger.RESERVED_ATTRS if _ not in list(reserved_attrs_map.keys()) ] formatter = jsonlogger.JsonFormatter( custom_format, reserved_attrs=reserved_attrs, rename_fields=reserved_attrs_map ) self.log_handler.setFormatter(formatter) self.log.info("message") msg = self.buffer.getvalue() self.assertEqual( msg, '{"error.type": null, "error.message": null, "log.origin.function": "test_rename_reserved_attrs", "log.level": "INFO", "log.origin.file.name": "test_jsonlogger", "process.name": "MainProcess", "process.thread.name": "MainThread", "log.message": "message"}\n', ) def test_merge_record_extra(self): record = logging.LogRecord( "name", level=1, pathname="", lineno=1, msg="Some message", args=None, exc_info=None ) output = jsonlogger.merge_record_extra(record, target=dict(foo="bar"), reserved=[]) self.assertIn("foo", output) self.assertIn("msg", output) self.assertEqual(output["foo"], "bar") self.assertEqual(output["msg"], "Some message") python-pythonjsonlogger-3.0.0/tox.ini000066400000000000000000000011761460062357500177740ustar00rootroot00000000000000[tox] requires = tox>=3 envlist = lint, type, pypy{37,38,39,310}, py{37,38,39,310,311,312} [gh-actions] python = pypy-3.7: pypy37 pypy-3.8: pypy38 pypy-3.9: pypy39 pypy-3.10: pypy310 3.7: py37 3.8: py38 3.9: py39 3.10: py310 3.11: py311 3.12: py312 [testenv] description = run unit tests extras = test commands = pytest tests [testenv:format] description = run formatters extras = lint commands = black src tests [testenv:lint] description = run linters extras = lint commands = validate-pyproject pyproject.toml black --check --diff src tests pylint src mypy src tests