madpah / serializable

Pythonic library to aid with serialisation and deserialisation to/from JSON and XML.

Home Page:https://py-serializable.readthedocs.io/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Using `serializable.serializable_class` during import configures root logger

kroeschl opened this issue · comments

Description

If some user of py-serializable calls serializable.serializable_class before configuring the root logger (which is common during import blocks), the root logger ends up configured with the default basic configuration.

This happens because we call logging.debug in ObjectMetadataLibrary.register_klass. Calling logging.debug (or similar) will automatically call logging.basicConfig if no handlers are configured for the root logger.

We should probably do what most modules do and set up our own logger and NullHandler rather than using the root logger.

Example

import logging
import serializable

@serializable.serializable_class
class Foo:
    pass

_logger = logging.getLogger()
_logger.addHandler(logging.NullHandler())
_logger.error("foo")

Outputs ERROR:root:foo, which shouldn't happen if I only configure a NullHandler.

Workaround

I'm currently working around this by wrapping the import of anything that uses py-serializable (in this case, CycloneDX) in a logging configuration hack:

_root_logger = logging.getLogger()
_root_null_handler = logging.NullHandler()
_root_logger.addHandler(_root_null_handler)
from cyclonedx.model.bom import Bom
_root_logger.removeHandler(_root_null_handler)

Version Info

  • Python 3.10.9 & Python 3.9.13
  • py-serializable 0.11.1

I'll post a PR to fix this if the issue is approved or sits for a while.

Ran into same issue today after spending time to find out where it happens. Issue is as described above in #9 (comment) - the library calls logging.debug() instead of using logger.debug(). As the serialization library is used via annotations the code is called on imports of any other code using it.

Another workaround for reconfiguring the root logger after the import of madpah/serializable/serializable/init.py is to use logging.basicConfig(..., force=True) and overwrite the settings later. However, the proper fix should be done in this library by not using the global logging.debug calls.

@kroeschl please go ahead for a PR to get this fixed

@kroeschl @bmihaila-synopsys

I took solution #10 and modified it to all needs. Now it looks good to me.
Please have a last review, before it gets merged and published :-)