forked from open-feature/python-sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlogging_hook.py
More file actions
68 lines (61 loc) · 2.4 KB
/
logging_hook.py
File metadata and controls
68 lines (61 loc) · 2.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
import json
import logging
from dataclasses import asdict
from openfeature.evaluation_context import EvaluationContext
from openfeature.exception import ErrorCode, OpenFeatureError
from openfeature.flag_evaluation import FlagEvaluationDetails, FlagValueType
from openfeature.hook import Hook, HookContext, HookHints
class LoggingHook(Hook):
def __init__(
self,
include_evaluation_context: bool = False,
logger: logging.Logger | None = None,
):
self.logger = logger or logging.getLogger("openfeature")
self.include_evaluation_context = include_evaluation_context
def _build_args(self, hook_context: HookContext, stage: str) -> dict:
args = {
"domain": hook_context.client_metadata.domain
if hook_context.client_metadata
else None,
"provider_name": hook_context.provider_metadata.name
if hook_context.provider_metadata
else None,
"flag_key": hook_context.flag_key,
"default_value": hook_context.default_value,
"stage": stage,
}
if self.include_evaluation_context:
args["evaluation_context"] = json.dumps(
asdict(hook_context.evaluation_context),
default=str,
)
return args
def before(
self, hook_context: HookContext, hints: HookHints
) -> EvaluationContext | None:
args = self._build_args(hook_context, "before")
self.logger.debug("Flag evaluation %s", args)
return None
def after(
self,
hook_context: HookContext,
details: FlagEvaluationDetails[FlagValueType],
hints: HookHints,
) -> None:
args = self._build_args(hook_context, "after")
args["reason"] = details.reason
args["variant"] = details.variant
args["value"] = details.value
self.logger.debug("Flag evaluation %s", args)
def error(
self, hook_context: HookContext, exception: Exception, hints: HookHints
) -> None:
args = self._build_args(hook_context, "error")
if isinstance(exception, OpenFeatureError):
args["error_code"] = exception.error_code
args["error_message"] = exception.error_message
else:
args["error_code"] = ErrorCode.GENERAL
args["error_message"] = str(exception)
self.logger.error("Flag evaluation %s", args)