
    go{                      d dl mZ d dlZd dlZd dlZd dlZd dlZd dlmZ d dl	m	Z	 d dl
mZmZmZmZmZmZmZmZmZmZmZ d dlmZ d dlmZ d dlmZ d dlmZmZm Z m!Z! d dl"m#Z#m$Z$ d d	lm%Z%m&Z& d d
l'm(Z) d dl*m+Z+m,Z, ddl-m.Z. ddl/m0Z0 ddl1m2Z2m3Z3 ddl4m5Z5m6Z6 ddl7m8Z8 ddl9m:Z:m;Z;m<Z<m=Z=m>Z>m?Z?m@Z@mAZAmBZBmCZCmDZDmEZEmFZF ddlGmHZHmIZI ddlJmJZJ ddlKmLZL ddlMmNZNmOZOmPZPmQZQ ddlRmSZS ddlTmUZU ddlVmWZWmXZXmYZY ddlZm[Z[m\Z\m]Z]m^Z^ erd dl(m_Z_ d dl`maZa d dlbZbd dlcZcd dldZdd dleZed dlfmgZgmhZh d dlimjZj d d lkmlZl d d!lmmnZnmoZompZp d d"lmqZr d d#lsmtZtmuZumvZv d d$lwmxZx d d%lymzZz d d&l{m|Z| d d'l}m~Z~ d d(lmZ d d)l*mZ dd*lmZmZmZ dd+lmZmZmZmZ dd,lmZ dd-lmZmZ dd,lmZ dd-lmZmZ dd.lmZmZ dd/lmZmZ dd0lmZ dd1lmZmZ dd2lmZ dd3lmZmZ dd4lZmZ eeeedf   Z G d5 d6      Z G d7 d8      Z G d9 d:e#      Z G d; d<      Z ed=eee)jf                  f   >      ZdDd?Z	 	 	 	 	 	 	 	 dEd@ZdFdAZ e,dB      Z edC      Zy)G    )annotationsN)cached_property)time)TYPE_CHECKINGAnyCallableContextManagerIterableLiteralSequenceTypeVarUnioncastoverload)Context)	CallbackTCounter	HistogramUpDownCounter)ReadableSpanSpan)SpanContextTracer)types)LiteralString	ParamSpec   )VERSION   )async_)AutoTraceModuleinstall_auto_tracing)GLOBAL_CONFIGLogfireConfig)PydanticPluginRecordValues)ATTRIBUTES_JSON_SCHEMA_KEYATTRIBUTES_LOG_LEVEL_NUM_KEYATTRIBUTES_MESSAGE_KEYATTRIBUTES_MESSAGE_TEMPLATE_KEYATTRIBUTES_SAMPLE_RATE_KEYATTRIBUTES_SPAN_TYPE_KEYATTRIBUTES_TAGS_KEYDISABLE_CONSOLE_KEYLEVEL_NUMBERSNULL_ARGS_KEYOTLP_MAX_INT_SIZE	LevelNamelog_level_attributes)logfire_formatlogfire_format_with_magic)
instrument)logfire_json_dumps)JsonSchemaPropertiesattributes_json_schema!attributes_json_schema_propertiescreate_json_schema)ProxyMeterProvider)get_user_stack_info)ProxyTracerProviderrecord_exceptionset_exception_status)get_versionhandle_internal_errorslog_internal_erroruniquify_sequence)
ModuleType)WSGIApplication)HttpRequestHttpResponse)FastAPI)Flask)ClientRequestHookClientResponseHookServerRequestHook)_Gauge)CommandFailedEventCommandStartedEventCommandSucceededEvent)Engine)AsyncEngine)	Starlette)Request)	WebSocket)Unpack)CommenterOptionsRequestHookResponseHook)AsyncRequestHookAsyncResponseHookrX   rY   )rW   )rX   rY   )ASGIAppASGIInstrumentKwargs)LambdaEventLambdaHandler)MySQLConnection)Psycopg2ConnectionPsycopgConnection)SQLite3Connection)BaseConfig)
SysExcInfoc                     e Zd ZdZeddddd	 	 	 	 	 	 	 	 	 	 	 dYdZedZd       Zed[d	       Z	ed\d
       Z
ed        Zed]d       Zed]d       Zd^dZddddd	 	 	 	 	 	 	 	 	 	 	 	 	 d_dZd`dZ	 	 	 	 	 	 	 	 dadZddd	 	 	 	 	 	 	 	 	 dbdZddd	 	 	 	 	 	 	 	 	 dbdZddd	 	 	 	 	 	 	 	 	 dbdZddd	 	 	 	 	 	 	 	 	 dbdZddd	 	 	 	 	 	 	 	 	 dbdZddd	 	 	 	 	 	 	 	 	 dbdZddd	 	 	 	 	 	 	 	 	 dbdZddd	 	 	 	 	 	 	 	 	 dbdZddddd	 	 	 	 	 	 	 	 	 	 	 	 	 dcdZe	 dddddd	 	 	 	 	 	 	 	 	 ded       Zedfd        Z	 dddddd	 	 	 	 	 	 	 	 	 dgd!Z	 	 	 	 dh	 	 	 	 	 	 	 	 	 	 	 	 	 did"Zdjd#Zdkd$Zddddd%	 	 	 	 	 	 	 	 	 dld&Z dmdnd'Z!dodpd(Z"d)d*	 	 	 	 	 	 	 dqd+Z#d, Z$	 	 	 dr	 	 	 	 	 	 	 dsd-Z%ddddd.	 	 	 	 	 	 	 	 	 	 	 	 	 dtd/Z&	 dddd0	 	 	 	 	 dud1Z'	 dddd0	 	 	 	 	 dvd2Z(dwd3Z)eddddddd4	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dxd5       Z*eddddddd4	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dyd6       Z*e	 ddddddddddd7	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dzd8       Z*	 ddddddddddd7	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d{d9Z*dwd:Z+	 	 	 	 	 d|	 	 	 	 	 	 	 	 	 	 	 	 	 d}d;Z,	 	 	 d~	 	 	 	 	 	 	 	 	 dd<Z-edd=       Z.e	 	 	 d	 	 	 	 	 	 	 	 	 dd>       Z.	 	 	 d	 	 	 	 	 	 	 	 	 dd?Z.ddddddd@	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 ddAZ/ddddddB	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 ddCZ0	 	 d	 	 	 	 	 	 	 	 	 ddDZ1	 	 	 d	 	 	 	 	 	 	 	 	 	 	 ddEZ2dwdFZ3	 	 	 d	 	 	 	 	 	 	 	 	 ddGZ4ddddHZ5	 dd	 	 	 	 	 	 	 ddIZ6	 	 	 	 d	 	 	 	 	 	 	 	 	 	 	 ddJZ7	 	 	 d	 	 	 	 	 	 	 	 	 ddKZ8ddddLZ9	 d	 	 	 	 	 ddMZ:dNdNdOddPZ;dNdNdOddQZ<dNdNdOddRZ=dNdNdOddSZ>dNdNdO	 	 	 	 	 	 	 	 	 ddTZ?dNdNdO	 	 	 	 	 	 	 	 	 ddUZ@dNdNdO	 	 	 	 	 	 	 	 	 ddVZAddWZBdddXZCy)LogfirezThe main logfire class.N Tlogfire)configsample_ratetagsconsole_log
otel_scopec               \    t        |      | _        || _        || _        || _        || _        y N)tuple_tags_config_sample_rate_console_log_otel_scope)selfrk   rl   rm   rn   ro   s         K/var/www/openai/venv/lib/python3.12/site-packages/logfire/_internal/main.py__init__zLogfire.__init__{   s.     4[
''%    c                    | j                   S rq   )rt   rx   s    ry   rk   zLogfire.config   s    ||r{   c                l    | j                   j                  d       | j                   j                         S )Nz No logs or spans will be created)rt   warn_if_not_initializedget_tracer_providerr}   s    ry   _tracer_providerzLogfire._tracer_provider   s(    ,,-OP||//11r{   c                6    | j                   j                         S rq   )rt   get_meter_providerr}   s    ry   _meter_providerzLogfire._meter_provider   s    ||..00r{   c                V    | j                   j                  | j                  t              S rq   )r   	get_meterrw   r   r}   s    ry   _meterzLogfire._meter   s!    ##--d.>.>HHr{   c                &    | j                  d      S )NFis_span_tracer_get_tracerr}   s    ry   _logs_tracerzLogfire._logs_tracer   s    u55r{   c                &    | j                  d      S )NTr   r   r}   s    ry   _spans_tracerzLogfire._spans_tracer   s    t44r{   c               Z    | j                   j                  | j                  t        |      S )Nr   )r   
get_tracerrw   r   )rx   r   s     ry   r   zLogfire._get_tracer   s/    $$//) 0 
 	
r{   rs   
_span_name_level_linksc               :   	 t               }i ||}| j                  j                  rt        j                         j
                  }	nd }	t        ||| j                  j                  |	      \  }
}}|j                  |       |j                  |       ||t        <   |
|t        <   t        |      }t        |      x}rt        |      |t        <   | j                  xs dt!        |xs d      z   }|rt#        |      |t$        <   | j&                  | j&                  n|j)                  t*        d       }||dk7  r	||t*        <   ||j                  t-        |             t/        |xs ||| j0                  ||      S # t2        $ r t5                t7               cY S w xY w)Nfstring_frameri   r   )links)r<   rt   inspect_argumentsinspectcurrentframef_backr4   scrubberupdater)   r(   prepare_otlp_attributesr9   r8   r&   rs   rr   rC   r,   ru   popr*   r2   LogfireSpanr   	ExceptionrB   NoopSpan)rx   msg_template
attributesrs   r   r   r   
stack_infomerged_attributesr   log_messageextra_attrsotlp_attributesjson_schema_propertiesrm   rl   s                   ry   _spanzLogfire._span   s   1	,.J <: < <||-- ' 4 4 6 = = $5N!%%+	62Kl $$[1k*AM=>8C4556GHO)J:)VV%V>TUk>l :;JJ$"ekr(::D7H7N 34 $$0 !!$(()CTJ 
 &;!+;>I :;!&&';F'CD*l""&   	 :	s   E7E: :FFc                    	 | j                   j                  ||      }t        |      S # t        $ r t	                t               cY S w xY w)zA simple version of `_span` optimized for auto-tracing that doesn't support message formatting.

        Returns a similarly simplified version of `LogfireSpan` which must immediately be used as a context manager.
        )namer   )r   
start_spanFastLogfireSpanr   rB   r   )rx   r   r   spans       ry   
_fast_spanzLogfire._fast_span   sJ    
	%%00dz0RD"4(( 	 :	s   '* A
	A
c                B   	 |t            }t        ||| j                  j                        |t        <   t        |      x}rt        |      |t        <   |j                  t        |             | j                  ||      S # t        $ r t                t               cY S w xY w)zA version of `_span` used by `@instrument` with `extract_args=True`.

        This is a bit faster than `_span` but not as fast as `_fast_span` because it supports message formatting
        and arbitrary types of attributes.
        )r)   r3   rt   r   r(   r9   r8   r&   r   r   r   r   rB   r   )rx   r   r   function_argsr   r   s         ry   _instrument_span_with_argsz"Logfire._instrument_span_with_args   s    		 *+J KL1?m]a]i]i]r]r1sJ-.)J=)YY%Y9OPf9g
565mDE??444 	 :	s   A;A> >BBF)rs   	_exc_infoc              j    t        d |D              rt        d      | j                  d||||       y)aB  Log a trace message.

        ```py
        import logfire

        logfire.configure()

        logfire.trace('This is a trace log')
        ```

        Args:
            msg_template: The message to log.
            attributes: The attributes to bind to the log.
            _tags: An optional sequence of tags to include in the log.
            _exc_info: Set to an exception or a tuple as returned by [`sys.exc_info()`][sys.exc_info]
                to record a traceback with the log message.

                Set to `True` to use the currently handled exception.
        c              3  >   K   | ]  }|j                  d         yw_N
startswith.0ks     ry   	<genexpr>z Logfire.trace.<locals>.<genexpr>#       5*Qq||C *   /Attribute keys cannot start with an underscore.tracerm   exc_infoNany
ValueErrorlogrx   r   rs   r   r   s        ry   r   zLogfire.trace  4    8 5*55NOO,
Sr{   c              j    t        d |D              rt        d      | j                  d||||       y)aB  Log a debug message.

        ```py
        import logfire

        logfire.configure()

        logfire.debug('This is a debug log')
        ```

        Args:
            msg_template: The message to log.
            attributes: The attributes to bind to the log.
            _tags: An optional sequence of tags to include in the log.
            _exc_info: Set to an exception or a tuple as returned by [`sys.exc_info()`][sys.exc_info]
                to record a traceback with the log message.

                Set to `True` to use the currently handled exception.
        c              3  >   K   | ]  }|j                  d         ywr   r   r   s     ry   r   z Logfire.debug.<locals>.<genexpr>C  r   r   r   debugr   Nr   r   s        ry   r   zLogfire.debug'  r   r{   c              j    t        d |D              rt        d      | j                  d||||       y)aA  Log an info message.

        ```py
        import logfire

        logfire.configure()

        logfire.info('This is an info log')
        ```

        Args:
            msg_template: The message to log.
            attributes: The attributes to bind to the log.
            _tags: An optional sequence of tags to include in the log.
            _exc_info: Set to an exception or a tuple as returned by [`sys.exc_info()`][sys.exc_info]
                to record a traceback with the log message.

                Set to `True` to use the currently handled exception.
        c              3  >   K   | ]  }|j                  d         ywr   r   r   s     ry   r   zLogfire.info.<locals>.<genexpr>c  r   r   r   infor   Nr   r   s        ry   r   zLogfire.infoG  4    8 5*55NOOz	Rr{   c              j    t        d |D              rt        d      | j                  d||||       y)aE  Log a notice message.

        ```py
        import logfire

        logfire.configure()

        logfire.notice('This is a notice log')
        ```

        Args:
            msg_template: The message to log.
            attributes: The attributes to bind to the log.
            _tags: An optional sequence of tags to include in the log.
            _exc_info: Set to an exception or a tuple as returned by [`sys.exc_info()`][sys.exc_info]
                to record a traceback with the log message.

                Set to `True` to use the currently handled exception.
        c              3  >   K   | ]  }|j                  d         ywr   r   r   s     ry   r   z!Logfire.notice.<locals>.<genexpr>  r   r   r   noticer   Nr   r   s        ry   r   zLogfire.noticeg  s4    8 5*55NOO<%)Tr{   c              j    t        d |D              rt        d      | j                  d||||       y)aE  Log a warning message.

        ```py
        import logfire

        logfire.configure()

        logfire.warn('This is a warning log')
        ```

        Args:
            msg_template: The message to log.
            attributes: The attributes to bind to the log.
            _tags: An optional sequence of tags to include in the log.
            _exc_info: Set to an exception or a tuple as returned by [`sys.exc_info()`][sys.exc_info]
                to record a traceback with the log message.

                Set to `True` to use the currently handled exception.
        c              3  >   K   | ]  }|j                  d         ywr   r   r   s     ry   r   zLogfire.warn.<locals>.<genexpr>  r   r   r   warnr   Nr   r   s        ry   r   zLogfire.warn  r   r{   c              j    t        d |D              rt        d      | j                  d||||       y)aD  Log an error message.

        ```py
        import logfire

        logfire.configure()

        logfire.error('This is an error log')
        ```

        Args:
            msg_template: The message to log.
            attributes: The attributes to bind to the log.
            _tags: An optional sequence of tags to include in the log.
            _exc_info: Set to an exception or a tuple as returned by [`sys.exc_info()`][sys.exc_info]
                to record a traceback with the log message.

                Set to `True` to use the currently handled exception.
        c              3  >   K   | ]  }|j                  d         ywr   r   r   s     ry   r   z Logfire.error.<locals>.<genexpr>  r   r   r   errorr   Nr   r   s        ry   r   zLogfire.error  r   r{   c              j    t        d |D              rt        d      | j                  d||||       y)aB  Log a fatal message.

        ```py
        import logfire

        logfire.configure()

        logfire.fatal('This is a fatal log')
        ```

        Args:
            msg_template: The message to log.
            attributes: The attributes to bind to the log.
            _tags: An optional sequence of tags to include in the log.
            _exc_info: Set to an exception or a tuple as returned by [`sys.exc_info()`][sys.exc_info]
                to record a traceback with the log message.

                Set to `True` to use the currently handled exception.
        c              3  >   K   | ]  }|j                  d         ywr   r   r   s     ry   r   z Logfire.fatal.<locals>.<genexpr>  r   r   r   fatalr   Nr   r   s        ry   r   zLogfire.fatal  r   r{   c              j    t        d |D              rt        d      | j                  d||||       y)a  The same as `error` but with `_exc_info=True` by default.

        This means that a traceback will be logged for any currently handled exception.

        Args:
            msg_template: The message to log.
            attributes: The attributes to bind to the log.
            _tags: An optional sequence of tags to include in the log.
            _exc_info: Set to an exception or a tuple as returned by [`sys.exc_info()`][sys.exc_info]
                to record a traceback with the log message.
        c              3  >   K   | ]  }|j                  d         ywr   r   r   s     ry   r   z$Logfire.exception.<locals>.<genexpr>  r   r   r   r   r   Nr   r   s        ry   	exceptionzLogfire.exception  s4    ( 5*55NOO,
Sr{   c              j    t        d |D              rt        d      | j                  ||||||      S )a   Context manager for creating a span.

        ```py
        import logfire

        logfire.configure()

        with logfire.span('This is a span {a=}', a='data'):
            logfire.info('new log 1')
        ```

        Args:
            msg_template: The template for the span message.
            _span_name: The span name. If not provided, the `msg_template` will be used.
            _tags: An optional sequence of tags to include in the span.
            _level: An optional log level name.
            _links: An optional sequence of links to other spans. Each link is a tuple of a span context and attributes.
            attributes: The arguments to include in the span and format the message template with.
                Attributes starting with an underscore are not allowed.
        c              3  >   K   | ]  }|j                  d         ywr   r   r   s     ry   r   zLogfire.span.<locals>.<genexpr>  r   r   r   r   )r   r   r   )rx   r   rs   r   r   r   r   s          ry   r   zLogfire.span  sF    > 5*55NOOzz!  
 	
r{   )	span_nameextract_argsallow_generatorc                    y)  Decorator for instrumenting a function as a span.

        ```py
        import logfire

        logfire.configure()


        @logfire.instrument('This is a span {a=}')
        def my_function(a: int):
            logfire.info('new log {a=}', a=a)
        ```

        Args:
            msg_template: The template for the span message. If not provided, the module and function name will be used.
            span_name: The span name. If not provided, the `msg_template` will be used.
            extract_args: By default, all function call arguments are logged as span attributes.
                Set to `False` to disable this, or pass an iterable of argument names to include.
            allow_generator: Set to `True` to prevent a warning when instrumenting a generator function.
                Read https://logfire.pydantic.dev/docs/guides/advanced/generators/#using-logfireinstrument first.
        Nri   rx   r   r   r   r   s        ry   r5   zLogfire.instrument)      r{   c                     y)a  Decorator for instrumenting a function as a span, with default configuration.

        ```py
        import logfire

        logfire.configure()


        @logfire.instrument
        def my_function(a: int):
            logfire.info('new log {a=}', a=a)
        ```
        Nri   )rx   funcs     ry   r5   zLogfire.instrumentH  r   r{   c                   t        |      r | j                         |      S t        | t        | j                        ||||      S )r   )callabler5   rr   rs   r   s        ry   r5   zLogfire.instrumentX  s?    : L!$4??$\22$djj 1<LZijjr{   c                   t               5  t               }|xs i }i ||}|j                  t        d      x}	d}
| j                  j
                  ret        j                         }
|
j                  j                  j                  t        j                  j                  j                  k(  r|
j                  }
t        ||| j                  j                  |
      \  }	}}|r7|j!                  |       i ||}nt#        |	      x}	|t        <   t#        |      }t%        |      }t&        dit)        |      t*        |t        |	i|}t-        |      x}rt/        |      |t0        <   | j2                  t5        |xs d      z   }|rt7        |      |t8        <   | j:                  | j:                  n|j                  t<        d      }||dk7  r	||t<        <   || j>                  sn|s	d|t@        <   | j                  jB                  jE                         }| jF                  jI                  |||      }|r|du rtK        jL                         }tO        |t4              r|d   }tO        |tP              r,tS        ||       |tT           tV        d   k\  r1tY        ||       n$|"t[        d	|j\                  j^                         |ja                  |       ddd       y# 1 sw Y   yxY w)
a  Log a message.

        ```py
        import logfire

        logfire.configure()

        logfire.log('info', 'This is a log {a}', {'a': 'Apple'})
        ```

        Args:
            level: The level of the log.
            msg_template: The message to log.
            attributes: The attributes to bind to the log.
            tags: An optional sequence of tags to include in the log.
            exc_info: Set to an exception or a tuple as returned by [`sys.exc_info()`][sys.exc_info]
                to record a traceback with the log message.

                Set to `True` to use the currently handled exception.
            console_log: Whether to log to the console, defaults to `True`.
        Nr   r   ri   r   T)r   
start_timer   zInvalid type for exc_info: )1rA   r<   r   r(   rt   r   r   r   r   f_codeco_filenamerh   r   __code__r4   r   r   strr   r+   r2   r)   r9   r8   r&   rs   rr   rC   r,   ru   r*   rv   r-   advancedns_timestamp_generatorr   r   sysr   
isinstanceBaseExceptionr>   r'   r.   r?   	TypeError	__class____name__end)rx   levelr   r   rm   r   rn   r   r   msgr   r   r   r   rl   r   r   s                    ry   r   zLogfire.logy  s   < $%,.J#)rJ <: < <!~~&<dCCL $<<11$+$8$8$:M$++22>>'++BVBVBbBbb )6(<(<1J %LL))"/	2.[, %,,[9 "?J!>+!>J CFc(J'(>?"<056GHO(%&u- 0&	
 "O *K:)VV%V>TUk>l :;::djb 11D7H7N 34 $$0 !!$(()CTJ 
 &;!+;>I :;)4)<D%%+7; 34..EEGJ$$//*% 0 D t#"||~Hh.'{Hh6$T84&'CDV]H^^ -T8<)#&A(BTBTB]B]A^$_``HHZ _ &%%s   KKK c                &    | j                  |      S )a  A new Logfire instance which always uses the given tags.

        ```py
        import logfire

        logfire.configure()

        local_logfire = logfire.with_tags('tag1')
        local_logfire.info('a log message', _tags=['tag2'])

        # This is equivalent to:
        logfire.info('a log message', _tags=['tag1', 'tag2'])
        ```

        Args:
            tags: The tags to add.

        Returns:
            A new Logfire instance with the `tags` added to any existing tags.
        )rm   )with_settings)rx   rm   s     ry   	with_tagszLogfire.with_tags  s    * !!t!,,r{   c                p    |dkD  s|dk  rt        d      t        | j                  | j                  |      S )zA new Logfire instance with the given sampling ratio applied.

        Args:
            sample_rate: The sampling ratio to use.

        Returns:
            A new Logfire instance with the sampling ratio applied.
        r   r   z#sample_rate must be between 0 and 1)rk   rm   rl   )r   rh   rt   rs   )rx   rl   s     ry   with_trace_sample_ratezLogfire.with_trace_sample_rate  s;     ?kAoBCC<<#
 	
r{   )rm   stack_offsetrn   custom_scope_suffixc                   t        | j                  | j                  t        |      z   | j                  || j
                  n||| j                        S d|       S )a  A new Logfire instance which uses the given settings.

        Args:
            tags: Sequence of tags to include in the log.
            stack_offset: The stack level offset to use when collecting stack info, also affects the warning which
                message formatting might emit, defaults to `0` which means the stack info will be collected from the
                position where [`logfire.log`][logfire.Logfire.log] was called.
            console_log: Whether to log to the console, defaults to `True`.
            custom_scope_suffix: A custom suffix to append to `logfire.` e.g. `logfire.loguru`.

                It should only be used when instrumenting another library with Logfire, such as structlog or loguru.

                See the `instrumenting_module_name` parameter on
                [TracerProvider.get_tracer][opentelemetry.sdk.trace.TracerProvider.get_tracer] for more info.

        Returns:
            A new Logfire instance with the given settings applied.
        zlogfire.)rk   rm   rl   rn   ro   )rh   rt   rs   rr   ru   rv   rw   )rx   rm   r  rn   r  s        ry   r  zLogfire.with_settings  si    6 <<eDk)))-8-@))k+>+Ft''
 	

 OWWjVkLl
 	
r{   c                8    | j                   j                  |      S )zForce flush all spans and metrics.

        Args:
            timeout_millis: The timeout in milliseconds.

        Returns:
            Whether the flush of spans was successful.
        )rt   force_flush)rx   timeout_milliss     ry   r  zLogfire.force_flush3  s     ||''77r{   c                .    t        j                  | |      S )a  Log a warning whenever a function running in the asyncio event loop blocks for too long.

        This works by patching the `asyncio.events.Handle._run` method.

        Args:
            slow_duration: the threshold in seconds for when a callback is considered slow.

        Returns:
            A context manager that will revert the patch when exited.
                This context manager doesn't take into account threads or other concurrency.
                Calling this method will immediately apply the patch
                without waiting for the context manager to be opened,
                i.e. it's not necessary to use this as a context manager.
        )r    log_slow_callbacks)rx   slow_durations     ry   log_slow_async_callbacksz Logfire.log_slow_async_callbacks>  s     ((}==r{   r   )check_imported_modulesc               "    t        | |||       y)a;  Install automatic tracing.

        See the [Auto-Tracing guide](https://logfire.pydantic.dev/docs/guides/onboarding_checklist/add_auto_tracing/)
        for more info.

        This will trace all non-generator function calls in the modules specified by the modules argument.
        It's equivalent to wrapping the body of every function in matching modules in `with logfire.span(...):`.

        !!! note
            This function MUST be called before any of the modules to be traced are imported.

            Generator functions will not be traced for reasons explained [here](https://logfire.pydantic.dev/docs/guides/advanced/generators/).

        This works by inserting a new meta path finder into `sys.meta_path`, so inserting another finder before it
        may prevent it from working.

        It relies on being able to retrieve the source code via at least one other existing finder in the meta path,
        so it may not work if standard finders are not present or if the source code is not available.
        A modified version of the source code is then compiled and executed in place of the original module.

        Args:
            modules: List of module names to trace, or a function which returns True for modules that should be traced.
                If a list is provided, any submodules within a given module will also be traced.
            min_duration: A minimum duration in seconds for which a function must run before it's traced.
                Setting to `0` causes all functions to be traced from the beginning.
                Otherwise, the first time(s) each function is called, it will be timed but not traced.
                Only after the function has run for at least `min_duration` will it be traced in subsequent calls.
            check_imported_modules: If this is `'error'` (the default), then an exception will be raised if any of the
                modules in `sys.modules` (i.e. modules that have already been imported) match the modules to trace.
                Set to `'warn'` to issue a warning instead, or `'ignore'` to skip the check.
        )r  min_durationN)r"   )rx   modulesr  r  s       ry   r"   zLogfire.install_auto_tracingO  s    L 	T7CYhtur{   c                :    | j                   j                  d       y )Nz#Instrumentation will have no effect)rk   r   r}   s    ry   ,_warn_if_not_initialized_for_instrumentationz4Logfire._warn_if_not_initialized_for_instrumentationw  s    ++,QRr{   c           	        |dk7  r0ddl }t        |j                        t        d      k  rt        d      ddlm}m} t        |t              r|h}t        |t              r|h} | ||t        |      t        |                   y)a  Instrument Pydantic model validations.

        This must be called before defining and importing the model classes you want to instrument.
        See the [Pydantic integration guide](https://logfire.pydantic.dev/docs/integrations/pydantic/) for more info.

        Args:
            record: The record mode for the Pydantic plugin. It can be one of the following values:

                - `all`: Send traces and metrics for all events. This is default value.
                - `failure`: Send metrics for all validations and traces only for validation failures.
                - `metrics`: Send only metrics.
                - `off`: Disable instrumentation.
            include:
                By default, third party modules are not instrumented. This option allows you to include specific modules.
            exclude:
                Exclude specific modules from instrumentation.
        offr   Nz2.5.0z5The Pydantic plugin requires Pydantic 2.5.0 or newer.)PydanticPluginset_pydantic_plugin_config)recordincludeexclude)
pydanticr@   __version__RuntimeErrorlogfire.integrations.pydanticr  r  r   r   set)rx   r  r  r  r  r  r  s          ry   instrument_pydanticzLogfire.instrument_pydanticz  sz    4 U?8//0;w3GG"#Z[[\gs#iGgs#iG 	#GG	
r{   capture_headersrequest_attributes_mapperexcluded_urlsrecord_send_receivec               L    ddl m} | j                           || |f||||d|S )a
  Instrument a FastAPI app so that spans and logs are automatically created for each request.

        Uses the [OpenTelemetry FastAPI Instrumentation](https://opentelemetry-python-contrib.readthedocs.io/en/latest/instrumentation/fastapi/fastapi.html)
        under the hood, with some additional features.

        Args:
            app: The FastAPI app to instrument.
            capture_headers: Set to `True` to capture all request and response headers.
            request_attributes_mapper: A function that takes a [`Request`][fastapi.Request] or [`WebSocket`][fastapi.WebSocket]
                and a dictionary of attributes and returns a new dictionary of attributes.
                The input dictionary will contain:

                - `values`: A dictionary mapping argument names of the endpoint function to parsed and validated values.
                - `errors`: A list of validation errors for any invalid inputs.

                The returned dictionary will be used as the attributes for a log message.
                If `None` is returned, no log message will be created.

                You can use this to e.g. only log validation errors, or nothing at all.
                You can also add custom attributes.

                The default implementation will return the input dictionary unchanged.
                The function mustn't modify the contents of `values` or `errors`.
            excluded_urls: A string of comma-separated regexes which will exclude a request from tracing if the full URL
                matches any of the regexes. This applies to both the Logfire and OpenTelemetry instrumentation.
                If not provided, the environment variables
                `OTEL_PYTHON_FASTAPI_EXCLUDED_URLS` and `OTEL_PYTHON_EXCLUDED_URLS` will be checked.
            record_send_receive: Set to `True` to allow the OpenTelemetry ASGI middleware to create send/receive spans.

                These are disabled by default to reduce overhead and the number of spans created,
                since many can be created for a single request, and they are not often useful.
                If enabled, they will be set to debug level, meaning they will usually still be hidden in the UI.
            opentelemetry_kwargs: Additional keyword arguments to pass to the OpenTelemetry FastAPI instrumentation.

        Returns:
            A context manager that will revert the instrumentation when exited.
                This context manager doesn't take into account threads or other concurrency.
                Calling this method will immediately apply the instrumentation
                without waiting for the context manager to be opened,
                i.e. it's not necessary to use this as a context manager.
        r   )instrument_fastapir$  )integrations.fastapir*  r  )rx   appr%  r&  r'  r(  opentelemetry_kwargsr*  s           ry   r*  zLogfire.instrument_fastapi  sD    t 	=99;!
 ,&?' 3
 #
 	
r{   )suppress_other_instrumentationc          	         ddl }ddlm} ddlm}m}m} | j                           || |xs |j                  |j                  f|d|||      S )u  Instrument an OpenAI client so that spans are automatically created for each request.

        The following methods are instrumented for both the sync and the async clients:

        - [`client.chat.completions.create`](https://platform.openai.com/docs/guides/text-generation/chat-completions-api) — with and without `stream=True`
        - [`client.completions.create`](https://platform.openai.com/docs/guides/text-generation/completions-api) — with and without `stream=True`
        - [`client.embeddings.create`](https://platform.openai.com/docs/guides/embeddings/how-to-get-embeddings)
        - [`client.images.generate`](https://platform.openai.com/docs/guides/images/generations)

        When `stream=True` a second span is created to instrument the streamed response.

        Example usage:

        ```python
        import logfire
        import openai

        client = openai.OpenAI()
        logfire.configure()
        logfire.instrument_openai(client)

        response = client.chat.completions.create(
            model='gpt-4',
            messages=[
                {'role': 'system', 'content': 'You are a helpful assistant.'},
                {'role': 'user', 'content': 'What is four plus five?'},
            ],
        )
        print('answer:', response.choices[0].message.content)
        ```

        Args:
            openai_client: The OpenAI client or class to instrument:

                - `None` (the default) to instrument both the `openai.OpenAI` and `openai.AsyncOpenAI` classes.
                - The `openai.OpenAI` class or a subclass
                - The `openai.AsyncOpenAI` class or a subclass
                - An instance of `openai.OpenAI`
                - An instance of `openai.AsyncOpenAI`

            suppress_other_instrumentation: If True, suppress any other OTEL instrumentation that may be otherwise
                enabled. In reality, this means the HTTPX instrumentation, which could otherwise be called since
                OpenAI uses HTTPX to make HTTP requests.

        Returns:
            A context manager that will revert the instrumentation when exited.
                Use of this context manager is optional.
        r   Nr   instrument_llm_providerget_endpoint_configis_async_clienton_responseOpenAI)
openai'integrations.llm_providers.llm_providerr1  !integrations.llm_providers.openair3  r4  r5  r  r6  AsyncOpenAI)rx   openai_clientr.  r7  r1  r3  r4  r5  s           ry   instrument_openaizLogfire.instrument_openai  sS    t 	Thh99;&@fmmV-?-?@*
 	
r{   c          	         ddl }ddlm}m}m} ddlm} | j                           || |xs. |j                  |j                  |j                  |j                  f|d|||      S )a  Instrument an Anthropic client so that spans are automatically created for each request.

        The following methods are instrumented for both the sync and async clients:

        - [`client.messages.create`](https://docs.anthropic.com/en/api/messages)
        - [`client.messages.stream`](https://docs.anthropic.com/en/api/messages-streaming)
        - [`client.beta.tools.messages.create`](https://docs.anthropic.com/en/docs/tool-use)

        When `stream=True` a second span is created to instrument the streamed response.

        Example usage:

        ```python
        import logfire
        import anthropic

        client = anthropic.Anthropic()

        logfire.configure()
        logfire.instrument_anthropic(client)

        response = client.messages.create(
            model='claude-3-haiku-20240307',
            system='You are a helpful assistant.',
            messages=[
                {'role': 'user', 'content': 'What is four plus five?'},
            ],
        )
        print('answer:', response.content[0].text)
        ```

        Args:
            anthropic_client: The Anthropic client or class to instrument:
                - `None` (the default) to instrument all Anthropic client types
                - The `anthropic.Anthropic` or `anthropic.AnthropicBedrock` class or subclass
                - The `anthropic.AsyncAnthropic` or `anthropic.AsyncAnthropicBedrock` class or subclass
                - An instance of any of the above classes

            suppress_other_instrumentation: If True, suppress any other OTEL instrumentation that may be otherwise
                enabled. In reality, this means the HTTPX instrumentation, which could otherwise be called since
                OpenAI uses HTTPX to make HTTP requests.

        Returns:
            A context manager that will revert the instrumentation when exited.
                Use of this context manager is optional.
        r   Nr   r2  r0  	Anthropic)	anthropic$integrations.llm_providers.anthropicr3  r4  r5  r8  r1  r  r>  AsyncAnthropicAnthropicBedrockAsyncAnthropicBedrock)rx   anthropic_clientr.  r?  r3  r4  r5  r1  s           ry   instrument_anthropiczLogfire.instrument_anthropic<  so    | 	kkT99;& ##((**//	 +
 	
r{   c                    ddl m} | j                           |di | j                  j	                         | j                  j                         d|S )zWInstrument the `asyncpg` module so that spans are automatically created for each query.r   )instrument_asyncpgtracer_providermeter_providerri   )integrations.asyncpgrG  r  rt   r   r   )rx   kwargsrG  s      ry   rG  zLogfire.instrument_asyncpg  sR    <99;! 
#'<<#C#C#E"&,,"A"A"C 
 	
r{   )capture_allr%  capture_request_bodycapture_response_bodyrequest_hookresponse_hookc                    y rq   ri   	rx   clientrM  r%  rN  rO  rP  rQ  rL  s	            ry   instrument_httpxzLogfire.instrument_httpx       r{   c                    y rq   ri   rS  s	            ry   rU  zLogfire.instrument_httpx  rV  r{   rM  r%  rN  rO  rP  rQ  async_request_hookasync_response_hookc                    y rq   ri   )rx   rT  rM  r%  rN  rO  rP  rQ  rY  rZ  rL  s              ry   rU  zLogfire.instrument_httpx  s     r{   c               T    ddl m} | j                           || |f||||||||	d|
S )a  Instrument the `httpx` module so that spans are automatically created for each request.

        Optionally, pass an `httpx.Client` instance to instrument only that client.

        Uses the
        [OpenTelemetry HTTPX Instrumentation](https://opentelemetry-python-contrib.readthedocs.io/en/latest/instrumentation/httpx/httpx.html)
        library, specifically `HTTPXClientInstrumentor().instrument()`, to which it passes `**kwargs`.

        Args:
            client: The `httpx.Client` or `httpx.AsyncClient` instance to instrument.
                If `None`, the default, all clients will be instrumented.
            capture_all: Set to `True` to capture all HTTP headers, request and response bodies.
            capture_headers: Set to `True` to capture all HTTP headers.

                If you don't want to capture all headers, you can customize the headers captured. See the
                [Capture Headers](https://logfire.pydantic.dev/docs/guides/advanced/capture_headers/) section for more info.
            capture_request_body: Set to `True` to capture the request body.
            capture_response_body: Set to `True` to capture the response body.
            request_hook: A function called right after a span is created for a request.
            response_hook: A function called right before a span is finished for the response.
            async_request_hook: A function called right after a span is created for an async request.
            async_response_hook: A function called right before a span is finished for an async response.
            **kwargs: Additional keyword arguments to pass to the OpenTelemetry `instrument` method, for future compatibility.
        r   )rU  rX  )integrations.httpxrU  r  )rx   rT  rM  r%  rN  rO  rP  rQ  rY  rZ  rL  rU  s               ry   rU  zLogfire.instrument_httpx  sP    L 	999;
 $+!5"7%'1 3
 
 	
r{   c                    ddl m} | j                           |di | j                  j	                         | j                  j                         d|S )a  Instrument `celery` so that spans are automatically created for each task.

        Uses the
        [OpenTelemetry Celery Instrumentation](https://opentelemetry-python-contrib.readthedocs.io/en/latest/instrumentation/celery/celery.html)
        library.

        Args:
            **kwargs: Additional keyword arguments to pass to the OpenTelemetry `instrument` method, for future compatibility.
        r   )instrument_celeryrH  ri   )integrations.celeryr_  r  rt   r   r   )rx   rL  r_  s      ry   r_  zLogfire.instrument_celery   sT     	;99;  
#'<<#C#C#E"&,,"A"A"C 
 	
r{   c           	         ddl m} | j                           |d|||||d| j                  j	                         | j                  j                         d|S )a  Instrument `django` so that spans are automatically created for each web request.

        Uses the
        [OpenTelemetry Django Instrumentation](https://opentelemetry-python-contrib.readthedocs.io/en/latest/instrumentation/django/django.html)
        library.

        Args:
            capture_headers: Set to `True` to capture all request and response headers.
            is_sql_commentor_enabled: Adds comments to SQL queries performed by Django,
                so that database logs have additional context.

                This does NOT create spans/logs for the queries themselves.
                For that you need to instrument the database driver, e.g. with `logfire.instrument_psycopg()`.

                To configure the SQL Commentor, see the OpenTelemetry documentation for the
                values that need to be added to `settings.py`.

            request_hook: A function called right after a span is created for a request.
                The function should accept two arguments: the span and the Django `Request` object.

            response_hook: A function called right before a span is finished for the response.
                The function should accept three arguments:
                the span, the Django `Request` object, and the Django `Response` object.

            excluded_urls: A string containing a comma-delimited list of regexes used to exclude URLs from tracking.

            **kwargs: Additional keyword arguments to pass to the OpenTelemetry `instrument` method,
                for future compatibility.

        r   )instrument_django)r%  is_sql_commentor_enabledrP  rQ  r'  rH  ri   )integrations.djangorb  r  rt   r   r   )rx   r%  rc  rP  rQ  r'  rL  rb  s           ry   rb  zLogfire.instrument_django  sk    N 	;99;  
+%=%''
 $(<<#C#C#E"&,,"A"A"C 
 	
r{   c                    ddl m} | j                           |d|||d| j                  j	                         | j                  j                         d|S )a  Instrument the `requests` module so that spans are automatically created for each request.

        Args:
            excluded_urls: A string containing a comma-delimited list of regexes used to exclude URLs from tracking
            request_hook: A function called right after a span is created for a request.
            response_hook: A function called right before a span is finished for the response.
            **kwargs: Additional keyword arguments to pass to the OpenTelemetry `instrument` methods, for future compatibility.
        r   )instrument_requests)r'  rP  rQ  rH  ri   )integrations.requestsrf  r  rt   r   r   )rx   r'  rP  rQ  rL  rf  s         ry   rf  zLogfire.instrument_requestsL  sd     	?99;" 	
'%'	

 $(<<#C#C#E"&,,"A"A"C 		
 		
r{   c                     y rq   ri   )rx   conn_or_modulerL  s      ry   instrument_psycopgzLogfire.instrument_psycopgi  s    qtr{   c                     y rq   ri   )rx   ri  enable_commentercommenter_optionsrL  s        ry   rj  zLogfire.instrument_psycopgl  s     r{   c                x    ddl m} | j                          |r|j                  d|xs i d        || fd|i|S )ag  Instrument a `psycopg` connection or module so that spans are automatically created for each query.

        Uses the OpenTelemetry instrumentation libraries for
        [`psycopg`](https://opentelemetry-python-contrib.readthedocs.io/en/latest/instrumentation/psycopg/psycopg.html)
        and
        [`psycopg2`](https://opentelemetry-python-contrib.readthedocs.io/en/latest/instrumentation/psycopg2/psycopg2.html).

        Args:
            conn_or_module: Can be:

                - The `psycopg` (version 3) or `psycopg2` module.
                - The string `'psycopg'` or `'psycopg2'` to instrument the module.
                - `None` (the default) to instrument whichever module(s) are installed.
                - A `psycopg` or `psycopg2` connection.

            enable_commenter: Adds comments to SQL queries performed by Psycopg, so that database logs have additional context.
            commenter_options: Configure the tags to be added to the SQL comments.
            **kwargs: Additional keyword arguments to pass to the OpenTelemetry `instrument` methods,
                for future compatibility.
        r   )rj  T)rl  rm  ri  )integrations.psycopgrj  r  r   )rx   ri  rl  rm  rL  rj  s         ry   rj  zLogfire.instrument_psycopgu  sC    6 	=99;MMtJ[Ja_abc!$P~PPPr{   r%  rl  rm  exclude_urlsrP  rQ  c          
         ddl m}	 | j                           |	|f||||||d| j                  j	                         | j                  j                         d|S )a  Instrument `app` so that spans are automatically created for each request.

        Uses the
        [OpenTelemetry Flask Instrumentation](https://opentelemetry-python-contrib.readthedocs.io/en/latest/instrumentation/flask/flask.html)
        library, specifically `FlaskInstrumentor().instrument_app()`, to which it passes `**kwargs`.

        Args:
            app: The Flask app to instrument.
            capture_headers: Set to `True` to capture all request and response headers.
            enable_commenter: Adds comments to SQL queries performed by Flask, so that database logs have additional context.
            commenter_options: Configure the tags to be added to the SQL comments.
                See more about it on the [SQLCommenter Configurations](https://opentelemetry-python-contrib.readthedocs.io/en/latest/instrumentation/flask/flask.html#sqlcommenter-configurations).
            exclude_urls: A string containing a comma-delimited list of regexes used to exclude URLs from tracking.
            request_hook: A function called right after a span is created for a request.
            response_hook: A function called right before a span is finished for the response.
            **kwargs: Additional keyword arguments to pass to the OpenTelemetry Flask instrumentation.
        r   )instrument_flaskrp  rH  )integrations.flaskrs  r  rt   r   r   )
rx   r,  r%  rl  rm  rq  rP  rQ  rL  rs  s
             ry   rs  zLogfire.instrument_flask  sp    : 	999;
+-/%%'
 $(<<#C#C#E"&,,"A"A"C 
 	
r{   )r%  r(  server_request_hookclient_request_hookclient_response_hookc          	     N    ddl m} | j                           || |f|||||d|S )a  Instrument `app` so that spans are automatically created for each request.

        Uses the
        [OpenTelemetry Starlette Instrumentation](https://opentelemetry-python-contrib.readthedocs.io/en/latest/instrumentation/starlette/starlette.html)
        library, specifically `StarletteInstrumentor.instrument_app()`, to which it passes `**kwargs`.

        Args:
            app: The Starlette app to instrument.
            capture_headers: Set to `True` to capture all request and response headers.
            record_send_receive: Set to `True` to allow the OpenTelemetry ASGI middleware to create send/receive spans.

                These are disabled by default to reduce overhead and the number of spans created,
                since many can be created for a single request, and they are not often useful.
                If enabled, they will be set to debug level, meaning they will usually still be hidden in the UI.
            server_request_hook: A function that receives a server span and the ASGI scope for every incoming request.
            client_request_hook: A function that receives a span, the ASGI scope and the receive ASGI message for every ASGI receive event.
            client_response_hook: A function that receives a span, the ASGI scope and the send ASGI message for every ASGI send event.
            **kwargs: Additional keyword arguments to pass to the OpenTelemetry Starlette instrumentation.
        r   )instrument_starlette)r(  r%  ru  rv  rw  )integrations.starlettery  r  )	rx   r,  r%  r(  ru  rv  rw  rL  ry  s	            ry   ry  zLogfire.instrument_starlette  sG    < 	A99;#	
 !4+ 3 3!5	
 	
 		
r{   c                H    ddl m} | j                           || |f||d|S )a_  Instrument `app` so that spans are automatically created for each request.

        Uses the ASGI [`OpenTelemetryMiddleware`][opentelemetry.instrumentation.asgi.OpenTelemetryMiddleware] under
        the hood, to which it passes `**kwargs`.

        Warning:
            Instead of modifying the app in place, this method returns the instrumented ASGI application.

        Args:
            app: The ASGI application to instrument.
            capture_headers: Set to `True` to capture all request and response headers.
            record_send_receive: Set to `True` to allow the OpenTelemetry ASGI middleware to create send/receive spans.

                These are disabled by default to reduce overhead and the number of spans created,
                since many can be created for a single request, and they are not often useful.
                If enabled, they will be set to debug level, meaning they will usually still be hidden in the UI.
            **kwargs: Additional keyword arguments to pass to the OpenTelemetry ASGI middleware.

        Returns:
            The instrumented ASGI application.
        r   )instrument_asgi)r(  r%  )integrations.asgir|  r  )rx   r,  r%  r(  rL  r|  s         ry   r|  zLogfire.instrument_asgi  s=    8 	799;
 !4+	

 
 	
r{   c                    ddl m} | j                           ||f|||d| j                  j	                         | j                  j                         d|S )ak  Instrument `app` so that spans are automatically created for each request.

        Uses the WSGI [`OpenTelemetryMiddleware`][opentelemetry.instrumentation.wsgi.OpenTelemetryMiddleware] under
        the hood, to which it passes `**kwargs`.

        Warning:
            Instead of modifying the app in place, this method returns the instrumented WSGI application.

        Args:
            app: The WSGI application to instrument.
            capture_headers: Set to `True` to capture all request and response headers.
            request_hook: A function called right after a span is created for a request.
            response_hook: A function called right before a span is finished for the response.
            **kwargs: Additional keyword arguments to pass to the OpenTelemetry WSGI middleware.

        Returns:
            The instrumented WSGI application.
        r   )instrument_wsgi)r%  rP  rQ  rH  )integrations.wsgir  r  rt   r   r   )rx   r,  r%  rP  rQ  rL  r  s          ry   r  zLogfire.instrument_wsgi  sg    4 	799;

+%'	

 $(<<#C#C#E"&,,"A"A"C 

 
	
r{   c                @    ddl m} | j                           || fi |S )a  Instrument the `aiohttp` module so that spans are automatically created for each client request.

        Uses the
        [OpenTelemetry aiohttp client Instrumentation](https://opentelemetry-python-contrib.readthedocs.io/en/latest/instrumentation/aiohttp_client/aiohttp_client.html)
        library, specifically `AioHttpClientInstrumentor().instrument()`, to which it passes `**kwargs`.
        r   )instrument_aiohttp_client)integrations.aiohttp_clientr  r  )rx   rL  r  s      ry   r  z!Logfire.instrument_aiohttp_clientB  s$     	K99;(888r{   c                    ddl m} | j                           |d|||xs i d| j                  j	                         | j                  j                         d|S )a#  Instrument the `sqlalchemy` module so that spans are automatically created for each query.

        Uses the
        [OpenTelemetry SQLAlchemy Instrumentation](https://opentelemetry-python-contrib.readthedocs.io/en/latest/instrumentation/sqlalchemy/sqlalchemy.html)
        library, specifically `SQLAlchemyInstrumentor().instrument()`, to which it passes `**kwargs`.

        Args:
            engine: The `sqlalchemy` engine to instrument, or `None` to instrument all engines.
            enable_commenter: Adds comments to SQL queries performed by SQLAlchemy, so that database logs have additional context.
            commenter_options: Configure the tags to be added to the SQL comments.
            **kwargs: Additional keyword arguments to pass to the OpenTelemetry `instrument` methods.
        r   )instrument_sqlalchemy)enginerl  rm  rH  ri   )integrations.sqlalchemyr  r  rt   r   r   )rx   r  rl  rm  rL  r  s         ry   r  zLogfire.instrument_sqlalchemyN  sj    & 	C99;$ 	
-/52	

 $(<<#C#C#E"&,,"A"A"C 		
 		
r{   c                z    ddl m} | j                           |dd|id| j                  j	                         i|S )a  Instrument the `sqlite3` module or a specific connection so that spans are automatically created for each operation.

        Uses the
        [OpenTelemetry SQLite3 Instrumentation](https://opentelemetry-python-contrib.readthedocs.io/en/latest/instrumentation/sqlite3/sqlite3.html)
        library.

        Args:
            conn: The `sqlite3` connection to instrument, or `None` to instrument all connections.
            **kwargs: Additional keyword arguments to pass to the OpenTelemetry `instrument` methods.

        Returns:
            If a connection is provided, returns the instrumented connection. If no connection is provided, returns `None`.
        r   )instrument_sqlite3connrI  ri   )integrations.sqlite3r  r  rt   r   )rx   r  rL  r  s       ry   r  zLogfire.instrument_sqlite3o  s?     	=99;!qtq0A4<<CcCcCe/pio/pqqr{   c                    ddl m} | j                           |d||d| j                  j	                         | j                  j                         d|S )a  Instrument AWS Lambda so that spans are automatically created for each invocation.

        Uses the
        [OpenTelemetry AWS Lambda Instrumentation](https://opentelemetry-python-contrib.readthedocs.io/en/latest/instrumentation/aws_lambda/aws_lambda.html)
        library, specifically `AwsLambdaInstrumentor().instrument()`, to which it passes `**kwargs`.

        Args:
            lambda_handler: The lambda handler function to instrument.
            event_context_extractor: A function that returns an OTel Trace Context given the Lambda Event the AWS.
            **kwargs: Additional keyword arguments to pass to the OpenTelemetry `instrument` methods for future compatibility.
        r   )instrument_aws_lambda)lambda_handlerevent_context_extractorrH  ri   )integrations.aws_lambdar  r  rt   r   r   )rx   r  r  rL  r  s        ry   r  zLogfire.instrument_aws_lambda  sb    " 	C99;$ 
)$;
 $(<<#C#C#E"&,,"A"A"C 
 	
r{   c                    ddl m} | j                           |d||||d| j                  j	                         | j                  j                         d|S )aS  Instrument the `pymongo` module so that spans are automatically created for each operation.

        Uses the
        [OpenTelemetry pymongo Instrumentation](https://opentelemetry-python-contrib.readthedocs.io/en/latest/instrumentation/pymongo/pymongo.html)
        library, specifically `PymongoInstrumentor().instrument()`, to which it passes `**kwargs`.

        Args:
            capture_statement: Set to `True` to capture the statement in the span attributes.
            request_hook: A function called when a command is sent to the server.
            response_hook: A function that is called when a command is successfully completed.
            failed_hook: A function that is called when a command fails.
            **kwargs: Additional keyword arguments to pass to the OpenTelemetry `instrument` methods for future compatibility.
        r   )instrument_pymongo)capture_statementrP  rQ  failed_hookrH  ri   )integrations.pymongor  r  rt   r   r   )rx   r  rP  rQ  r  rL  r  s          ry   r  zLogfire.instrument_pymongo  sg    * 	=99;! 

/%'#	

 $(<<#C#C#E"&,,"A"A"C 

 
	
r{   c                    ddl m} | j                           |d|||d| j                  j	                         | j                  j                         d|S )a  Instrument the `redis` module so that spans are automatically created for each operation.

        Uses the
        [OpenTelemetry Redis Instrumentation](https://opentelemetry-python-contrib.readthedocs.io/en/latest/instrumentation/redis/redis.html)
        library, specifically `RedisInstrumentor().instrument()`, to which it passes `**kwargs`.

        Args:
            capture_statement: Set to `True` to capture the statement in the span attributes.
            request_hook: A function that is called before performing the request.
            response_hook: A function that is called after receiving the response.
            **kwargs: Additional keyword arguments to pass to the OpenTelemetry `instrument` methods for future compatibility.
        r   )instrument_redis)r  rP  rQ  rH  ri   )integrations.redisr  r  rt   r   r   )rx   r  rP  rQ  rL  r  s         ry   r  zLogfire.instrument_redis  sd    & 	999; 	
/%'	

 $(<<#C#C#E"&,,"A"A"C 		
 		
r{   c                    ddl m} | j                           |dd|i| j                  j	                         | j                  j                         d|S )a  Instrument the `mysql` module or a specific MySQL connection so that spans are automatically created for each operation.

        Uses the
        [OpenTelemetry MySQL Instrumentation](https://opentelemetry-python-contrib.readthedocs.io/en/latest/instrumentation/mysql/mysql.html)
        library.

        Args:
            conn: The `mysql` connection to instrument, or `None` to instrument all connections.
            **kwargs: Additional keyword arguments to pass to the OpenTelemetry `instrument` methods.

        Returns:
            If a connection is provided, returns the instrumented connection. If no connection is provided, returns None.
        r   )instrument_mysqlr  rH  ri   )integrations.mysqlr  r  rt   r   r   )rx   r  rL  r  s       ry   r  zLogfire.instrument_mysql  s^     	999; 

 $(<<#C#C#E"&,,"A"A"C 
 	
r{   c                B    ddl m} | j                           || ||      S )a  Collect system metrics.

        See [the guide](https://logfire.pydantic.dev/docs/integrations/system-metrics/) for more information.

        Args:
            config: A dictionary where the keys are metric names
                and the values are optional further configuration for that metric.
            base: A string indicating the base config dictionary which `config` will be merged with,
                or `None` for an empty base config.
        r   )instrument_system_metrics)integrations.system_metricsr  r  )rx   rk   baser  s       ry   r  z!Logfire.instrument_system_metrics  s#     	K99;(vt<<r{    )unitdescriptionc               <    | j                   j                  |||      S )a  Create a counter metric.

        A counter is a cumulative metric that represents a single numerical value that only ever goes up.

        ```py
        import logfire

        logfire.configure()
        counter = logfire.metric_counter('exceptions', unit='1', description='Number of exceptions caught')

        try:
            raise Exception('oops')
        except Exception:
            counter.add(1)
        ```

        See the [Opentelemetry documentation](https://opentelemetry.io/docs/specs/otel/metrics/api/#counter) about
        counters.

        Args:
            name: The name of the metric.
            unit: The unit of the metric.
            description: The description of the metric.

        Returns:
            The counter metric.
        )r   create_counterrx   r   r  r  s       ry   metric_counterzLogfire.metric_counter  s    8 {{))$kBBr{   c               <    | j                   j                  |||      S )a  Create a histogram metric.

        A histogram is a metric that samples observations (usually things like request durations or response sizes).

        ```py
        import logfire

        logfire.configure()
        histogram = logfire.metric_histogram('bank.amount_transferred', unit='$', description='Amount transferred')


        def transfer(amount: int):
            histogram.record(amount)
        ```

        See the [Opentelemetry documentation](https://opentelemetry.io/docs/specs/otel/metrics/api/#histogram) about

        Args:
            name: The name of the metric.
            unit: The unit of the metric.
            description: The description of the metric.

        Returns:
            The histogram metric.
        )r   create_histogramr  s       ry   metric_histogramzLogfire.metric_histogram/  s    4 {{++D$DDr{   c               <    | j                   j                  |||      S )a  Create a gauge metric.

        Gauge is a synchronous instrument which can be used to record non-additive measurements.

        ```py
        import logfire

        logfire.configure()
        gauge = logfire.metric_gauge('system.cpu_usage', unit='%', description='CPU usage')


        def update_cpu_usage(cpu_percent):
            gauge.set(cpu_percent)
        ```

        See the [Opentelemetry documentation](https://opentelemetry.io/docs/specs/otel/metrics/api/#gauge) about gauges.

        Args:
            name: The name of the metric.
            unit: The unit of the metric.
            description: The description of the metric.

        Returns:
            The gauge metric.
        )r   create_gauger  s       ry   metric_gaugezLogfire.metric_gaugeK  s    4 {{''dK@@r{   c               <    | j                   j                  |||      S )a`  Create an up-down counter metric.

        An up-down counter is a cumulative metric that represents a single numerical value that can be adjusted up or
        down.

        ```py
        import logfire

        logfire.configure()
        up_down_counter = logfire.metric_up_down_counter('users.logged_in', unit='1', description='Users logged in')


        def on_login(user):
            up_down_counter.add(1)


        def on_logout(user):
            up_down_counter.add(-1)
        ```

        See the [Opentelemetry documentation](https://opentelemetry.io/docs/specs/otel/metrics/api/#updowncounter) about
        up-down counters.

        Args:
            name: The name of the metric.
            unit: The unit of the metric.
            description: The description of the metric.

        Returns:
            The up-down counter metric.
        )r   create_up_down_counterr  s       ry   metric_up_down_counterzLogfire.metric_up_down_counterg  s    @ {{11$kJJr{   c               @    | j                   j                  ||||       y)a9  Create a counter metric that uses a callback to collect observations.

        The counter metric is a cumulative metric that represents a single numerical value that only ever goes up.

        ```py
        import logfire
        import psutil
        from opentelemetry.metrics import CallbackOptions, Observation

        logfire.configure()


        def cpu_usage_callback(options: CallbackOptions):
            cpu_percents = psutil.cpu_percent(percpu=True)

            for i, cpu_percent in enumerate(cpu_percents):
                yield Observation(cpu_percent, {'cpu': i})


        cpu_usage_counter = logfire.metric_counter_callback(
            'system.cpu.usage',
            callbacks=[cpu_usage_callback],
            unit='%',
            description='CPU usage',
        )
        ```

        See the [Opentelemetry documentation](https://opentelemetry.io/docs/specs/otel/metrics/api/#asynchronous-counter)
        about asynchronous counter.

        Args:
            name: The name of the metric.
            callbacks: A sequence of callbacks that return an iterable of
                [Observation](https://opentelemetry-python.readthedocs.io/en/latest/api/metrics.html#opentelemetry.metrics.Observation).
            unit: The unit of the metric.
            description: The description of the metric.
        N)r   create_observable_counterrx   r   	callbacksr  r  s        ry   metric_counter_callbackzLogfire.metric_counter_callback  s    Z 	--dIt[Qr{   c               @    | j                   j                  ||||       y)a  Create a gauge metric that uses a callback to collect observations.

        The gauge metric is a metric that represents a single numerical value that can arbitrarily go up and down.

        ```py
        import threading

        import logfire
        from opentelemetry.metrics import CallbackOptions, Observation

        logfire.configure()


        def thread_count_callback(options: CallbackOptions):
            yield Observation(threading.active_count())


        logfire.metric_gauge_callback(
            'system.thread_count',
            callbacks=[thread_count_callback],
            unit='1',
            description='Number of threads',
        )
        ```

        See the [Opentelemetry documentation](https://opentelemetry.io/docs/specs/otel/metrics/api/#asynchronous-gauge)
        about asynchronous gauge.

        Args:
            name: The name of the metric.
            callbacks: A sequence of callbacks that return an iterable of
                [Observation](https://opentelemetry-python.readthedocs.io/en/latest/api/metrics.html#opentelemetry.metrics.Observation).
            unit: The unit of the metric.
            description: The description of the metric.
        N)r   create_observable_gauger  s        ry   metric_gauge_callbackzLogfire.metric_gauge_callback  s    L 	++D)T;Or{   c               @    | j                   j                  ||||       y)a  Create an up-down counter metric that uses a callback to collect observations.

        The up-down counter is a cumulative metric that represents a single numerical value that can be adjusted up or
        down.

        ```py
        import logfire
        from opentelemetry.metrics import CallbackOptions, Observation

        logfire.configure()

        items = []


        def inventory_callback(options: CallbackOptions):
            yield Observation(len(items))


        logfire.metric_up_down_counter_callback(
            name='store.inventory',
            description='Number of items in the inventory',
            callbacks=[inventory_callback],
        )
        ```

        See the [Opentelemetry documentation](https://opentelemetry.io/docs/specs/otel/metrics/api/#asynchronous-updowncounter)
        about asynchronous up-down counters.

        Args:
            name: The name of the metric.
            callbacks: A sequence of callbacks that return an iterable of
                [Observation](https://opentelemetry-python.readthedocs.io/en/latest/api/metrics.html#opentelemetry.metrics.Observation).
            unit: The unit of the metric.
            description: The description of the metric.
        N)r   !create_observable_up_down_counterr  s        ry   metric_up_down_counter_callbackz'Logfire.metric_up_down_counter_callback  s    L 	55dIt[Yr{   c                6     | j                   j                  |  y)zPrevent spans and metrics from being created for the given OpenTelemetry scope names.

        To get the scope name of a span/metric,
        check the value of the `otel_scope_name` column in the Logfire database.
        N)rt   suppress_scopes)rx   scopess     ry   r  zLogfire.suppress_scopes  s     	%$$f-r{   c                   t               }|r| j                  j                  |       t        d|t               |z
  z
        }|sy| j                  j	                          t        d|t               |z
  z
        }|sy|r| j
                  j                  |       t        d|t               |z
  z
        }|sy| j
                  j	                  |       |t               z
  |k  S )a  Shut down all tracers and meters.

        This will clean up any resources used by the tracers and meters and flush any remaining spans and metrics.

        Args:
            timeout_millis: The timeout in milliseconds.
            flush: Whether to flush remaining spans and metrics before shutting down.

        Returns:
            `False` if the timeout was reached before the shutdown was completed, `True` otherwise.
        r   F)r   r   r  maxshutdownr   )rx   r  flushstart	remainings        ry   r  zLogfire.shutdown  s     !!--n=>TVe^<=	&&(>TVe^<=	  ,,Y7>TVe^<=	%%i0.00r{   )rk   r$   rl   zfloat | Nonerm   Sequence[str]rn   boolro   r   returnNone)r  r$   )r  r=   )r  r;   )r  r   )r   r  r  r   )r   r   r   dict[str, Any]rs   Sequence[str] | Noner   
