o
    i-                    @  s  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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 d dlmZ d dlmZmZ d dlmZmZmZmZmZ d d	lmZ d d
lm Z  d dl!Z!d dl"m#Z# d dl$m%Z%m&Z& d dl'm(Z(m)Z)m*Z* d dl+m,Z, d dl-m.Z. d dl/m0Z0 d dl1m2Z2 d dl3m4Z4m5Z5 d dl6m7Z7m8Z8 d dl9m:Z;m<Z< d dl=m>Z> d dl?m@Z@mAZA d dlBmCZCmDZDmEZEmFZFmGZG d dlHmIZImJZJmKZKmLZLmMZMmNZNmOZO d dlPmQZQmRZRmSZS d dlTmUZUmVZV d dlWmXZX d dlYmZZZm[Z[m\Z] d dl^m_Z_m`Z` d dlambZb d dlcmdZdmeZe d d lfmgZg d d!lhmiZimjZj d d"lkmlZlmmZm d d#lnmoZompZp d d$lqmrZr d d%lsmtZt d d&lumvZv d d'lwmxZx d d(lymzZz d)d*l{m|Z|m}Z} d)d+l~mZ d,d-lmZmZmZ d,d.lmZmZ d,d/lmZmZmZmZmZmZmZ d,d0lmZmZmZmZmZ d,d1lmZ d,d2lmZmZ d,d3lmZmZmZmZmZ d,d4lmZmZ d,d5lmZ d,d6lmZ d,d7lmZ d,d8lmZ d,d9lmZ d,d:lmZ d,d;lmZmZmZmZ d,d<lmZ d,d=lmZmZmZ d,d>lmZmZmZmZmZ erd d?lmZ d d@lmZ d,dAlmZ dBZ	 dCdDez iZ	 dEZeIeQjeOeQjeJeQjeLeQjeNeQjeMeQjiZ	 eG dFdG dGZeG dHdI dIZeG dJdK dKZeG dLdM dMZeG dNdO dOZG dPdQ dQeZdRdddddddddddddddSddddTddydzZejG d{d| d|ZG d}d~ d~e҃ZeӃ ZejG dd dZdddZdddZdddZdddZdddZdd ZdddZG dd de݃ZdS )    )annotationsN)Sequence)suppress)	dataclassfield)Path)RLockThread)TYPE_CHECKINGAnyCallableLiteral	TypedDict)urljoin)uuid4)trace)NoOpLoggerProviderset_logger_provider)OTEL_LOGS_EXPORTEROTEL_METRICS_EXPORTEROTEL_TRACES_EXPORTER)Compression)OTLPLogExporter)OTLPMetricExporter)OTLPSpanExporter)NoOpMeterProviderset_meter_provider)get_global_textmapset_global_textmap)LoggerProviderLogRecordProcessor)"SynchronousMultiLogRecordProcessor)BatchLogRecordProcessorSimpleLogRecordProcessor)OTEL_EXPORTER_OTLP_ENDPOINT OTEL_EXPORTER_OTLP_LOGS_ENDPOINT#OTEL_EXPORTER_OTLP_METRICS_ENDPOINT"OTEL_EXPORTER_OTLP_TRACES_ENDPOINTOTEL_RESOURCE_ATTRIBUTES)Counter	HistogramMeterProviderObservableCounterObservableGaugeObservableUpDownCounterUpDownCounter)AggregationTemporalityMetricReaderPeriodicExportingMetricReader)%ExponentialBucketHistogramAggregationView)Resource)SpanProcessorSynchronousMultiSpanProcessorTracerProvider)BatchSpanProcessorSimpleSpanProcessor)IdGenerator)ParentBasedTraceIdRatioSamplerConsole)ConfirmPrompt)SelfUnpack)PYDANTIC_LOGFIRE_TOKEN_PATTERNREGIONS)$DirectBaggageAttributesSpanProcessor)LogfireConfigError)SamplingOptions)TailSamplingProcessor)VERSION   )NoExtractTraceContextPropagator#WarnOnExtractTraceContextPropagator)ExceptionCallback   )InvalidProjectNameLogfireClientProjectAlreadyExists)ParamManagerPydanticPluginRecordValues)LEVEL_NUMBERS"RESOURCE_ATTRIBUTES_CODE_ROOT_PATH!RESOURCE_ATTRIBUTES_CODE_WORK_DIR/RESOURCE_ATTRIBUTES_DEPLOYMENT_ENVIRONMENT_NAME/RESOURCE_ATTRIBUTES_VCS_REPOSITORY_REF_REVISION&RESOURCE_ATTRIBUTES_VCS_REPOSITORY_URL	LevelName)ConsoleColorsValuesConsoleLogExporterIndentedConsoleSpanExporterShowParentsConsoleSpanExporterSimpleConsoleSpanExporter)DynamicBatchSpanProcessor)/CheckSuppressInstrumentationLogProcessorWrapperMainLogProcessorWrapper) BodySizeCheckingOTLPSpanExporterOTLPExporterHttpSessionQuietLogExporterQuietSpanExporterRetryFewerSpansSpanExporter),CheckSuppressInstrumentationProcessorWrapperMainSpanProcessorWrapper)QuietMetricExporter)RemovePendingSpansExporter)TestExporter)instrument_executors)ProxyLoggerProvider)ProxyMeterProvider)NOOP_SCRUBBERBaseScrubberScrubberScrubbingOptions)warn_at_user_stacklevel)
OPEN_SPANSPendingSpanProcessorProxyTracerProvider)SeededRandomIdGeneratorensure_data_dir_existshandle_internal_errorsplatform_is_emscriptensuppress_instrumentation)TextIOEventLoggerProvider)Logfirezlogfire_credentials.json
User-Agentlogfire/z^[a-z0-9]+(?:-[a-z0-9]+)*$c                   @  s~   e Zd ZU dZdZded< dZded< 	 dZd	ed
< 	 dZd	ed< 	 dZ	d	ed< 	 dZ
ded< 	 dZd	ed< 	 dZded< dS )ConsoleOptionsz'Options for controlling console output.autor\   colorsshow-parentsz-Literal['simple', 'indented', 'show-parents']
span_styleTboolinclude_timestampsinclude_tagsFverboseinfor[   min_log_levelshow_project_linkNzTextIO | Noneoutput)__name__
__module____qualname____doc__r   __annotations__r   r   r   r   r   r   r    r   r   ^/var/www/html/karishye-ai-python/venv/lib/python3.10/site-packages/logfire/_internal/config.pyr      s"   
 r   c                   @  sp   e Zd ZU dZdZded< 	 ejdd dZded	< 	 e	j
Zd
ed< 	 dZded< 	 dZded< 	 dddZdS )AdvancedOptionsz9Options primarily used for testing by Logfire developers.N
str | Nonebase_urlc                   C  s   t d S N)ry   r   r   r   r   <lambda>   s    zAdvancedOptions.<lambda>default_factoryr;   id_generatorzCallable[[], int]ns_timestamp_generatorr   zSequence[LogRecordProcessor]log_record_processorszExceptionCallback | Noneexception_callbacktokenstrreturnc                 C  s   | j d ur| j S t|S r   )r   get_base_url_from_tokenselfr   r   r   r   generate_base_url   s   
z!AdvancedOptions.generate_base_urlr   r   r   r   )r   r   r   r   r   r   dataclassesr   r   timetime_nsr   r   r   r   r   r   r   r   r      s   
 r   c                   @  sF   e Zd ZU dZdZded< 	 eedZded< 	 eedZ	ded< d	S )
PydanticPluginzOptions for the Pydantic plugin.

    This class is deprecated for external use. Use `logfire.instrument_pydantic()` instead.
    offrT   recordr   zset[str]includeexcludeN)
r   r   r   r   r   r   r   setr   r   r   r   r   r   r      s   
 	r   c                   @  s,   e Zd ZU dZdZded< 	 dZded< dS )	MetricsOptionszConfiguration of metrics.r   zSequence[MetricReader]additional_readersFr   collect_in_spansN)r   r   r   r   r   r   r   r   r   r   r   r      s   
 r   c                   @  s2   e Zd ZU dZded< 	 ded< 	 dZded< dS )
CodeSourcez,Settings for the source code of the project.r   
repositoryrevision 	root_pathN)r   r   r   r   r   r   r   r   r   r   r      s   
 r   c                   @     e Zd ZdS )DeprecatedKwargsNr   r   r   r   r   r   r   r     s    r   FT)localsend_to_logfirer   service_nameservice_versionenvironmentconsole
config_dirdata_diradditional_span_processorsmetrics	scrubbinginspect_argumentssampling	min_leveladd_baggage_to_attributescode_sourcedistributed_tracingadvancedr   r   r   )bool | Literal['if-token-present'] | Noner   r   r   r   r   r   &ConsoleOptions | Literal[False] | Noner   Path | str | Noner   r   Sequence[SpanProcessor] | Noner   &MetricsOptions | Literal[False] | Noner   (ScrubbingOptions | Literal[False] | Noner   bool | Noner   SamplingOptions | Noner   int | LevelName | Noner   r   CodeSource | Noner   r   AdvancedOptions | Nonedeprecated_kwargsUnpack[DeprecatedKwargs]r   r   c           $      K  s  ddl m}m} |dd}|durtd|dd}|dur$td|dd}|d	u r2td
|dur:td|dd}|dd}|sJ|r]|durRtdtd t||d}|dd}|durltd |dd}|dur|r|tdt|d}td |dd}|durtd dD ]0}||d}|du rq|durtd| dt	d=i ||i}tjd| d| ddd q|d d} | r|
durtd!td" t
| d#}
|d$d}!|!durtd% d&d'lm}" |"|! |rtd(d)| | rt }#nt}#|#jd=i d*|d+|d,|d-|d.|d/|d0|
d1|r2t|ndd2|r<t|ndd3|	d4|d5|d6|d7|d8|d9|d:|d;| | rc||#d<S |S )>ac  Configure the logfire SDK.

    Args:
        local: If `True`, configures and returns a `Logfire` instance that is not the default global instance.
            Use this to create multiple separate configurations, e.g. to send to different projects.
        send_to_logfire: Whether to send logs to logfire.dev.

            Defaults to the `LOGFIRE_SEND_TO_LOGFIRE` environment variable if set, otherwise defaults to `True`.
            If `if-token-present` is provided, logs will only be sent if a token is present.

        token: The project token.

            Defaults to the `LOGFIRE_TOKEN` environment variable.

        service_name: Name of this service.

            Defaults to the `LOGFIRE_SERVICE_NAME` environment variable.

        service_version: Version of this service.

            Defaults to the `LOGFIRE_SERVICE_VERSION` environment variable, or the current git commit hash if available.

        environment: The environment this service is running in, e.g. `'staging'` or `'prod'`. Sets the
            [`deployment.environment.name`](https://opentelemetry.io/docs/specs/semconv/resource/deployment-environment/)
            resource attribute. Useful for filtering within projects in the Logfire UI.

            Defaults to the `LOGFIRE_ENVIRONMENT` environment variable.

        console: Whether to control terminal output. If `None` uses the `LOGFIRE_CONSOLE_*` environment variables,
            otherwise defaults to `ConsoleOption(colors='auto', indent_spans=True, include_timestamps=True, include_tags=True, verbose=False)`.
            If `False` disables console output. It can also be disabled by setting `LOGFIRE_CONSOLE` environment variable to `false`.

        config_dir: Directory that contains the `pyproject.toml` file for this project. If `None` uses the
            `LOGFIRE_CONFIG_DIR` environment variable, otherwise defaults to the current working directory.

        data_dir: Directory to store credentials, and logs. If `None` uses the `LOGFIRE_CREDENTIALS_DIR` environment variable, otherwise defaults to `'.logfire'`.
        additional_span_processors: Span processors to use in addition to the default processor which exports spans to Logfire's API.
        metrics: Set to `False` to disable sending all metrics,
            or provide a `MetricsOptions` object to configure metrics, e.g. additional metric readers.
        scrubbing: Options for scrubbing sensitive data. Set to `False` to disable.
        inspect_arguments: Whether to enable
            [f-string magic](https://logfire.pydantic.dev/docs/guides/onboarding-checklist/add-manual-tracing/#f-strings).
            If `None` uses the `LOGFIRE_INSPECT_ARGUMENTS` environment variable.

            Defaults to `True` if and only if the Python version is at least 3.11.

            Also enables magic argument inspection in [`logfire.instrument_print()`][logfire.Logfire.instrument_print].

        min_level:
            Minimum log level for logs and spans to be created. By default, all logs and spans are created.
            For example, set to 'info' to only create logs with level 'info' or higher, thus filtering out debug logs.
            For spans, this only applies when `_level` is explicitly specified in `logfire.span`.
            Changing the level of a span _after_ it is created will be ignored by this.
            If a span is not created, this has no effect on the current active span, or on logs/spans created inside the
            filtered `logfire.span` context manager.
            If set to `None`, uses the `LOGFIRE_MIN_LEVEL` environment variable; if that is not set, there is no minimum level.
        sampling: Sampling options. See the [sampling guide](https://logfire.pydantic.dev/docs/guides/advanced/sampling/).
        add_baggage_to_attributes: Set to `False` to prevent OpenTelemetry Baggage from being added to spans as attributes.
            See the [Baggage documentation](https://logfire.pydantic.dev/docs/reference/advanced/baggage/) for more details.
        code_source: Settings for the source code of the project.
        distributed_tracing: By default, incoming trace context is extracted, but generates a warning.
            Set to `True` to disable the warning.
            Set to `False` to suppress extraction of incoming trace context.
            See [Unintentional Distributed Tracing](https://logfire.pydantic.dev/docs/how-to-guides/distributed-tracing/#unintentional-distributed-tracing)
            for more information.
            This setting always applies globally, and the last value set is used, including the default value.
        advanced: Advanced options primarily used for testing by Logfire developers.
    rK   )DEFAULT_LOGFIRE_INSTANCEr   
processorsNzThe `processors` argument has been replaced by `additional_span_processors`. Set `send_to_logfire=False` to disable the default processor.metric_readerszThe `metric_readers` argument has been replaced by `metrics=logfire.MetricsOptions(additional_readers=[...])`. Set `send_to_logfire=False` to disable the default metric reader.collect_system_metricsFzjThe `collect_system_metrics` argument has been removed. System metrics are no longer collected by default.zjThe `collect_system_metrics` argument has been removed. Use `logfire.instrument_system_metrics()` instead.scrubbing_callbackscrubbing_patternszsCannot specify `scrubbing` and `scrubbing_callback` or `scrubbing_patterns` at the same time. Use only `scrubbing`.zThe `scrubbing_callback` and `scrubbing_patterns` arguments are deprecated. Use `scrubbing=logfire.ScrubbingOptions(callback=..., extra_patterns=[...])` instead.)callbackextra_patternsproject_namez9The `project_name` argument is deprecated and not needed.trace_sample_ratezkCannot specify both `trace_sample_rate` and `sampling`. Use `sampling.head` instead of `trace_sample_rate`.headziThe `trace_sample_rate` argument is deprecated. Use `sampling=logfire.SamplingOptions(head=...)` instead.show_summaryzThe `show_summary` argument is deprecated. Use `console=False` or `console=logfire.ConsoleOptions(show_project_link=False)` instead.)r   r   r   zCannot specify `z&` and `advanced`. Use only `advanced`.zThe `z@` argument is deprecated. Use `advanced=logfire.AdvancedOptions(z=...)` instead.)
stackleveladditional_metric_readerszCannot specify both `additional_metric_readers` and `metrics`. Use `metrics=logfire.MetricsOptions(additional_readers=[...])` instead.zThe `additional_metric_readers` argument is deprecated. Use `metrics=logfire.MetricsOptions(additional_readers=[...])` instead.)r   pydantic_pluginzZThe `pydantic_plugin` argument is deprecated. Use `logfire.instrument_pydantic()` instead.r   )set_pydantic_plugin_configz.configure() got unexpected keyword arguments: z, r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   )configr   )r   r   r   pop
ValueErrorwarningswarnrt   rH   r   r   logfire.integrations.pydanticr   	TypeErrorjoinLogfireConfigGLOBAL_CONFIG	configurer   )$r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   keyvaluer   r   r   r   r   r   r   r   
  s   [


	

r   c                   @  s   e Zd ZU dZded< 	 ded< 	 ded< 	 ded< 	 ded	< 	 d
ed< 	 ded< 	 ded< 	 ded< 	 ded< 	 ded< 	 ded< 	 ded< 	 ded< 	 ded< 	 ded< 	 d-d*d+Zd,S )._LogfireConfigDataa  Data-only parent class for LogfireConfig.

    This class can be pickled / copied and gives a nice repr,
    while allowing us to keep the ugly stuff only in LogfireConfig.

    In particular, using this dataclass as a base class of LogfireConfig allows us to use
    `dataclasses.asdict` in `integrations/executors.py` to get a dict with just the attributes from
    `_LogfireConfigData`, and none of the attributes added in `LogfireConfig`.
    z"bool | Literal['if-token-present']r   r   r   r   r   r   r   r   r   r   r   r   r   z!ScrubbingOptions | Literal[False]r   r   r   rH   r   intr   r   r   r   r   r   r   r   r   r   Path | Noner   r   r   r   r   r   r   Nonec              
   C  s  t | | _}|d|| _|d|| _|d|| _|d|| _|d|| _|d|| _	|d|| _
|d|| _|d	| _|d
|}|du rSd}n	t|tr\t| }|| _|| _t|trntdi |}|du rut }|| _|rt|j|jnt| _t|trtdi |}|dur|| _n,|ddu rd| _n!t|d|d|d|d|d|d|dd| _t|trtdi |}n|du rt|dd}|| _t|trtdi |}|| _t|trt di |}|j!}t|trt"|# ddgkrt$di ||_!n|du r&t |dd}|| _%|	| _&|
du r4t' }
|
| _(| jdu rPzt) | _W dS  t*yO   Y dS w dS )zNMerge the given parameters with the environment variables file configurations.r   r   r   r   r   r   r   r   ignore_no_configr   Nr   r   Fconsole_colorsconsole_span_styleconsole_include_timestampconsole_include_tagsconsole_verboseconsole_min_log_levelconsole_show_project_link)r   r   r   r   r   r   r   r   r   seed_ms_timestamp_generatorr   )r   r   )+rS   createparam_manager
load_paramr   r   r   r   r   r   r   r   r   
isinstancer   rU   r   r   dictrt   r   rs   r   r   rq   scrubberr   r   rH   r   r   r   r   r   listkeysry   r   r   r   r   get_git_revision_hash	Exception)r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r  r   r   r   r   _load_configuration+  s   





"

z&_LogfireConfigData._load_configurationN&r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   )r   r   r   r   r   r  r   r   r   r   r     sF   
 
r   c                   @  s   e Zd Z																		dIdJd$d%ZdJd&d'ZdKd(d)ZdKd*d+ZdLdMd/d0ZdNd2d3ZdOd5d6Z	dPd8d9Z
dQd;d<ZdRd?d@ZdSdBdCZdDdE ZdTdGdHZdS )Ur   NTr   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   c                 C  s   | j di d|d|d|d|d|d|d|d|d	|	d
|
d|d|d|d|d|d|d|d| tt | | _tt | _tt	 | _
zddlm} || j
| _W n tyj   d| _Y nw d| _d| _t | _dS )zCreate a new LogfireConfig.

        Users should never need to call this directly, instead use `logfire.configure`.

        See `_LogfireConfigData` for parameter documentation.
        r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   NFr   )r  rx   r   NoOpTracerProvider_tracer_providerrp   r   _meter_providerro   r   _logger_provideropentelemetry.sdk._eventsr   _event_logger_providerImportError_has_set_providers_initializedr   _lock)r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   SDKEventLoggerProviderr   r   r   __init__  sb   
	

zLogfireConfig.__init__c                 C  sf   | j & d| _| |||||||||	|
|||||||| |   W d    d S 1 s,w   Y  d S )NF)r  r  r  
initialize)r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r     s0   
"zLogfireConfig.configurec                 C  s4   | j  |   W d   dS 1 sw   Y  dS )z:Configure internals to start exporting traces and metrics.N)r  _initializer   r   r   r   r"    s   
"zLogfireConfig.initializec           *        s  j rd S t }t  jt tjjt	 tj
d}jr6|tjjtjji jjr6jj|t< jr>j|d< jrFj|t< tt}|rf|dD ]}|jddd\}}| || < qRt|v rtt|v rtt |t< |r{t|nt|tdt ji j!j"}d }t#|t$t%fr|dk rt&|}n|}t'|j(j)d	j*+  j*,	 g t-  }	j!j.rt/|	j!j.}		0t1t2|	j3 d8fdd}
j4r|
t5  j6d urj6D ]}|
| qt7j(j8}j9rAj9j:dkrt;}nj9j:dkrt<}nj9j:dksJ t=}|j9j>j9j?j9j@j9jAj9jBj9jCd}|
tD| |EtFtG| d }t#jHtIrPt7jHjJ}jKraj9r]j9jLp^dztMNjO}W n tPyx   jQst d }Y nw jQsjKdu r|d u rtRSj(jT}tMjU|d}|VjO |d urjQp|jQ_Qj(jTp|jWj(_TjQra|rɈjQ|jQkrɈr|X  dfdd}|r|  n
tY|dd}|Z  j([jQ}dt\ jQd}t] }t^t_|d|t`ja|d}tb|}tc|}td|}|rtD|}nte|}|
| |d ur:|s:|Etftgtht_|d||t`jatidtid  tjt_|d!||t`jad"}tk|}|rRtF|}ntl|}|E| |jm| rt- }D ]}|0| qi0tnj(j)t2|j3 tto}ttp}ttq}ttr}ttsd#t } ttud#t }!ttvd#t }"|s|r| d$v r|
twtx  |s|r|!d$v r|d ur|tfth g7 }|s|r|"d$v r|rtFtj }ntltj }|E| |d urty|tzt{t| d%tzt}d&h d'd(gd)nt~ ttd*r'	fd+d,}#tj|#d- jj+d.d/ j t }$|D ]}|$| q9tt|$j3}%t|% jr]j+  nj+  j, jj tu rjsd_tj* tj tj jrd0d1lm}& |&j tjd2d3  tjd9 fd6d7}'|'t_d_ t  t }(t#|(ttfr|(j}(t#|(ttfsjd u rt|(})njr|(})nt|(})t|)   W d    d S 1 sw   Y  d S ):N)zservice.nameprocess.pidzprocess.runtime.namezprocess.runtime.versionzprocess.runtime.descriptionzservice.version,=rO   )maxsplitzservice.instance.id)samplerresourcer   span_processorr6   r   r   c                   s8     |  tt| dd tttf}|r|  d S d S )Nspan_exporter)add_span_processorr  getattrrm   rl   r`   append)r+  has_pending)main_multiprocessorprocessors_with_pending_spansr   r   r-  e  s   

z5LogfireConfig._initialize.<locals>.add_span_processorsimpleindentedr   )r   include_timestampr   r   r   r   FTclientc                    s`    j d usJ t    j } W d    n1 sw   Y  r,| d ur.|   d S d S d S r   )r   r}   "_initialize_credentials_from_tokenprint_token_summary)validated_credentials)r   r   r   r   check_token  s   z.LogfireConfig._initialize.<locals>.check_tokencheck_logfire_token)targetnamer   )r   Authorizationz
/v1/traces)endpointsessioncompressionheadersz/v1/metrics)r@  rC  rA  rB  preferred_temporality)rD  z/v1/logs)r@  rA  rC  rB  r   )otlpr   )instrument_typeaggregationzhttp.server.active_requests>   
url.schemehttp.flavorhttp.methodhttp.schemehttp.request.method)rF  instrument_nameattribute_keys)r   r*  viewsregister_at_forkc                    sR   t  tdt i} | _| _|  _W d    d S 1 s"w   Y  d S )Nr%  )r{   merger5   osgetpid	_resource)new_resource)logger_providermeter_providerr*  tracer_providerr   r   fix_pidB  s   "z*LogfireConfig._initialize.<locals>.fix_pid)after_in_child   timeout_millisr   )set_event_logger_providerc                  S  s(   t t D ]} |   dd | _qd S )Nc                  _  s   d S r   r   )___r   r   r   r   |  s    zDLogfireConfig._initialize.<locals>.exit_open_spans.<locals>.<lambda>)r  rv   valuesend)spanr   r   r   exit_open_spansn  s   	z2LogfireConfig._initialize.<locals>.exit_open_spanscoder   c                   s*   z      W | S    Y | S r   )force_flush)re  )rd  original_os_exitr   r   r   patched_os_exit  s   
z2LogfireConfig._initialize.<locals>.patched_os_exit)r+  r6   r   r   )re  r   )r  r|   r}   r   rR  rS  sysimplementationr>  get_runtime_versionversionr   updaterZ   r   rY   r   r   rV   r   r   rX   getenvr(   splitstripgetcwdrW   r5   r
  r   hexrQ  r   r   r  r   floatr<   SDKTracerProviderr   r   r  shutdownset_providerr7   tailrI   r-  ri   rj   r  r   rF   r   r  r   r   r   r`   r^   r_   r   r   r   r   r   r   r:   r/  r#   r]   r   r   r   r   r   LogfireCredentialsload_creds_filer   r  r   rQ   from_urlr   initialize_projectwrite_creds_filelogfire_api_urlr9  r	   startr   rJ   re   rd   r   r   Gziprg   rh   rl   ra   r2   rk   r   METRICS_PREFERRED_TEMPORALITYr   rf   r"   rC  rw   r$   r'   r&   r%   r   lowerr   r   r9   r   r+   r4   r*   r3   r/   r   hasattrrP  r  r   r!   add_log_record_processorrb   rc   SDKLoggerProviderr  r  set_min_levelr   r   r  r   set_tracer_providerr   opentelemetry._eventsr^  atexitregister_exitrn   r   rM   rL   wrappedr   r   _ensure_flush_after_aws_lambda)*r   
