|
| 1 | +from dataclasses import dataclass |
| 2 | +from logfire._internal.constants import ATTRIBUTES_LOG_LEVEL_NUM_KEY as ATTRIBUTES_LOG_LEVEL_NUM_KEY, LEVEL_NUMBERS as LEVEL_NUMBERS, LevelName as LevelName, NUMBER_TO_LEVEL as NUMBER_TO_LEVEL, log_level_attributes as log_level_attributes |
| 3 | +from logfire._internal.tracer import get_parent_span as get_parent_span |
| 4 | +from logfire._internal.utils import canonicalize_exception_traceback as canonicalize_exception_traceback |
| 5 | +from opentelemetry.sdk.trace import ReadableSpan, Span |
| 6 | +from opentelemetry.util import types as otel_types |
| 7 | +from typing import Callable |
| 8 | + |
| 9 | +@dataclass |
| 10 | +class SpanLevel: |
| 11 | + """A convenience class for comparing span/log levels. |
| 12 | +
|
| 13 | + Can be compared to log level names (strings) such as 'info' or 'error' using |
| 14 | + `<`, `>`, `<=`, or `>=`, so e.g. `level >= 'error'` is valid. |
| 15 | +
|
| 16 | + Will raise an exception if compared to a non-string or an invalid level name. |
| 17 | + """ |
| 18 | + number: int |
| 19 | + @classmethod |
| 20 | + def from_span(cls, span: ReadableSpan) -> SpanLevel: |
| 21 | + """Create a SpanLevel from an OpenTelemetry span. |
| 22 | +
|
| 23 | + If the span has no level set, defaults to 'info'. |
| 24 | + """ |
| 25 | + @property |
| 26 | + def name(self) -> LevelName | None: |
| 27 | + """The human-readable name of the level, or `None` if the number is invalid.""" |
| 28 | + def __eq__(self, other: object): ... |
| 29 | + def __hash__(self): ... |
| 30 | + def __lt__(self, other: LevelName): ... |
| 31 | + def __gt__(self, other: LevelName): ... |
| 32 | + def __ge__(self, other: LevelName): ... |
| 33 | + def __le__(self, other: LevelName): ... |
| 34 | + |
| 35 | +@dataclass |
| 36 | +class ExceptionCallbackHelper: |
| 37 | + """Helper object passed to the exception callback. |
| 38 | +
|
| 39 | + This is experimental and may change significantly in future releases. |
| 40 | + """ |
| 41 | + span: Span |
| 42 | + exception: BaseException |
| 43 | + event_attributes: dict[str, otel_types.AttributeValue] |
| 44 | + @property |
| 45 | + def level(self) -> SpanLevel: |
| 46 | + """Convenient way to see and compare the level of the span. |
| 47 | +
|
| 48 | + - When using `logfire.span` or `logfire.exception`, this is usually `error`. |
| 49 | + - Spans created directly by an OpenTelemetry tracer (e.g. from any `logfire.instrument_*()` method) |
| 50 | + typically don't have a level set, so this will return the default of `info`, |
| 51 | + but `level_is_unset` will be `True`. |
| 52 | + - FastAPI/Starlette 4xx HTTPExceptions are warnings. |
| 53 | + - Will be a different level if this is created by e.g. `logfire.info(..., _exc_info=True)`. |
| 54 | + """ |
| 55 | + @level.setter |
| 56 | + def level(self, value: LevelName | int) -> None: |
| 57 | + """Override the level of the span. |
| 58 | +
|
| 59 | + For example: |
| 60 | +
|
| 61 | + helper.level = 'warning' |
| 62 | + """ |
| 63 | + @property |
| 64 | + def level_is_unset(self) -> bool: |
| 65 | + """Determine if the level has not been explicitly set on the span (yet). |
| 66 | +
|
| 67 | + For messy technical reasons, this is typically `True` for spans created directly by an OpenTelemetry tracer |
| 68 | + (e.g. from any `logfire.instrument_*()` method) |
| 69 | + although the level will usually still eventually be `error` by the time it's exported. |
| 70 | +
|
| 71 | + Spans created by `logfire.span()` get the level set to `error` immediately when an exception passes through, |
| 72 | + so this will be `False` in that case. |
| 73 | +
|
| 74 | + This is also typically `True` when calling `span.record_exception()` directly on any span |
| 75 | + instead of letting an exception bubble through. |
| 76 | + """ |
| 77 | + @property |
| 78 | + def parent_span(self) -> ReadableSpan | None: |
| 79 | + """The parent span of the span the exception was recorded on. |
| 80 | +
|
| 81 | + This is `None` if there is no parent span, or if the parent span is in a different process. |
| 82 | + """ |
| 83 | + @property |
| 84 | + def issue_fingerprint_source(self) -> str: |
| 85 | + """Returns a string that will be hashed to create the issue fingerprint. |
| 86 | +
|
| 87 | + By default this is a canonical representation of the exception traceback: |
| 88 | +
|
| 89 | + - The source line is used, but not the line number, so that changes elsewhere in a file are irrelevant. |
| 90 | + - The module is used instead of the filename. |
| 91 | + - The same line appearing multiple times in a stack is ignored. |
| 92 | + - Exception group sub-exceptions are sorted and deduplicated. |
| 93 | + - If the exception has a cause or (not suppressed) context, it is included in the representation. |
| 94 | + - Cause and context are treated as different. |
| 95 | + """ |
| 96 | + @issue_fingerprint_source.setter |
| 97 | + def issue_fingerprint_source(self, value: str): |
| 98 | + '''Override the string that will be hashed to create the issue fingerprint. |
| 99 | +
|
| 100 | + For example, if you want all exceptions of a certain type to be grouped into the same issue, |
| 101 | + you could do something like: |
| 102 | +
|
| 103 | + if isinstance(helper.exception, MyCustomError): |
| 104 | + helper.issue_fingerprint_source = "MyCustomError" |
| 105 | +
|
| 106 | + Or if you want to add the exception message to make grouping more granular: |
| 107 | +
|
| 108 | + helper.issue_fingerprint_source += str(helper.exception) |
| 109 | +
|
| 110 | + Note that setting this property automatically sets `create_issue` to True. |
| 111 | + ''' |
| 112 | + @property |
| 113 | + def create_issue(self) -> bool: |
| 114 | + '''Whether to create an issue for this exception. |
| 115 | +
|
| 116 | + By default, issues are only created for exceptions on spans where: |
| 117 | +
|
| 118 | + - The level is \'error\' or higher or is unset (see `level_is_unset` for details), |
| 119 | + - No parent span exists in the current process, |
| 120 | + - The exception isn\'t handled by FastAPI, except if it\'s a 5xx HTTPException. |
| 121 | +
|
| 122 | + Example: |
| 123 | + if helper.create_issue: |
| 124 | + helper.issue_fingerprint_source = "MyCustomError" |
| 125 | + ''' |
| 126 | + @create_issue.setter |
| 127 | + def create_issue(self, value: bool): |
| 128 | + """Override whether to create an issue for this exception. |
| 129 | +
|
| 130 | + For example, if you want to create issues for all exceptions, even warnings: |
| 131 | +
|
| 132 | + helper.create_issue = True |
| 133 | +
|
| 134 | + Issues can only be created if the exception is recorded on the span. |
| 135 | + """ |
| 136 | + def no_record_exception(self) -> None: |
| 137 | + """Call this method to prevent recording the exception on the span. |
| 138 | +
|
| 139 | + This improves performance and reduces noise in Logfire. |
| 140 | + This will also prevent creating an issue for this exception. |
| 141 | + The span itself will still be recorded, just without the exception information. |
| 142 | + This doesn't affect the level of the span, it will still be 'error' by default. |
| 143 | + To still record exception info without creating an issue, use `helper.create_issue = False` instead. |
| 144 | + To still record the exception info but at a different level, use `helper.level = 'warning'` |
| 145 | + or some other level instead. |
| 146 | + """ |
| 147 | +ExceptionCallback = Callable[[ExceptionCallbackHelper], None] |
0 commit comments