str | Noner   zLevelName | int | Noner   3Sequence[tuple[SpanContext, otel_types.Attributes]]r  r   )r   r   r   otel_types.Attributesr  r   )r   r   r   $dict[str, otel_types.AttributeValue]r   r  r  r   )
r   r   rs   r  r   ExcInfor   r   r  r  )r   r   rs   r  r   r  r   zLevelName | Noner   r  r   r   r  r   rq   )
r   zLiteralString | Noner   r  r   bool | Iterable[str]r   r  r  z*Callable[[Callable[P, R]], Callable[P, R]])r   Callable[P, R]r  r  )
r   z%Callable[P, R] | LiteralString | Noner   r  r   r  r   r  r  z;Callable[[Callable[P, R]], Callable[P, R]] | Callable[P, R])NNFN)r   LevelName | intr   r   r   zdict[str, Any] | Nonerm   r  r   r  rn   bool | Noner  r  )rm   r   r  rh   )rl   floatr  rh   )
rm   r  r  
int | Nonern   r  r  r  r  rh   )i  )r  intr  r  )g?)r  r  r  ContextManager[None])r  z1Sequence[str] | Callable[[AutoTraceModule], bool]r  r  r  z"Literal['error', 'warn', 'ignore']r  r  )allri   ri   )r  r%   r  Iterable[str]r  r  r  r  )r,  rH   r%  r  r&  zMCallable[[Request | WebSocket, dict[str, Any]], dict[str, Any] | None] | Noner'  zstr | Iterable[str] | Noner(  r  r-  r   r  r  )r;  zZopenai.OpenAI | openai.AsyncOpenAI | type[openai.OpenAI] | type[openai.AsyncOpenAI] | Noner.  r  r  r  )rD  zanthropic.Anthropic | anthropic.AsyncAnthropic | anthropic.AnthropicBedrock | anthropic.AsyncAnthropicBedrock | type[anthropic.Anthropic] | type[anthropic.AsyncAnthropic] | type[anthropic.AnthropicBedrock] | type[anthropic.AsyncAnthropicBedrock] | Noner.  r  r  r  )rL  r   r  r  )rT  zhttpx.ClientrM  r  r%  r  rN  r  rO  r  rP  HttpxRequestHook | NonerQ  HttpxResponseHook | NonerL  r   r  r  )rT  zhttpx.AsyncClientrM  r  r%  r  rN  r  rO  r  rP  /HttpxRequestHook | HttpxAsyncRequestHook | NonerQ  1HttpxResponseHook | HttpxAsyncResponseHook | NonerL  r   r  r  )rT  r  rM  r  r%  r  rN  r  rO  r  rP  r  rQ  r  rY  HttpxAsyncRequestHook | NonerZ  HttpxAsyncResponseHook | NonerL  r   r  r  )rT  z'httpx.Client | httpx.AsyncClient | NonerM  r  r%  r  rN  r  rO  r  rP  r  rQ  r  rY  r  rZ  r  rL  r   r  r  )FNNNN)r%  r  rc  r  rP  z4Callable[[trace_api.Span, HttpRequest], None] | NonerQ  zBCallable[[trace_api.Span, HttpRequest, HttpResponse], None] | Noner'  r  rL  r   r  r  )NNN)
r'  r  rP  z7Callable[[Span, requests.PreparedRequest], None] | NonerQ  zJCallable[[Span, requests.PreparedRequest, requests.Response], None] | NonerL  r   r  r  )ri  z&PsycopgConnection | Psycopg2ConnectionrL  r   r  r  )NFN)
ri  z2None | Literal['psycopg', 'psycopg2'] | ModuleTyperl  r  rm  PsycopgCommenterOptions | NonerL  r   r  r  )
ri  r   rl  r  rm  r  rL  r   r  r  )r,  rI   r%  r  rl  r  rm  zFlaskCommenterOptions | Nonerq  r  rP  zFlaskRequestHook | NonerQ  zFlaskResponseHook | NonerL  r   r  r  )r,  rS   r%  r  r(  r  ru  zServerRequestHook | Nonerv  zClientRequestHook | Nonerw  zClientResponseHook | NonerL  r   r  r  )FF)
r,  r\   r%  r  r(  r  rL  zUnpack[ASGIInstrumentKwargs]r  r\   )FNN)r,  rE   r%  r  rP  zWSGIRequestHook | NonerQ  zWSGIResponseHook | NonerL  r   r  rE   )
r  zAsyncEngine | Engine | Nonerl  r  rm  z!SQLAlchemyCommenterOptions | NonerL  r   r  r  )r  rc   rL  r   r  rc   )r  r_   r  z'Callable[[LambdaEvent], Context] | NonerL  r   r  r  )FNNN)r  r  rP  z2Callable[[Span, CommandStartedEvent], None] | NonerQ  z4Callable[[Span, CommandSucceededEvent], None] | Noner  z1Callable[[Span, CommandFailedEvent], None] | NonerL  r   r  r  )
r  r  rP  zRedisRequestHook | NonerQ  zRedisResponseHook | NonerL  r   r  r  )r  r`   rL  r   r  r`   )Nbasic)rk   zSystemMetricsConfig | Noner  SystemMetricsBaser  r  )r   r   r  r   r  r   r  r   )r   r   r  r   r  r   r  r   )r   r   r  r   r  r   r  Gauge)r   r   r  r   r  r   r  r   )
r   r   r  zSequence[CallbackT]r  r   r  r   r  r  )r  r   r  r  )i0u  T)r  r  r  r  r  r  )Dr   
__module____qualname____doc__r#   rz   propertyrk   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r5   r   r  r  r  r  r  r"   r  r#  r*  r<  rE  rG  rU  r_  rb  rf  rj  rs  ry  r|  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  ri   r{   ry   rh   rh   x   s   !
 !.$(  #& & "	&
 & & & 
&   2 2 1 1 I I 6 6 5 5
 '+!%)-FH;; #;
 $; ; '; D; 
;z
%IZh	0 '+"TT
 $T T T 
TJ '+"TT
 $T T T 
TJ '+"SS
 $S S S 
SJ '+"UU
 $U U U 
UJ '+"SS
 $S S S 
SJ '+"TT
 $T T T 
TJ '+"TT
 $T T T 
TJ '+!TT
 $T T T 
T: '+!%#'FH(
(

 $(
 (
 !(
 D(
 (
 
(
T  .2 !%-1 %* 	
 +  
4 <  " ?Ck !%-1 %k;k 	k
 +k k 
EkJ -1%)!#'m!m! m! *	m!
 #m! m! !m! 
m!^-.
( !#'#'*.!
 !
 !	!

 !!
 (!
 
!
F	8>, FM&vB&v 	&v
 !C&v 
&vPS
 .3!#!#	/
*/
 /
 	/

 
/
j !& 48$)E
E
 	E

$E
 2E
 "E
 !$E
  
!E
Z H
 04H
H
 )-H
 
H
l R
 04R
R
 )-R
 
R
h
 
 " %%*&+0426 	
  #  $ . 0  
  
 " %%*&+HLKO! 	
  #  $ F I  
    " %%*&+0426;?=A 	
  #  $ . 0 9 ;  
 " ;?5
 " %%*&+HLKO;?=A5
75
 	5

 5
 #5
  $5
 F5
 I5
 95
 ;5
 5
 
5
n
. !&04MQ\`$(5
5
 #.5
 K	5

 Z5
 "5
 5
 
5
r %)PTdh	
!
 N
 b	

 
 

: t t NR!&<@	J  :	
  
  #!&<@	 Q Q  Q :	 Q
  Q 
 QL !&!%:>#'0426-
-
 	-

 -
 8-
 !-
 .-
 0-
 -
 
-
f !&$)8<8<:>*
*
 	*

 "*
 6*
 6*
 8*
 *
 
*
^ !&$)	%
%
 %
 "	%

 /%
 
%
T !&/315'
'
 '
 -	'

 /'
 '
 
'
R
9 /3!&?C	
+
 
 =	

 
 

Br, LP
%
 "I
 	

 

@ #(KONRIM"
"
 I"
 L	"

 G"
 "
 
"
L #(0426	

 .
 0	

 
 

B
6 T[=0=?P=	=$ 8:b C< :<PR E8 68B A8 @BVX  KN -R-R '	-R
 -R -R 
-R` IK_a&P&P$7&PBE&PY\&P	&PR IK_a&Z&Z$7&ZBE&ZY\&Z	&ZP.1r{   rh   c                  @    e Zd ZdZdZddZddZ e       d	d       Zy)
r   z=A simple version of `LogfireSpan` optimized for auto-tracing.)r   _tokenc                    || _         t        j                  t        j                  | j                               | _        y rq   )r   context_apiattach	trace_apiset_span_in_contextr  )rx   r   s     ry   rz   zFastLogfireSpan.__init__5  s*    
!(()F)Ftzz)RSr{   c                    | S rq   ri   r}   s    ry   	__enter__zFastLogfireSpan.__enter__9      r{   c                |    t        j                  | j                         | j                  j	                  |||       y rq   )r  detachr  r   __exit__rx   exc_type	exc_value	tracebacks       ry   r  zFastLogfireSpan.__exit__<  s*    4;;'

Hi;r{   N)r   ztrace_api.Spanr  r  )r  r   r  ztype[BaseException] | Noner  zBaseException | Noner  r   r  r  )	r   r  r  r  	__slots__rz   r  rA   r  ri   r{   ry   r   r   0  s,    G#IT < <r{   r   c                  v   e Zd Z	 	 	 	 	 	 	 	 	 	 	 	 ddZesddZddZ e       dd       Ze	dd       Z
e	dd       Zej                   e       dd              Ze	dd       Zej                  dd	       Z e       dd
       ZddZdddZ	 	 	 d 	 	 	 	 	 	 	 	 	 d!dZd"dZ e       d#d       Zd$dZddZy)%r   c                    || _         || _        || _        || _        t	        d |D              | _        d| _        d | _        d | _        y )Nc              3  P   K   | ]  \  }}t        j                  ||          yw)contextr   N)r  Link)r   r  r   s      ry   r   z'LogfireSpan.__init__.<locals>.<genexpr>P  s(     smrViV]_i9>>'jQQmrs   $&F)	r   _otlp_attributes_tracer_json_schema_propertieslistr   _added_attributesr  r   )rx   r   r   tracerr   r   s         ry   rz   zLogfireSpan.__init__D  sK     $ /'=$smrss!&%),0
r{   c                .    t        | j                  |      S rq   )getattrr   )rx   r   s     ry   __getattr__zLogfireSpan.__getattr__X  s    4::t,,r{   c                   t               5  | j                  A| j                  j                  | j                  | j
                  | j                        | _        | j                  j                          | j                  7t        j                  t        j                  | j                              | _        d d d        | S # 1 sw Y   | S xY w)N)r   r   r   )rA   r   r  r   r   r   r   r  r  r  r  r  r  r}   s    ry   r  zLogfireSpan.__enter__[  s    #%zz!!\\44#44++ 5 

 JJ  "{{")001N1Ntzz1Z[ &  & s   B+C  C
c                   | j                   y | j                  J t        j                  | j                          d | _         | j                  j	                         rpt               5  | j                  r3| j                  j                  t        t        | j                               d d d        | j                  j                  |||       y y # 1 sw Y   (xY wrq   )r  r   r  r  is_recordingrA   r  set_attributer&   r8   r  r  r  s       ry   r  zLogfireSpan.__exit__i  s    ;;zz%%%4;;'::""$')))JJ,,24J4KgKg4h *
 JJ)Y? %))s   &A CCc                .    | j                  t        d       S rq   )_get_attributer)   r}   s    ry   message_templatezLogfireSpan.message_templatey  s    ""#BDIIr{   c                .    | j                  t        d      S Nri   )r  r,   r}   s    ry   rm   zLogfireSpan.tags}  s    ""#6;;r{   c                z    t        |t              r|f}| j                  t        t	        t        |                   y)zSet or add tags to the span.N)r   r   _set_attributer,   rr   rC   rx   new_tagss     ry   rm   zLogfireSpan.tags  s1     h$ {H/7H7R1STr{   c                B    | j                  t        | j                        S rq   )r  r(   r   r}   s    ry   messagezLogfireSpan.message  s    ""#94??KKr{   c                0    | j                  t        |       y rq   )r  r(   rx   r  s     ry   r  zLogfireSpan.message  s    2G<r{   c                    d| _         t        |t                     | j                  |<   t	        | j
                  ||      \  }}| j                  | j                  j                  ||       yy)zSets an attribute on the span.

        Args:
            key: The key of the attribute.
            value: The value of the attribute.
        TN)r  r:   r"  r  set_user_attributer   r   r  )rx   keyvalue
