Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Break up logging so everything isn't coming off the root #87

Open
danielquinn opened this issue Oct 13, 2018 · 3 comments
Open

Break up logging so everything isn't coming off the root #87

danielquinn opened this issue Oct 13, 2018 · 3 comments

Comments

@danielquinn
Copy link
Contributor

As discussed earlier, here's the code snippet I was talking about to make logging easier project-wide:

# logger.py

import logging


class LogMixin:
    """
    Use this mixin to do logging:
      self.logger.debug("My debugging message")
    """

    __logger = None

    @property
    def logger(self) -> logging.Logger:

        if self.__logger:
            return self.__logger
        self.__logger = logging.getLogger(self.__class__.__module__)

        return self.logger

To use it, just do this:

from logger import LogMixin


class MyClass(LogMixin, AnyOtherParent):
    ...
    def my_method(self):
        self.logger.debug("This is my debug message with %s", some_variable)

This will produce log entries attached to the class and file path rather than the root.

@cgmcintyr
Copy link
Contributor

cgmcintyr commented Oct 18, 2018

Nice, going to steal this mixin for a project I'm working on.

You can get a speedup using a try/except block, as the except block will only run on the first call to self.logger.

class LogMixin:

    @property
    def logger(self) -> logging.Logger:
        try:
            return self.__logger
        except AttributeError:
            self.__logger = logging.getLogger(self.__class__.__module__)
            return self.__logger

Whether it's cleaner is another question...

@danielquinn
Copy link
Contributor Author

Ooh handy tip, thanks!

@cgmcintyr
Copy link
Contributor

cgmcintyr commented Oct 18, 2018

No worries :) It's explained here

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants