diff --git a/lib/gruvi/endpoints.py b/lib/gruvi/endpoints.py index 970298b..d3cecb1 100644 --- a/lib/gruvi/endpoints.py +++ b/lib/gruvi/endpoints.py @@ -22,9 +22,12 @@ from .ssl import SslTransport from .sslcompat import create_default_context from .address import getaddrinfo, saddr +from .util import EnvBool __all__ = ['create_connection', 'create_server', 'Endpoint', 'Client', 'Server'] +DEBUG = EnvBool.new('DEBUG') + @switchpoint def create_connection(protocol_factory, address, ssl=False, server_hostname=None, @@ -340,7 +343,7 @@ def handle_connection(self, client, ssl): transport = Transport(client) transport._log = self._log transport._server = self - if __debug__: + if DEBUG: self._log.debug('new connection on {}', saddr(client.getsockname())) if hasattr(client, 'getpeername'): self._log.debug('remote peer is {}', saddr(client.getpeername())) diff --git a/lib/gruvi/util.py b/lib/gruvi/util.py index a645dfc..7278c3a 100644 --- a/lib/gruvi/util.py +++ b/lib/gruvi/util.py @@ -8,6 +8,7 @@ from __future__ import absolute_import, print_function +import os import sys import re import functools @@ -17,6 +18,29 @@ __all__ = [] +class EnvBool(object): + """A boolean-like object that takes its value from the environment variable + *name*.""" + + _zero_values = ('0', 'n', 'f', 'false') + + def __init__(self, name): + self._name = name + + @classmethod + def new(cls, name): + # Optimize away $DEBUG when interpreter is running with -O + if name == 'DEBUG' and not __debug__: + return False + return cls(name) + + def __nonzero__(self): + value = os.environ.get(self._name, '0') + return value.lower() not in self._zero_values + + __bool__ = __nonzero__ + + class AbsentType(object): """A type that represents the absence of a value.