otel_values       ry   r  zLogfireSpan.set_attribute  s`     "&,>uce,L$$S),T-B-BCOZ::!JJ$$S*5 "r{   c                X    |j                         D ]  \  }}| j                  ||        y)z&Sets the given attributes on the span.N)itemsr  )rx   r   r  r  s       ry   set_attributeszLogfireSpan.set_attributes  s)    $**,JCsE* -r{   Nc                    | j                   ,| xj                  t        j                  ||      gz  c_        y | j                   j	                  ||       y )Nr  )r   r   r  r  add_link)rx   r  r   s      ry   r#  zLogfireSpan.add_link  s<    ::KKINN7zRSSKJJ4r{   c                    | j                   t        d      | j                   j                         syt        | j                   ||||       y)zzRecords an exception as a span event.

        Delegates to the OpenTelemetry SDK `Span.record_exception` method.
        NzSpan has not been started)r   	timestampescaped)r   r   r  r>   )rx   r   r   r%  r&  s        ry   r>   zLogfireSpan.record_exception  sJ     :::;; zz&&(JJ!	
r{   c                V    | j                   d uxr | j                   j                         S rq   )r   r  r}   s    ry   r  zLogfireSpan.is_recording  s#    zz%C$***A*A*CCr{   c                    t        |      }| j                  | j                  j                  |       y| j                  j	                  |       y)zSet the log level of this span.N)r2   r   r   r   r!  )rx   r   r   s      ry   	set_levelzLogfireSpan.set_level  s>     *%0
::!!((4JJ%%j1r{   c                h    t        | j                  d| j                        }|j                  ||      S )Nr   )r  r   r   get)rx   r  defaultr   s       ry   r  zLogfireSpan._get_attribute  s+    TZZt7L7LM
~~c7++r{   c                t    | j                   || j                  |<   y| j                   j                  ||       y)zSSet an attribute on the span or in the _otlp_attributes if span is not yet created.N)r   r   r  )rx   r  r  s      ry   r  zLogfireSpan._set_attribute  s0    ::).D!!#&JJ$$S%0r{   )r   r   r   r  r  r   r   r7   r   r  r  r  )r   r   r  r   )r  r   r  )r  r  r  ztuple[str, ...]r  r  r  r  r  r   r  r   )r  r   r  r   r  r  )r   r  r  r  rq   )r  r   r   r  r  r  )NNF)
r   r   r   r  r%  r  r&  r  r  r  r  r  )r   r  )r  r   r,  r   r  r   )r   r  r  rz   r   r  r  rA   r  r  r  rm   setterr  r  r!  r#  r>   r  r)  r  r  ri   r{   ry   r   r   C  so   11 >1 	1
 !51 C1 
1$ 	- @ @ J J < < 
[[U  U L L ^^= = 6 6+
5 -1 $
 
 *
 	

 
 

4D 2 2,1r{   r   c                      e Zd ZdZddZddZddZddZedd       Z	edd       Z
e
j                  dd       Z
edd	       Zej                  dd
       ZddZy)r   a?  Implements the same methods as `LogfireSpan` but does nothing.

    Used in place of `LogfireSpan` and `FastLogfireSpan` when an exception occurs during span creation.
    This way code like:

        with logfire.span(...) as span:
            span.set_attribute(...)

    doesn't raise an error even if `logfire.span` fails internally.
    If `logfire.span` just returned `None` then the `with` block and the `span.set_attribute` call would raise an error.

    TODO this should also be used when tracing is disabled, e.g. before `logfire.configure()` has been called.
    c                     y rq   ri   )rx   _args_NoopSpan__kwargss      ry   rz   zNoopSpan.__init__      r{   c                    d S )Nc                      y rq   ri   )r6  r7  s     ry   <lambda>z&NoopSpan.__getattr__.<locals>.<lambda>  s    $r{   ri   )rx   _names     ry   r  zNoopSpan.__getattr__  s    ..r{   c                    | S rq   ri   r}   s    ry   r  zNoopSpan.__enter__  r  r{   c                     y rq   ri   r  s       ry   r  zNoopSpan.__exit__  r8  r{   c                     yNr  ri   r}   s    ry   r  zNoopSpan.message_template      r{   c                     yr  ri   r}   s    ry   rm   zNoopSpan.tags  rA  r{   c                     y rq   ri   r  s     ry   rm   zNoopSpan.tags	      r{   c                     yr@  ri   r}   s    ry   r  zNoopSpan.message	  rA  r{   c                     y rq   ri   r  s     ry   r  zNoopSpan.message	  rD  r{   c                     y)NFri   r}   s    ry   r  zNoopSpan.is_recording	  s    r{   N)r6  r   r7  r   r  r  )r<  r   r  r   )r  r   r  r0  r.  r/  r1  r2  )r   r  r  r  rz   r  r  r  r  r  rm   r3  r  r  ri   r{   ry   r   r     s    /     
[[    ^^ r{   r   AttributesValueType)boundc                T    i }| j                         D ]  \  }}t        |||        |S )z|Prepare attributes for sending to OpenTelemetry.

    This will convert any non-OpenTelemetry compatible types to JSON.
    )r   r  )r   r   r  r  s       ry   r   r   	  s4    
 =?O &&(
U?C7 ) r{   c                Z   |+t        d| j                  t        g             |gz   }t        }nvt        |t              r=|t
        kD  r1t        j                  d| dt
         dt               t        |      }n,|}n)t        |t        t        t        f      r|}nt        |      }|| |<   ||fS )a  Convert a user attribute to an OpenTelemetry compatible type and add it to the given dictionary.

    Returns the final key and value that was added to the dictionary.
    The key will be the original key unless the value was `None`, in which case it will be `NULL_ARGS_KEY`.
    z	list[str]zInteger value z1 is larger than the maximum OTLP integer size of z[ (64-bits),  if you need support for sending larger integers, please open a feature request)r   r+  r/   r   r  r0   warningsr   UserWarningr   r  r  r6   )r   r  r  r  s       ry   r  r  $	  s     }+':':="'MNRUQVV
	E3	$$MM 'XYjXk lb b
 UJJ	ECu-	.
'.
%OC
?r{   c                   | j                         sy t        |      }t        |      x}rt        i       }| j                  xs i j                  t              }|rct        |t              rSt        j                  t        j                        5  t        j                  |      }|j                  di       }d d d        |j                  |       t        |      |t        <   | j!                  |       y # 1 sw Y   >xY w)N
properties)r  r   r9   r7   r   r+  r&   r   r   
contextlibsuppressjsonJSONDecodeErrorloadsr   r8   r!  )r   r   r   r   existing_propertiesexisting_json_schema_strexisting_json_schemas          ry   set_user_attributes_on_raw_spanrX  B	  s    -j9O!B:!NNN226$(OO$9r#>#>?Y#Z #
3KS(Q$$T%9%9:'+zz2J'K$&:&>&>|R&P# ; 	""#9:6LM`6a23( ;:s   (C22C;PR)r   r  r  r  )r   r  r  r   r  r   r  z%tuple[str, otel_types.AttributeValue])r   r   r   r  r  r  )
__future__r   rP  r   rR  r   rL  	functoolsr   r   typingr   r   r   r	   r
   r   r   r   r   r   r   opentelemetry.contextr  r  opentelemetry.tracer   r  r   opentelemetry.metricsr   r   r   r   opentelemetry.sdk.tracer   r   r   r   opentelemetry.utilr   
