seagrass.hooks
- class seagrass.hooks.ContextManagerHook(cm: Union[AbstractContextManager[C], Callable[[], AbstractContextManager[C]]], nest: bool = False)
Bases:
ProtoHook[Optional[AbstractContextManager[C]]]A hook that wraps around a context manager, calling the context manager’s
__enter__and__exit__methods whenever the hook is activated.- property current_context_manager: Optional[AbstractContextManager[C]]
Return the current context manager instance being used by the hook.
- __init__(cm: Union[AbstractContextManager[C], Callable[[], AbstractContextManager[C]]], nest: bool = False) None
Create a new
ContextManagerHook.- Parameters
cm (t.Union[t.ContextManager, t.Callable[[], t.ContextManager]]) – a context manager (i.e., an object with
__enter__and__exit__methods) or a function that takes no arguments and creates a new context manager.nest (bool) –
whether successive invocations of the context manager should be nested. If
nest=Falseand another Seagrass event that uses this hook gets called, the prehook and cleanup stages of the hook will be skipped. In general, you should setnest=Trueif your context manager should be used along the lines ofwith cm: # Execute outer event ... with cm: # Execute inner event ... # Continue executing outer event ...
and
nest=Falseif your context manager should be used aswith cm: # Execute outer event ... # Execute inner event ... # Continue executing outer event ...
- prehook(event: str, args: Tuple[Any, ...], kwargs: Dict[str, Any]) Optional[AbstractContextManager[C]]
Run the prehook. The prehook is run at the beginning of the execution of an audited event, before the function wrapped by the event is run.
- Parameters
- Returns
“context” data that can be used by the posthook.
- Return type
C
- class seagrass.hooks.CounterHook
-
A Seagrass hook that counts the number of times an event occurs.
Examples:
>>> from seagrass.hooks import CounterHook >>> hook = CounterHook() >>> event_a = auditor.create_event("event_a", hooks=[hook]) >>> event_b = auditor.create_event("event_b", hooks=[hook]) >>> with auditor.start_auditing(log_results=True): ... for _ in range(15): ... auditor.raise_event("event_a") ... for _ in range(8): ... auditor.raise_event("event_b") {"message": "CounterHook results", "seagrass": {"event": null, "hook": "CounterHook", "hook_ctx": {"event": "event_a", "count": 15}}, "level": "INFO"} {"message": "CounterHook results", "seagrass": {"event": null, "hook": "CounterHook", "hook_ctx": {"event": "event_b", "count": 8}}, "level": "INFO"}
- class seagrass.hooks.FileOpenHook(**kwargs)
Bases:
RuntimeAuditHookAn event hook for tracking calls to the Python standard library’s open function.
- __init__(**kwargs) None
Initialize the RuntimeAuditHook.
- Parameters
propagate_errors (Optional[bool]) –
if not equal to
None, set thepropagate_errorsattribute of the hook, which controls whether errors raised bysys_hook()are propagated. Hooks for whichpropagate_errorsisFalsewill log errors raised bysys_hook(), but won’t raise them.By default,
hook.propagate_errors = Truefor RuntimeAuditHooks.
- class seagrass.hooks.LoggingHook(prehook_msg: Optional[Callable[[str, Tuple[Any, ...], Dict[str, Any]], Union[str, Tuple[Any, ...]]]] = None, posthook_msg: Optional[Callable[[str, Any], Union[str, Tuple[Any, ...]]]] = None, loglevel: int = 10)
-
A hook that emits a new log whenever it gets called.
- __init__(prehook_msg: Optional[Callable[[str, Tuple[Any, ...], Dict[str, Any]], Union[str, Tuple[Any, ...]]]] = None, posthook_msg: Optional[Callable[[str, Any], Union[str, Tuple[Any, ...]]]] = None, loglevel: int = 10) None
- prehook(event_name: str, args: Tuple[Any, ...], kwargs: Dict[str, Any]) None
Run the prehook. The prehook is run at the beginning of the execution of an audited event, before the function wrapped by the event is run.
- Parameters
- Returns
“context” data that can be used by the posthook.
- Return type
C
- posthook(event_name: str, result: Any, context: None) None
Run the posthook. The posthook is run at the end of the execution of an audited event, after the function wrapped by the event is run.
- Parameters
event_name (str) – The name of the event that was triggered.
result (Any) – The value that was returned by the event’s wrapped function.
context (C) – The context that was returned by the original call to
prehook.
- class seagrass.hooks.ProfilerHook(sort_keys: Union[str, int, Tuple[str, ...]] = (), restrictions: Union[str, int, float, Tuple[Union[str, int, float], ...]] = ())
-
A Seagrass hook that uses the built-in cProfile module to collect and log performance statistics on events.
- __init__(sort_keys: Union[str, int, Tuple[str, ...]] = (), restrictions: Union[str, int, float, Tuple[Union[str, int, float], ...]] = ()) None
Create a new ProfilerHook.
- Parameters
sort_keys (Union[K,Tuple[K,...]]) – a key or list of keys to use to sort the output generated by
log_results(). The available keys and their meanings are the same as those of pstats.Stats.sort_stats.restrictions (Union[R,Tuple[R,...]]) – a restriction or list of restrictions to use for the output generated by
log_results(). The available restrictions and their meanings are the same as those of pstats.Stats.print_stats.
- prehook(event_name: str, args: Tuple[Any, ...], kwargs: Dict[str, Any]) bool
Run the prehook. The prehook is run at the beginning of the execution of an audited event, before the function wrapped by the event is run.
- Parameters
- Returns
“context” data that can be used by the posthook.
- Return type
C
- get_stats(**kwargs) Optional[Stats]
Return the profiling statistics as a pstats.Stats class.
- Parameters
kwargs – Keyword arguments to pass to the constructor of pstats.Stats.
- Returns
an instance of pstats.Stats. If no profiling information was collected, this function will return
Noneinstead.- Return type
Optional[pstats.Stats]
- class seagrass.hooks.StackTraceHook(stack_depth: Optional[int] = 10)
-
An audit hook that captures the stack trace of where events are raised and collects statistics about caller locations.
- class seagrass.hooks.RuntimeAuditHook(sys_hook: Callable[[str, Tuple[Any, ...]], None], propagate_errors: Optional[bool] = None, traceable: bool = False)
Bases:
ProtoHook[Optional[str]]A hook that executes its body as a Python runtime audit hook, in accordance with PEP 578.
Note
RuntimeAuditHookis only supported for Python versions >= 3.8Examples: in the code below,
RuntimeEventCounterHookis a class derived from theRuntimeAuditHookbase class that prints every time a runtime audit event is triggered.>>> import sys >>> from seagrass.hooks import RuntimeAuditHook >>> class RuntimeEventCounterHook(RuntimeAuditHook): ... def __init__(self): ... super().__init__(self.sys_hook) ... ... def sys_hook(self, event, args): ... print(f"Encountered event={event!r} with args={args}") ... >>> hook = RuntimeEventCounterHook() >>> @auditor.audit("my_event", hooks=[hook]) ... def my_event(*args): ... sys.audit("sys.my_event", *args) >>> with auditor.start_auditing(): ... my_event(42, "hello, world") Encountered event='sys.my_event' with args=(42, 'hello, world')
- property is_active: bool
Return whether or not the hook is currently active (i.e., whether a Seagrass event that uses the hook is currently executing.)
- property current_event: Optional[str]
Returns the current Seagrass event being executed that’s hooked by this function. If no events using this hook are being executed,
current_eventisNone.
- __init__(sys_hook: Callable[[str, Tuple[Any, ...]], None], propagate_errors: Optional[bool] = None, traceable: bool = False) None
Initialize the RuntimeAuditHook.
- Parameters
propagate_errors (Optional[bool]) –
if not equal to
None, set thepropagate_errorsattribute of the hook, which controls whether errors raised bysys_hook()are propagated. Hooks for whichpropagate_errorsisFalsewill log errors raised bysys_hook(), but won’t raise them.By default,
hook.propagate_errors = Truefor RuntimeAuditHooks.
- prehook(event: str, args: Tuple[Any, ...], kwargs: Dict[str, Any]) Optional[str]
Run the prehook. The prehook is run at the beginning of the execution of an audited event, before the function wrapped by the event is run.
- Parameters
- Returns
“context” data that can be used by the posthook.
- Return type
C
- posthook(event: str, result: Any, context: Optional[str]) None
Run the posthook. The posthook is run at the end of the execution of an audited event, after the function wrapped by the event is run.
- Parameters
event_name (str) – The name of the event that was triggered.
result (Any) – The value that was returned by the event’s wrapped function.
context (C) – The context that was returned by the original call to
prehook.
- class seagrass.hooks.TimerHook
-
- prehook(event_name: str, args: Tuple[Any, ...], kwargs: Dict[str, Any]) float
Run the prehook. The prehook is run at the beginning of the execution of an audited event, before the function wrapped by the event is run.
- Parameters
- Returns
“context” data that can be used by the posthook.
- Return type
C
- posthook(event_name: str, result: Any, context: float) None
Run the posthook. The posthook is run at the end of the execution of an audited event, after the function wrapped by the event is run.
- Parameters
event_name (str) – The name of the event that was triggered.
result (Any) – The value that was returned by the event’s wrapped function.
context (C) – The context that was returned by the original call to
prehook.
- class seagrass.hooks.TracingHook(tracefunc: TraceFunc)
Bases:
CleanupHook[Tuple[Optional[str],Token,Token]]Seagrass hook wrapper for tracing functions.
Example: the code snippet below defines a new hook from
TracingHookthat checks each frame to see ifMY_VARis defined locally, and if it is, it recordsMY_VAR’s value.>>> import seagrass >>> from seagrass.hooks import TracingHook >>> def tracefunc(frame, event, arg): ... if "MY_VAR" in frame.f_locals: ... MY_VAR = frame.f_locals["MY_VAR"] ... logger = seagrass.get_audit_logger(None) ... if logger is not None: ... logger.info(f"Found MY_VAR={MY_VAR!r}") ... return tracefunc >>> hook = TracingHook(tracefunc) >>> @seagrass.audit(seagrass.auto, hooks=[hook]) ... def example(): ... MY_VAR = 100 ... MY_VAR = "hello, world!" >>> with seagrass.start_auditing(): ... example() {"message": "Found MY_VAR=100", "seagrass": {"event": "example"}, "level": "INFO"} {"message": "Found MY_VAR='hello, world!'", "seagrass": {"event": "example"}, "level": "INFO"}
- class TraceFunc(*args, **kwargs)
Bases:
ProtocolA tracing function set by
sys.settraceorthreading.settrace. The arguments to this function are the same as those to the function accepted bysys.settrace.- __init__(*args, **kwargs)
- __init__(tracefunc: TraceFunc) None
Create a new TracingHook.
- Parameters
tracefunc (TraceFunc) – the function that should be used to perform tracing via sys.settrace.
- property is_active: bool
Return whether or not the hook is currently active (i.e., whether a Seagrass event that uses the hook is currently executing.)
- static get_current_tracing_hook()
Get the current global tracing hook.
- prehook(event_name: str, args: Tuple[Any, ...], kwargs: Dict[str, Any]) Tuple[Optional[str], Token, Token]
Run the prehook. The prehook is run at the beginning of the execution of an audited event, before the function wrapped by the event is run.
- Parameters
- Returns
“context” data that can be used by the posthook.
- Return type
C
- cleanup(event_name: str, context: Tuple[Optional[str], Token, Token], exc: Tuple[Any, ...]) None
Perform the hook’s cleanup stage. The
event_nameandcontextare the same as those used by theposthookfunction. If an exception was thrown while executing the event it will be provided in theexceptionargument, otherwise,exceptionwill beNone.If
cleanupreturns a boolean value, that value is used to decide whether to suppress any exceptions that were raised during event execution.- Return type
Optional[bool]
- seagrass.hooks.get_hook_context(default: ~typing.Union[~seagrass.hooks._utils.T, ~seagrass._typing.Missing] = <seagrass._typing.Missing>) Union[HookContext, T]
Retrieve the logging context provided by an executing hook.
- Raises
LookupError – if no hook is currently being executed, and
defaultis not specified.