keijack / python-eureka-client

A eureka client written in python. Support registering your python component to Eureka Server, as well as calling remote services by pulling the the Eureka registry.
MIT License
189 stars 44 forks source link

How to use standard Python logging? #88

Open josephgrigg opened 2 weeks ago

josephgrigg commented 2 weeks ago

Hello,

I see that all logs go through the CacheLogger. Would you be able to add an option to use the standard Python logging instead? Using non-standard logging makes the logs confusing and error-prone. For example, if I call logging.getLogger('eureka_client'), then a new Logger instance is returned instead of the existing CacheLogger. This breaks some other code I've written to adjust log levels using environment variables.

Currently, I'm monkey patching the logger.get_logger method with something like the following code, which works well enough. However, it would be nice for this to be default behavior, or at least an option, since it is standard Python practice.

import logging
from py_eureka_client import logger as py_eureka_client_logger
py_eureka_client_logger.get_logger = logging.getLogger
keijack commented 1 week ago

You can now use the flowing code to set your own logger:

import py_eureka_client.logger as logger
logger.set_custom_logger(your_logger)
josephgrigg commented 1 week ago

Thank you.

The only downside with this is that users have to be aware of the import order. For example, I don't think this would work:

import logging
from py_eureka_client import logger
from py_eureka_client import eureka_client

your_logger = logging.getLogger("py_eureka_client")
logger.set_custom_logger(your_logger)

Instead, it'd have to be written like this so that set_custom_logger is called before get_logger:

import logging
from py_eureka_client import logger

your_logger = logging.getLogger("py_eureka_client")
logger.set_custom_logger(your_logger)

from py_eureka_client import eureka_client

The only alternative I can think of at the moment would be introducing configuration option through environment variable. However, I'm not even convinced that's any better. e.g.

def get_logger(tag: str = "python-eureka-client") -> logging.Logger:
    if os.get("PY_EUREKA_CLIENT__LOGGER", "").lower() == "logging":
        return logging.getLogger(tag)
    return _default_logger_factory.get_logger(tag)

That said, I find your solution acceptable for my use-case. I really appreciate the effort you put into maintaining this library and the quick turn around! 😄 🚀

keijack commented 6 days ago

Yes, you are right, I've fixed that to, please upgrade to 0.11.13.