otel_typestyping_extensionsr   r   versionr   r  r    
auto_tracer!   r"   rk   r#   r$   config_paramsr%   	constantsr&   r'   r(   r)   r*   r+   r,   r-   r.   r/   r0   r1   r2   	formatterr3   r4   r5   json_encoderr6   json_schemar7   r8   r9   r:   metricsr;   r   r<   r  r=   r>   r?   utilsr@   rA   rB   rC   rD   wsgiref.typesrE   r?  httpxr7  requestsdjango.httprF   rG   fastapirH   	flask.apprI   (opentelemetry.instrumentation.asgi.typesrJ   rK   rL   rM   r  pymongo.monitoringrN   rO   rP   
sqlalchemyrQ   sqlalchemy.ext.asynciorR   starlette.applicationsrS   starlette.requestsrT   starlette.websocketsrU   rV   rt  rW   FlaskCommenterOptionsrX   FlaskRequestHookrY   FlaskResponseHookr]  rZ   HttpxAsyncRequestHookr[   HttpxAsyncResponseHookHttpxRequestHookHttpxResponseHookro  PsycopgCommenterOptionsr  RedisRequestHookRedisResponseHookr  SQLAlchemyCommenterOptionsr  WSGIRequestHookWSGIResponseHookr}  r\   r]   r  r^   r_   r  r`   ra   rb   r  rc   r  rd   r  re   SystemMetricsConfigrf   r   r  r  rh   r   r   r   AttributeValuerH  r   r  rX  rY  rZ  ri   r{   ry   <module>r     s   "    
  %     , ' ) N N 6 3 2 6   = 0 5    A " ,  ( + O O ] ] -5qq5aa!20*.( 
  SgXd@C3K7e! JtT9:Gu1 u1p=< <&W1, W1t4 4n 35jF_F_A_;`a 
9@CLO*<)" cNCLr{   