|
| 1 | +import json |
| 2 | +import logging |
| 3 | +from dataclasses import asdict |
| 4 | + |
| 5 | +from openfeature.evaluation_context import EvaluationContext |
| 6 | +from openfeature.exception import ErrorCode, OpenFeatureError |
| 7 | +from openfeature.flag_evaluation import FlagEvaluationDetails, FlagValueType |
| 8 | +from openfeature.hook import Hook, HookContext, HookHints |
| 9 | + |
| 10 | + |
| 11 | +class LoggingHook(Hook): |
| 12 | + def __init__( |
| 13 | + self, |
| 14 | + include_evaluation_context: bool = False, |
| 15 | + logger: logging.Logger | None = None, |
| 16 | + ): |
| 17 | + self.logger = logger or logging.getLogger("openfeature") |
| 18 | + self.include_evaluation_context = include_evaluation_context |
| 19 | + |
| 20 | + def _build_args(self, hook_context: HookContext, stage: str) -> dict: |
| 21 | + args = { |
| 22 | + "domain": hook_context.client_metadata.domain |
| 23 | + if hook_context.client_metadata |
| 24 | + else None, |
| 25 | + "provider_name": hook_context.provider_metadata.name |
| 26 | + if hook_context.provider_metadata |
| 27 | + else None, |
| 28 | + "flag_key": hook_context.flag_key, |
| 29 | + "default_value": hook_context.default_value, |
| 30 | + "stage": stage, |
| 31 | + } |
| 32 | + if self.include_evaluation_context: |
| 33 | + args["evaluation_context"] = json.dumps( |
| 34 | + asdict(hook_context.evaluation_context), |
| 35 | + default=str, |
| 36 | + ) |
| 37 | + return args |
| 38 | + |
| 39 | + def before( |
| 40 | + self, hook_context: HookContext, hints: HookHints |
| 41 | + ) -> EvaluationContext | None: |
| 42 | + args = self._build_args(hook_context, "before") |
| 43 | + self.logger.debug("Flag evaluation %s", args) |
| 44 | + return None |
| 45 | + |
| 46 | + def after( |
| 47 | + self, |
| 48 | + hook_context: HookContext, |
| 49 | + details: FlagEvaluationDetails[FlagValueType], |
| 50 | + hints: HookHints, |
| 51 | + ) -> None: |
| 52 | + args = self._build_args(hook_context, "after") |
| 53 | + args["reason"] = details.reason |
| 54 | + args["variant"] = details.variant |
| 55 | + args["value"] = details.value |
| 56 | + self.logger.debug("Flag evaluation %s", args) |
| 57 | + |
| 58 | + def error( |
| 59 | + self, hook_context: HookContext, exception: Exception, hints: HookHints |
| 60 | + ) -> None: |
| 61 | + args = self._build_args(hook_context, "error") |
| 62 | + if isinstance(exception, OpenFeatureError): |
| 63 | + args["error_code"] = exception.error_code |
| 64 | + args["error_message"] = exception.error_message |
| 65 | + else: |
| 66 | + args["error_code"] = ErrorCode.GENERAL |
| 67 | + args["error_message"] = str(exception) |
| 68 | + self.logger.error("Flag evaluation %s", args) |
0 commit comments