Skip to content

Commit

Permalink
Resolve cyclic module imports as detected by LGTM.com
Browse files Browse the repository at this point in the history
  • Loading branch information
nolar committed Mar 26, 2020
1 parent d94070f commit a1cf3c2
Show file tree
Hide file tree
Showing 5 changed files with 53 additions and 55 deletions.
4 changes: 3 additions & 1 deletion kopf/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,14 +10,16 @@
on, # as a separate name on the public namespace
)
from kopf.config import (
configure,
LOGLEVEL_INFO, # deprecated
LOGLEVEL_WARNING, # deprecated
LOGLEVEL_ERROR, # deprecated
LOGLEVEL_CRITICAL, # deprecated
EventsConfig, # deprecated
WorkersConfig, # deprecated
)
from kopf.engines.logging import (
configure,
)
from kopf.engines.posting import (
event,
info,
Expand Down
4 changes: 2 additions & 2 deletions kopf/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@

import click

from kopf import config
from kopf.engines import logging
from kopf.engines import peering
from kopf.reactor import registries
from kopf.reactor import running
Expand All @@ -32,7 +32,7 @@ def logging_options(fn: Callable[..., Any]) -> Callable[..., Any]:
@click.option('-q', '--quiet', is_flag=True)
@functools.wraps(fn) # to preserve other opts/args
def wrapper(verbose: bool, quiet: bool, debug: bool, *args: Any, **kwargs: Any) -> Any:
config.configure(debug=debug, verbose=verbose, quiet=quiet)
logging.configure(debug=debug, verbose=verbose, quiet=quiet)
return fn(*args, **kwargs)

return wrapper
Expand Down
50 changes: 0 additions & 50 deletions kopf/config.py
Original file line number Diff line number Diff line change
@@ -1,63 +1,13 @@
import asyncio
import logging
from typing import Optional

from kopf.engines import logging as logging_engine

format = '[%(asctime)s] %(name)-20.20s [%(levelname)-8.8s] %(message)s'


# Deprecated: use ``logging.*`` constants instead. Kept here for backward-compatibility.
LOGLEVEL_INFO = logging.INFO
LOGLEVEL_WARNING = logging.WARNING
LOGLEVEL_ERROR = logging.ERROR
LOGLEVEL_CRITICAL = logging.CRITICAL


def configure(
debug: Optional[bool] = None,
verbose: Optional[bool] = None,
quiet: Optional[bool] = None,
) -> None:
log_level = 'DEBUG' if debug or verbose else 'WARNING' if quiet else 'INFO'

logger = logging.getLogger()
handler = logging.StreamHandler()
formatter = logging_engine.ObjectPrefixingFormatter(format)
handler.setFormatter(formatter)
logger.addHandler(handler)
logger.setLevel(log_level)

# Configure the Kubernetes client defaults according to our settings.
try:
import kubernetes
except ImportError:
pass
else:
config = kubernetes.client.configuration.Configuration()
config.logger_format = format
config.logger_file = None # once again after the constructor to re-apply the formatter
config.debug = debug
kubernetes.client.configuration.Configuration.set_default(config)

# Kubernetes client is as buggy as hell: it adds its own stream handlers even in non-debug mode,
# does not respect the formatting, and dumps too much of the low-level info.
if not debug:
logger = logging.getLogger("urllib3")
del logger.handlers[1:] # everything except the default NullHandler

# Prevent the low-level logging unless in the debug verbosity mode. Keep only the operator's messages.
# For no-propagation loggers, add a dummy null handler to prevent printing the messages.
for name in ['urllib3', 'asyncio', 'kubernetes']:
logger = logging.getLogger(name)
logger.propagate = bool(debug)
if not debug:
logger.handlers[:] = [logging.NullHandler()]

loop = asyncio.get_event_loop()
loop.set_debug(bool(debug))


# DEPRECATED: Used for initial defaults for per-operator settings (see kopf.structs.configuration).
class EventsConfig:
"""
Expand Down
47 changes: 47 additions & 0 deletions kopf/engines/logging.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
the operators' code, and can lead to information loss or mismatch
(e.g. when logging call is added, but posting is forgotten).
"""
import asyncio
import copy
import logging
from typing import Tuple, MutableMapping, Any, Optional
Expand Down Expand Up @@ -129,3 +130,49 @@ def log(self, *args: Any, **kwargs: Any) -> None:

logger = logging.getLogger('kopf.objects')
logger.addHandler(K8sPoster())

format = '[%(asctime)s] %(name)-20.20s [%(levelname)-8.8s] %(message)s'


def configure(
debug: Optional[bool] = None,
verbose: Optional[bool] = None,
quiet: Optional[bool] = None,
) -> None:
log_level = 'DEBUG' if debug or verbose else 'WARNING' if quiet else 'INFO'

logger = logging.getLogger()
handler = logging.StreamHandler()
formatter = ObjectPrefixingFormatter(format)
handler.setFormatter(formatter)
logger.addHandler(handler)
logger.setLevel(log_level)

# Configure the Kubernetes client defaults according to our settings.
try:
import kubernetes
except ImportError:
pass
else:
config = kubernetes.client.configuration.Configuration()
config.logger_format = format
config.logger_file = None # once again after the constructor to re-apply the formatter
config.debug = debug
kubernetes.client.configuration.Configuration.set_default(config)

# Kubernetes client is as buggy as hell: it adds its own stream handlers even in non-debug mode,
# does not respect the formatting, and dumps too much of the low-level info.
if not debug:
logger = logging.getLogger("urllib3")
del logger.handlers[1:] # everything except the default NullHandler

# Prevent the low-level logging unless in the debug verbosity mode. Keep only the operator's messages.
# For no-propagation loggers, add a dummy null handler to prevent printing the messages.
for name in ['urllib3', 'asyncio', 'kubernetes']:
logger = logging.getLogger(name)
logger.propagate = bool(debug)
if not debug:
logger.handlers[:] = [logging.NullHandler()]

loop = asyncio.get_event_loop()
loop.set_debug(bool(debug))
3 changes: 1 addition & 2 deletions tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,7 @@

import kopf
from kopf.clients.auth import APIContext
from kopf.config import configure
from kopf.engines.logging import ObjectPrefixingFormatter
from kopf.engines.logging import configure, ObjectPrefixingFormatter
from kopf.engines.posting import settings_var
from kopf.structs.configuration import OperatorSettings
from kopf.structs.credentials import Vault, VaultKey, ConnectionInfo
Expand Down

0 comments on commit a1cf3c2

Please sign in to comment.