emscriptenotel_resource_attributes!otel_resource_attributes_from_env_fieldr   r   r   r)  root_processorr-  	processorr   exporter_clsconsole_span_exporterr   credentialsr7  r;  threadr   rC  rA  r,  logfire_processorlog_exporterlogfire_log_processorpending_multiprocessorotlp_endpointotlp_traces_endpointotlp_metrics_endpointotlp_logs_endpointotlp_traces_exporterotlp_metrics_exporterotlp_logs_exporterrY  multi_log_processorroot_log_processorr^  rh  current_textmapnew_textmapr   )
rd  rV  r1  rW  rg  r2  r*  r   r   rX  r   r#    s  









	




	





















   $zLogfireConfig._initialize0u  r]  r   c                 C  s6   | j | | j| | jr| j| | j|S )zForce flush all spans and metrics.

        Args:
            timeout_millis: The timeout in milliseconds.

        Returns:
            Whether the flush of spans was successful.
        )r  rf  r  r  r  )r   r]  r   r   r   rf    s
   	zLogfireConfig.force_flushrx   c                 C     | j S )zGet a tracer provider from this `LogfireConfig`.

        This is used internally and should not be called by users of the SDK.

        Returns:
            The tracer provider.
        )r  r$  r   r   r   get_tracer_provider     z!LogfireConfig.get_tracer_providerrp   c                 C  r  )zGet a meter provider from this `LogfireConfig`.

        This is used internally and should not be called by users of the SDK.

        Returns:
            The meter provider.
        )r  r$  r   r   r   get_meter_provider  r  z LogfireConfig.get_meter_providerro   c                 C  r  )zGet a logger provider from this `LogfireConfig`.

        This is used internally and should not be called by users of the SDK.

        Returns:
            The logger provider.
        )r  r$  r   r   r   get_logger_provider  r  z!LogfireConfig.get_logger_providerEventLoggerProvider | Nonec                 C  r  )zGet an event logger provider from this `LogfireConfig`.

        This is used internally and should not be called by users of the SDK.

        Returns:
            The event logger provider.
        )r  r$  r   r   r   get_event_logger_provider  r  z'LogfireConfig.get_event_logger_providermessager   c                 C  sF   t dd}| dv p| j}| js|s!t| dtd d S d S d S )NLOGFIRE_IGNORE_NO_CONFIGr   )1truetz until `logfire.configure()` has been called. Set the environment variable LOGFIRE_IGNORE_NO_CONFIG=1 or add ignore_no_config=true in pyproject.toml to suppress this warning.)category)rR  rn  r  r   r  ru   LogfireNotConfiguredWarning)r   r  ignore_no_config_envr   r   r   r   warn_if_not_initialized  s   

z%LogfireConfig.warn_if_not_initializedLogfireCredentials | Nonec                 C  s   t |t | j|S r   )rx  
from_tokenrequestsSessionr   r   r   r   r   r   r8    s   z0LogfireConfig._initialize_credentials_from_tokenc                   s   d fdd}t tj D ]k}zt|dd}W n	 ty!   Y qw |s%qz||j|_||j|_W q tyy } z:tt t	|t
rJ|jdksW	 W d   W Y d}~qW d   n1 saw   Y  ddl}|| W Y d}~qd}~ww dS )	a  Ensure that `force_flush` is called after an AWS Lambda invocation.

        This way Logfire will just work in Lambda without the user needing to know anything.
        Without the `force_flush`, spans may just remain in the queue when the Lambda runtime is frozen.
        client_methodr   c                   s   t  d fdd}|S )Nargsr   kwargsr   c                    sB   zj dd W n ty   dd l}|  Y nw  | i |S )Ni  r\  r   )rf  r  	traceback	print_exc)r  r  r  )r  r   r   r   wrapper  s   ziLogfireConfig._ensure_flush_after_aws_lambda.<locals>.wrap_client_post_invocation_method.<locals>.wrapper)r  r   r  r   r   r   )	functoolswraps)r  r  r$  )r  r   "wrap_client_post_invocation_method  s   
zXLogfireConfig._ensure_flush_after_aws_lambda.<locals>.wrap_client_post_invocation_methodLambdaRuntimeClientNr   )r  r   )r  ri  modulesra  r.  r  post_invocation_errorpost_invocation_resultr   r  typer   r  print_exception)r   r  modr7  er  r   r$  r   r    s0   
z,LogfireConfig._ensure_flush_after_aws_lambdascopesc                 G  s(   | j j|  | jj|  | jj|  d S r   )r  suppress_scopesr  r  )r   r  r   r   r   r    s   zLogfireConfig.suppress_scopes)NNNNNNNNNNNNNNTNNNr  r   r   )r  )r]  r   r   r   )r   rx   )r   rp   )r   ro   )r   r  )r  r   )r   r   r   r  )r  r   r   r   )r   r   r   r!  r   r"  r#  rf  r  r  r  r  r  r8  r  r  r   r   r   r   r     sF    
C
-
   










4r   c                   @  s   e Zd ZU dZded< 	 ded< 	 ded< 	 ded< 	 ed,ddZed-ddZedddd.ddZeddddd/d"d#Z	ed0d%d&Z
d1d(d)Zd2d*d+ZdS )3rx  zCredentials for logfire.dev.r   r   r   project_urlr}  	creds_dirr   r   Self | Nonec              
   C  s   t |}| rkz|d}t|}W d   n1 sw   Y  W n ttfy: } ztd| |d}~ww z|dd}|durL|	d| | di |W S  t
yj } ztd| d| |d}~ww dS )aB  Check if a credentials file exists and if so load it.

        Args:
            creds_dir: Path to the credentials directory.

        Returns:
            The loaded credentials or `None` if the file does not exist.

        Raises:
            LogfireConfigError: If the credentials file exists but is invalid.
        rbNzInvalid credentials file: dashboard_urlr  z - r   )_get_creds_fileexistsopenjsonloadr   OSErrorrG   r   
