madzak / python-json-logger

Json Formatter for the standard python logger
BSD 2-Clause "Simplified" License
1.7k stars 231 forks source link

Type hints & PEP 561 packaging #118

Closed tuukkamustonen closed 1 year ago

tuukkamustonen commented 3 years ago

Add type hints to all (public API) code make the distribution PEP 561 compliant. This allows mypy (and other tools?) to find the type hints and use them in linting.

In practice, add py.typed file to src/pythonjsonlogger, and include it in the package:

setup(
    package_data={'pythonjsonlogger': ['py.typed']},
    zip_safe=False,  # not needed with wheels, AFAIK
)

PEP 561: https://www.python.org/dev/peps/pep-0561/

chdsbd commented 2 years ago

@madzak Would you accept a PR for this?

madzak commented 2 years ago

Sure!

bringhurst commented 2 years ago

I'm having trouble figuring out what should be done in this case:

      def format(self, record):
          """Formats a log record and serializes to json"""
          message_dict = {}
          if isinstance(record.msg, dict):
              message_dict = record.msg
              record.message = None
          else:
              record.message = record.getMessage()

with a related test:

    def testJsonCustomDefault(self):
        def custom(o):
            return "very custom"
        fr = jsonlogger.JsonFormatter(json_default=custom)
        self.logHandler.setFormatter(fr)

        msg = {"adate": datetime.datetime(1999, 12, 31, 23, 59),
               "normal": "value"}
        self.logger.info(msg)
        logJson = json.loads(self.buffer.getvalue())
        self.assertEqual(logJson.get("adate"), "very custom")
        self.assertEqual(logJson.get("normal"), "value")

Note that record.msg is type of Union[str, Dict] here, but logging.LogRecord.msg in typeshed is type of str (same deal with message).

I'll think about it a bit and see what I can do, but any help would be appreciated.

Possible workaround is over at https://github.com/madzak/python-json-logger/pull/133

alexmirrington commented 1 year ago

Any additional progress on this? Do we have a list of what needs to be completed in order to achieve PEP 561 compliance?

mwgamble commented 1 year ago

There's already a py.typed file in the repo, but it doesn't seem to be included in the packages uploaded to PyPI.

akshayphdk commented 1 year ago

@madzak perhaps https://github.com/madzak/python-json-logger/pull/156 would bring this issue closer to done?

Eyal-Shalev commented 1 year ago

@madzak any updates on this?