setdefaultr   )clsr  pathfdatar  r  r   r   r   ry  0  s*   z"LogfireCredentials.load_creds_filerA  requests.Sessionr   c              
   C  s   z|j t|ddi td|id}W n tjy/ } ztd|  W Y d}~dS d}~ww |jdkr`z| d }W n t	yQ   td	|j d
 Y dS w td	|j d|  dS | }| ||d |d |dS )aH  Check that the token is valid.

        Issue a warning if the Logfire API is unreachable, or we get a response other than 200 or 401.

        We continue unless we get a 401. If something is wrong, we'll later store data locally for back-fill.

        Raises:
            LogfireConfigError: If the token is invalid.
        z/v1/info
   r?  )timeoutrC  zFLogfire API is unreachable, you may have trouble sending data. Error: Nr[  detailz!Logfire API returned status code z$, you may have trouble sending data.z
. Detail: r   r  )r   r   r  r}  )
getr   COMMON_REQUEST_HEADERSr  RequestExceptionr   r   status_coder  r  )r  r   rA  r   responser  r  r  r   r   r   r  N  s>   

zLogfireCredentials.from_tokenNorganizationr   r7  rQ   projectslist[dict[str, Any]]r  r   dict[str, Any] | Nonec                  s  d}d}d}|}t tjd}	 dur& fdd|D }d  d}d	  }dur9d
 d}fdd|D }durPt|dkrP|d d  |d d nH|s|s[|	d dS tjd| d| dddgdddkr||	d| d| d dS |}d dndur du r|	d| d d d du sdu rdd t|D }
ddd |
	 D }tjd| dt
|
 d d}|
| }|d  |d | S )!a  Configure one of the user projects to be used by Logfire.

        It configures the project if organization/project_name is a valid project that
        the user has access to it. Otherwise, it asks the user to select a project interactively.

        Args:
            client: The Logfire client to use when making requests.
            projects: List of user projects.
            organization: Project organization.
            project_name: Name of project that has to be used.

        Returns:
            The configured project information.

        Raises:
            LogfireConfigError: If there was an error configuring the project.
        r   r  )fileNc                      g | ]
}|d   kr|qS organization_namer   .0p)r  r   r   
<listcomp>      z;LogfireCredentials.use_existing_project.<locals>.<listcomp>z in organization ``z --org zprojects with name `c                   r  r   r   r  r  r   r   r    r  rO   r   r  r   z`No projects found for the current user. You can create a new project with `logfire projects new`zNo z found for the current userz. Choose from all projects?ynchoicesdefaultzYou can create a new projectz with `logfire projects newzFound multiple .c                 S  s*   i | ]\}}t |d  |d |d fqS )rO   r  r   )r   r  indexitemr   r   r   
<dictcomp>  s    z;LogfireCredentials.use_existing_project.<locals>.<dictcomp>
c                 S  s,   g | ]\}}| d |d  d|d  qS )z. r   /rO   r   r  r   r   r   r    s   , z7Please select one of the following projects by number:
r  )r?   ri  stderrlenprintrA   ask	enumerater   itemsr  r  create_write_token)r  r7  r  r  r   org_messageorg_flagproject_messagefiltered_projectsr   project_choicesproject_choices_strselected_project_keyproject_info_tupler   r  r   use_existing_projectx  sj   


z'LogfireCredentials.use_existing_projectF)r  default_organizationr   r  r   dict[str, Any]c             
   C  sV  dd |  D }||vrLt|dkr4| }|di d}|r'|r'|}n%tjd||p0|d d}n|d }|sLtjd	| d
dd}|sLtd t	 }	d}
	 |pZtj|
|	d}|rrt
t|srtjd|	d}|rrt
t|rcz	|||}W |S  ty   d}	d| d}
d}Y qQ ty } zd}	d|j d}
d}W Y d}~qQd}~ww )a  Create a new project and configure it to be used by Logfire.

        It creates the project under the organization if both project and organization are valid.
        Otherwise, it asks the user to select organization and enter a valid project name interactively.

        Args:
            client: The Logfire client to use when making requests.
            organization: The organization name of the new project.
            default_organization: Whether to create the project under the user default organization.
            project_name: The default name of the project.

        Returns:
            The created project information.

        Raises:
            LogfireConfigError: If there was an error creating projects.
        c                 S  s   g | ]}|d  qS r  r   )r  r   r   r   r   r    s    z9LogfireCredentials.create_new_project.<locals>.<listcomp>rO   r  r  z|
To create and use a new project, please provide the following information:
Select the organization to create the project inr   r  z1The project will be created in the organization "z". Continue?Tr  zEnter the project namez
The project name you've entered is invalid. Valid project names:
  * may contain lowercase alphanumeric characters
  * may contain single hyphens
  * may not start or end with a hyphen

Enter the project name you want to use:.z
A project with the name 'z7' already exists. Please enter a different project nameNz*
The project name you entered is invalid:
z&
Please enter a different project name)get_user_organizationsr  get_user_informationr  rA   r  r@   ri  exitdefault_project_namerematchPROJECT_NAME_PATTERNcreate_new_projectrR   rP   reason)r  r7  r  r  r   organizationsuser_detailsuser_default_organization_nameconfirmproject_name_defaultproject_name_promptprojectexcr   r   r   r    s`   



z%LogfireCredentials.create_new_projectrB   c             
   C  s   d}t d | }|rtjddd}|r| j||d}|s$| j|d}z| di |d|ji}td	|j d
 |W S  t	yQ } zt
d| |d}~ww )a\  Create a new project or use an existing project on logfire.dev requesting the given project name.

        Args:
            client: The Logfire client to use when making requests.

        Returns:
            The new credentials.

        Raises:
            LogfireConfigError: If there was an error on creating/configuring the project.
        NzbNo Logfire project credentials found.
All data sent to Logfire must be associated with a project.
z2Do you want to use one of your existing projects? Tr  )r7  r  r6  r}  zBProject initialized successfully. You will be able to view it at: z
Press Enter to continuez0Invalid credentials, when initializing project: r   )r  get_user_projectsr@   r  r  r  r   rA   r  r   rG   )r  r7  r  r  use_existing_projectsresultr  r   r   r   r{  .  s*   z%LogfireCredentials.initialize_projectr   c                 C  s6   t | t| }t|}|tj|ddd  dS )z+Write a credentials file to the given path.rK   )indentr  N)rz   r   asdictr  
write_textr  dumps)r   r  r  r  r   r   r   r|  Y  s   
z#LogfireCredentials.write_creds_filec                 C  s2   | j rtd| j  d| j  dt| j d dS dS )z(Print a summary of the existing project.z([bold]Logfire[/bold] project URL: [link=z cyan]z[/link])min_content_widthN)r  _print_summaryr  r$  r   r   r   r9  `  s   
z&LogfireCredentials.print_token_summary)r  r   r   r  )r   r   rA  r  r   r   r   r  )
r7  rQ   r  r  r  r   r   r   r   r  )
r7  rQ   r  r   r  r   r   r   r   r  )r7  rQ   r   rB   )r  r   r   r   r  )r   r   r   r   r   classmethodry  r  r  r  r{  r|  r9  r   r   r   r   rx  #  s6   
 )^V
*rx  r  r   r/  r   r   c                 C  sh   ddl m} ddlm} ddlm} |d|ddi}|d|d	}|j|d
 k r-|d
 |_||  d S )Nr   r>   )Style)Themezmarkdown.link_urlcyan)colorT)r  theme   )rich.consoler?   
rich.styler2  
rich.themer3  widthr  )r  r/  r?   r2  r3  custom_themer   r   r   r   r0  i  s   
r0  r  r   c                 C  s   | t  S )z%Get the path to the credentials file.)CREDENTIALS_FILENAME)r  r   r   r   r  v  s   r  c                 C  sL   d}t |  }r |d}|dkrdS |dkrdS |tvr d}t| d S )z-Get the base API URL from the token's region.usregion	stagingusz https://logfire-us.pydantic.info	stagingeuz https://logfire-eu.pydantic.infor   )rD   r  grouprE   )r   r?  r  r   r   r   r   {  s   
r   c                  C  s&   ddl } | jg d| jdd S )z Get the current git commit hash.r   N)gitz	rev-parseHEAD)r  ascii)
subprocesscheck_outputSTDOUTdecoderp  )rF  r   r   r   r    s   r  r>  c                 C  s   t dd|  dd pdS )zSConvert `name` to a string suitable for the `requested_project_name` API parameter.z[^a-zA-Z0-9]r   N)   untitled)r  subr  )r>  r   r   r   sanitize_project_name  s   rM  c                   C  s   t tjt S r   )rM  rR  r  basenamerq  r   r   r   r   r    s   r  c                  C  s@   t jj} | jdkr| jsdtt| d d S dtt| S )Nfinalr     )ri  rj  rl  releaselevelserialr   mapr   )version_infor   r   r   rk    s   rk  c                   @  r   )r  Nr   r   r   r   r   r    s    r  )*r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   )r  r   r/  r   r   r   )r  r   r   r   r   )r   r   )r>  r   r   r   )
__future__r   _annotationsr  r   r  r  rR  r  ri  r   r   collections.abcr   
contextlibr   r   r   pathlibr   	threadingr   r	   typingr
   r   r   r   r   urllib.parser   uuidr   r  opentelemetryr   opentelemetry._logsr   r   #opentelemetry.environment_variablesr   r   r   &opentelemetry.exporter.otlp.proto.httpr   4opentelemetry.exporter.otlp.proto.http._log_exporterr   6opentelemetry.exporter.otlp.proto.http.metric_exporterr   5opentelemetry.exporter.otlp.proto.http.trace_exporterr   opentelemetry.metricsr   r   opentelemetry.propagater   r   opentelemetry.sdk._logsr   r  r    !opentelemetry.sdk._logs._internalr!   opentelemetry.sdk._logs.exportr"   r#   'opentelemetry.sdk.environment_variablesr$   r%   r&   r'   r(   opentelemetry.sdk.metricsr)   r*   r+   r,   r-   r.   r/    opentelemetry.sdk.metrics.exportr0   r1   r2   opentelemetry.sdk.metrics.viewr3   r4   opentelemetry.sdk.resourcesr5   opentelemetry.sdk.tracer6   r7   r8   rt  opentelemetry.sdk.trace.exportr9   r:   $opentelemetry.sdk.trace.id_generatorr;    opentelemetry.sdk.trace.samplingr<   r=   r8  r?   rich.promptr@   rA   typing_extensionsrB   rC   logfire._internal.authrD   rE   logfire._internal.baggagerF   logfire.exceptionsrG   logfire.samplingrH   logfire.sampling._tail_samplingrI   logfire.versionrJ   	propagaterL   rM   typesrN   r7  rP   rQ   rR   config_paramsrS   rT   	constantsrU   rV   rW   rX   rY   rZ   r[   exporters.consoler\   r]   r^   r_   r`   exporters.dynamic_batchra   exporters.logsrb   rc   exporters.otlprd   re   rf   rg   rh   exporters.processor_wrapperri   rj   exporters.quiet_metricsrk   exporters.remove_pendingrl   exporters.testrm   integrations.executorsrn   logsro   r   rp   r   rq   rr   rs   rt   
stack_inforu   tracerrv   rw   rx   utilsry   rz   r{   r|   r}   r~   r  r   mainr   r=  r  r  DELTA
CUMULATIVEr  r   r   r   r   r   r   r   r   r   r   rx  r0  r  r   r  rM  r  rk  UserWarningr  r   r   r   r   <module>   s   $	$	!
 f ,     
  
G




