
    	]jQ                         d 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	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 dd	lmZ  ed
i       ZdddddddddefddddfZg dZ G d de      Z G d de      Zy)zDefine API Loggers.    N)InvalidArgument)	DebugInfo)_add_defaults_to_filter)_add_instrumentation)LogEntryProtobufEntryStructEntry	TextEntry)detect_resource)Resourceglobal)typelabels)type_N)log_nameN)payloadN)r   N)	insert_idN)severityN)http_requestN)	timestampNresource)traceN)span_idN)trace_sampledN)source_locationN)r   r   r   c                       e Zd ZdZddddZed        Zed        Zed        Zed        Z	d	 Z
dd
dZddZdd
dZdd
dZdd
dZdd
dZddd
dZddd
dZddddddddZy)LoggerzLoggers represent named targets for log entries.

    See https://cloud.google.com/logging/docs/reference/v2/rest/v2/projects.logs
    N)r   r   c                j    |st        |j                        }|| _        || _        || _        || _        y)aI  
        Args:
            name (str): The name of the logger.
            client (~logging_v2.client.Client):
                A client which holds credentials and project configuration
                for the logger (which requires a project).
            resource (Optional[~logging_v2.Resource]): a monitored resource object
                representing the resource the code was run on. If not given, will
                be inferred from the environment.
            labels (Optional[dict]): Mapping of default labels for entries written
                via this logger.

        N)r   projectname_clientr   default_resource)selfr    clientr   r   s        H/root/env/lib/python3.12/site-packages/google/cloud/logging_v2/logger.py__init__zLogger.__init__@   s2     &v~~6H	 (    c                     | j                   S )zClent bound to the logger.r!   r#   s    r%   r$   zLogger.clientV   s     ||r'   c                 .    | j                   j                  S )zProject bound to the logger.)r!   r   r*   s    r%   r   zLogger.project[   s     ||###r'   c                 :    d| j                    d| j                   S )z)Fully-qualified name used in logging APIs	projects/z/logs/)r   r    r*   s    r%   	full_namezLogger.full_name`   s     4<<.tyyk::r'   c                      d| j                    S )z URI path for use in logging APIs/)r.   r*   s    r%   pathzLogger.pathe   s     4>>"##r'   c                 "    || j                   }|S )a  Check client or verify over-ride. Also sets ``parent``.

        Args:
            client (Union[None, ~logging_v2.client.Client]):
                The client to use.  If not passed, falls back to the
                ``client`` stored on the current sink.

        Returns:
            ~logging_v2.client.Client: The client passed in
                or the currently bound client.
        r)   r#   r$   s     r%   _require_clientzLogger._require_clientj   s     >\\Fr'   )r$   c                <    | j                  |      }t        | |      S )aF  Return a batch to use as a context manager.

        Args:
            client (Union[None, ~logging_v2.client.Client]):
                The client to use.  If not passed, falls back to the
                ``client`` stored on the current sink.

        Returns:
            Batch: A batch to use as a context manager.
        )r4   Batchr3   s     r%   batchzLogger.batchz   s!     %%f-T6""r'   c                 "   | j                  |      }|j                  d| j                        |d<   |j                  d| j                        |d<   |j                  d| j                        |d<   |j                  dd      }t        |t              r|j                         |d<   t        |d   t        j                  j                        r	 t        di |d   |d<   | |dd|i|}n |di |}|j                         }|g}	t        j                   j"                  j$                  du r+t'        |	fi |}	d	t        j                   j"                  _        |j(                  j+                  |	d	
       y# t        $ r}t        d      |d}~ww xY w)z4Helper for :meth:`log_empty`, :meth:`log_text`, etc.r   r   r   r   Nzinvalid resource dictr   FT)partial_success )r4   popr.   r   r"   get
isinstancestruppercollectionsabcMappingr   	TypeErrorto_api_reprgooglecloud
logging_v2_instrumentation_emittedr   logging_apiwrite_entries)
r#   r$   _entry_classr   kwr   eentryapi_reprentriess
             r%   _do_logzLogger._do_log   sk   %%f- 
DNN;:vvh48
D,A,AB:66*d+h$%^^-BzNbnkoo&=&=>@!)!;BzN!;:
  77B7E &2&E$$&*<<"";;uD*79b9G?CFLL##<(($(G!  @ 78a?@s   E4 4	F=F		Fc                4     | j                   |t        fi | y)a  Log an empty message

        See
        https://cloud.google.com/logging/docs/reference/v2/rest/v2/entries/write

        Args:
            client (Optional[~logging_v2.client.Client]):
                The client to use.  If not passed, falls back to the
                ``client`` stored on the current sink.
            kw (Optional[dict]): additional keyword arguments for the entry.
                See :class:`~logging_v2.entries.LogEntry`.
        N)rQ   r   )r#   r$   rL   s      r%   	log_emptyzLogger.log_empty   s     	VX,,r'   c                6     | j                   |t        |fi | y)a  Log a text message

        See
        https://cloud.google.com/logging/docs/reference/v2/rest/v2/entries/write

        Args:
            text (str): the log message
            client (Optional[~logging_v2.client.Client]):
                The client to use.  If not passed, falls back to the
                ``client`` stored on the current sink.
            kw (Optional[dict]): additional keyword arguments for the entry.
                See :class:`~logging_v2.entries.LogEntry`.
        N)rQ   r
   )r#   textr$   rL   s       r%   log_textzLogger.log_text   s     	VY33r'   c                p    t         D ]  }||v s||vs||   ||<     | j                  |t        |fi | y)aa  Logs a dictionary message.

        See
        https://cloud.google.com/logging/docs/reference/v2/rest/v2/entries/write

        The message must be able to be serializable to a Protobuf Struct.
        It must be a dictionary of strings to one of the following:

            - :class:`str`
            - :class:`int`
            - :class:`float`
            - :class:`bool`
            - :class:`list[str|float|int|bool|list|dict|None]`
            - :class:`dict[str, str|float|int|bool|list|dict|None]`

        For more details on Protobuf structs, see https://protobuf.dev/reference/protobuf/google.protobuf/#value.
        If the provided dictionary cannot be serialized into a Protobuf struct,
        it will not be logged, and a :class:`ValueError` will be raised.

        Args:
            info (dict[str, str|float|int|bool|list|dict|None]):
                the log entry information.
            client (Optional[~logging_v2.client.Client]):
                The client to use.  If not passed, falls back to the
                ``client`` stored on the current sink.
            kw (Optional[dict]): additional keyword arguments for the entry.
                See :class:`~logging_v2.entries.LogEntry`.

        Raises:
            ValueError:
                if the dictionary message provided cannot be serialized into a Protobuf
                struct.
        N)_STRUCT_EXTRACTABLE_FIELDSrQ   r	   )r#   infor$   rL   fields        r%   
log_structzLogger.log_struct   sG    D 0 	(E}b K5		( 	V[$5"5r'   c                6     | j                   |t        |fi | y)a3  Log a protobuf message

        See
        https://cloud.google.com/logging/docs/reference/v2/rest/v2/entries/list

        Args:
            message (google.protobuf.message.Message):
                The protobuf message to be logged.
            client (Optional[~logging_v2.client.Client]):
                The client to use.  If not passed, falls back to the
                ``client`` stored on the current sink.
            kw (Optional[dict]): additional keyword arguments for the entry.
                See :class:`~logging_v2.entries.LogEntry`.
        N)rQ   r   r#   messager$   rL   s       r%   	log_protozLogger.log_proto   s     	V]G:r:r'   c                ~   t        |t        j                  j                  j                        r | j
                  |fd|i| yt        |t        j                  j                        r | j                  |fd|i| yt        |t              r | j                  |fd|i| y | j                  |t        |fi | y)aR  Log an arbitrary message. Type will be inferred based on the input.

        See
        https://cloud.google.com/logging/docs/reference/v2/rest/v2/entries/list

        Args:
            message (Optional[str or dict or google.protobuf.Message]): The message. to log
            client (Optional[~logging_v2.client.Client]):
                The client to use.  If not passed, falls back to the
                ``client`` stored on the current sink.
            kw (Optional[dict]): additional keyword arguments for the entry.
                See :class:`~logging_v2.entries.LogEntry`.
        r$   N)r=   rE   protobufr^   Messager_   r@   rA   rB   r[   r>   rV   rQ   r   r]   s       r%   logz
Logger.log  s     gv66>>?DNN7868R8!8!89DOOG9F9b9%DMM'7&7B7DLL79b9r'   c                x    | j                  |      }|| j                  }|j                  j                  |       y)a  Delete all entries in a logger via a DELETE request

        See
        https://cloud.google.com/logging/docs/reference/v2/rest/v2/projects.logs/delete

        Args:
            logger_name (Optional[str]):  The resource name of the log to delete:

                ::

                    "projects/[PROJECT_ID]/logs/[LOG_ID]"
                    "organizations/[ORGANIZATION_ID]/logs/[LOG_ID]"
                    "billingAccounts/[BILLING_ACCOUNT_ID]/logs/[LOG_ID]"
                    "folders/[FOLDER_ID]/logs/[LOG_ID]"

                ``[LOG_ID]`` must be URL-encoded. For example,
                ``"projects/my-project-id/logs/syslog"``,
                ``"organizations/1234567890/logs/cloudresourcemanager.googleapis.com%2Factivity"``.
                If not passed, defaults to the project bound to the client.
            client (Optional[~logging_v2.client.Client]):
                The client to use.  If not passed, falls back to the
                ``client`` stored on the current logger.
        N)r4   r.   rI   logger_delete)r#   logger_namer$   s      r%   deletezLogger.delete  s7    0 %%f-..K((5r'   resource_namesfilter_order_bymax_results	page_size
page_tokenc                    |d| j                    g}d| j                   }|| d| }n|}t        |      }| j                  j	                  ||||||      S )a)  Return a generator of log entry resources.

        See
        https://cloud.google.com/logging/docs/reference/v2/rest/v2/entries/list

        Args:
            resource_names (Optional[Sequence[str]]): Names of one or more parent resources
                from which to retrieve log entries:

                ::

                    "projects/[PROJECT_ID]"
                    "organizations/[ORGANIZATION_ID]"
                    "billingAccounts/[BILLING_ACCOUNT_ID]"
                    "folders/[FOLDER_ID]"

                If not passed, defaults to the project bound to the client.
            filter_ (Optional[str]): a filter expression. See
                https://cloud.google.com/logging/docs/view/advanced_filters
                By default, a 24 hour filter is applied.
            order_by (Optional[str]): One of :data:`~logging_v2.ASCENDING`
                or :data:`~logging_v2.DESCENDING`.
            max_results (Optional[int]):
                Optional. The maximum number of entries to return.
                Non-positive values are treated as 0. If None, uses API defaults.
            page_size (int): number of entries to fetch in each API call. Although
                requests are paged internally, logs are returned by the generator
                one at a time. If not passed, defaults to a value set by the API.
            page_token (str): opaque marker for the starting "page" of entries. If not
                passed, the API will return the first page of entries.
        Returns:
            Generator[~logging_v2.LogEntry]
        r-   zlogName=z AND rh   )r   r.   r   r$   list_entries)r#   ri   rj   rk   rl   rm   rn   
log_filters           r%   rp   zLogger.list_entries9  s    X ! )$,,89N/0
 	zl3G G)'2{{'')#! ( 
 	
r'   N)__name__
__module____qualname____doc__r&   propertyr$   r   r.   r1   r4   r7   rQ   rS   rV   r[   r_   rc   rg   rp   r:   r'   r%   r   r   :   s    
 04d ),   $ $ ; ; $ $  # ##HJ #' - (, 4  *. &6P ,0 ;":$ :.6 6@ <
r'   r   c                   X    e Zd ZdddZd Zd Zd Zd Zd Zd	 Z	dd
Z
ddddZd Zy)r6   N)r   c                <    || _         g | _        || _        || _        y)a_  Context manager:  collect entries to log via a single API call.

        Helper returned by :meth:`Logger.batch`

        Args:
            logger (logging_v2.logger.Logger):
                the logger to which entries will be logged.
            client (~logging_V2.client.Client):
                The client to use.
            resource (Optional[~logging_v2.resource.Resource]):
                Monitored resource of the batch, defaults
                to None, which requires that every entry should have a
                resource specified. Since the methods used to write
                entries default the entry's resource to the global
                resource type, this parameter is only required
                if explicitly set to None. If no entries' resource are
                set to None, this parameter will be ignored on the server.
        N)loggerrP   r$   r   )r#   rz   r$   r   s       r%   r&   zBatch.__init__y  s     &  r'   c                     | S rr   r:   r*   s    r%   	__enter__zBatch.__enter__  s    r'   c                 *    || j                          y y rr   )commit)r#   exc_typeexc_valexc_tbs       r%   __exit__zBatch.__exit__  s    KKM r'   c                 L    | j                   j                  t        di |       y)zAdd a entry without payload to be logged during :meth:`commit`.

        Args:
            kw (Optional[dict]): Additional keyword arguments for the entry.
                See :class:`~logging_v2.entries.LogEntry`.
        Nr:   )rP   appendr   )r#   rL   s     r%   rS   zBatch.log_empty  s     	HNrN+r'   c                 P    | j                   j                  t        dd|i|       y)zAdd a text entry to be logged during :meth:`commit`.

        Args:
            text (str): the text entry
            kw (Optional[dict]): Additional keyword arguments for the entry.
                See :class:`~logging_v2.entries.LogEntry`.
        r   Nr:   )rP   r   r
   )r#   rU   rL   s      r%   rV   zBatch.log_text  s#     	I9d9b9:r'   c                 P    | j                   j                  t        dd|i|       y)a  Add a struct entry to be logged during :meth:`commit`.

        The message must be able to be serializable to a Protobuf Struct.
        It must be a dictionary of strings to one of the following:

            - :class:`str`
            - :class:`int`
            - :class:`float`
            - :class:`bool`
            - :class:`list[str|float|int|bool|list|dict|None]`
            - :class:`dict[str, str|float|int|bool|list|dict|None]`

        For more details on Protobuf structs, see https://protobuf.dev/reference/protobuf/google.protobuf/#value.
        If the provided dictionary cannot be serialized into a Protobuf struct,
        it will not be logged, and a :class:`ValueError` will be raised during :meth:`commit`.

        Args:
            info (dict[str, str|float|int|bool|list|dict|None]): The struct entry,
            kw (Optional[dict]): Additional keyword arguments for the entry.
                See :class:`~logging_v2.entries.LogEntry`.
        r   Nr:   )rP   r   r	   )r#   rY   rL   s      r%   r[   zBatch.log_struct  s#    , 	K;;;<r'   c                 P    | j                   j                  t        dd|i|       y)a  Add a protobuf entry to be logged during :meth:`commit`.

        Args:
            message (google.protobuf.Message): The protobuf entry.
            kw (Optional[dict]): Additional keyword arguments for the entry.
                See :class:`~logging_v2.entries.LogEntry`.
        r   Nr:   )rP   r   r   )r#   r^   rL   s      r%   r_   zBatch.log_proto  s#     	M@'@R@Ar'   c                 B   t         }t        |t        j                  j                  j
                        rt        }nAt        |t        j                  j                        rt        }nt        |t              rt        }| j                  j                   |dd|i|       y)ar  Add an arbitrary message to be logged during :meth:`commit`.
        Type will be inferred based on the input message.

        Args:
            message (Optional[str or dict or google.protobuf.Message]): The message. to log
            kw (Optional[dict]): Additional keyword arguments for the entry.
                See :class:`~logging_v2.entries.LogEntry`.
        r   Nr:   )r   r=   rE   ra   r^   rb   r   r@   rA   rB   r	   r>   r
   rP   r   )r#   r^   rL   
entry_types       r%   rc   z	Batch.log  so     
gv66>>?&J!8!89$J%"JJ=w="=>r'   T)r$   r9   c                   || j                   }d| j                  j                  i}| j                  | j                  j	                         |d<   | j                  j
                  | j                  j
                  |d<   | j                  D cg c]  }|j                          }}	  |j                  j                  |fd|i| | j                  dd= yc c}w # t        $ r}| j                  |       |d}~ww xY w)ao  Send saved log entries as a single API call.

        Args:
            client (Optional[~logging_v2.client.Client]):
                The client to use.  If not passed, falls back to the
                ``client`` stored on the current batch.
            partial_success (Optional[bool]):
                Whether a batch's valid entries should be written even
                if some other entry failed due to a permanent error such
                as INVALID_ARGUMENT or PERMISSION_DENIED.

        Raises:
            ValueError:
                if one of the messages in the batch cannot be successfully parsed.
        Nrf   r   r   r9   )r$   rz   r.   r   _to_dictr   rP   rD   rI   rJ   r   _append_context_to_error)r#   r$   r9   kwargsrN   rP   rM   s          r%   r~   zBatch.commit  s      >[[F!6!67==$!%!7!7!9F:;;)#{{11F848LLA55$$&AA	,F,,)8<B LLO B
  	 ))!,G		s   C'C 	C<$C77C<c                 L   	 t        d |j                  D              }t        j                  d|j                        j                  d      }| j                  t        |         }t        |j                               }|j                   d|dd|_
        y# t        $ r Y yw xY w)a  
        Attempts to Modify `write_entries` exception messages to contain
        context on which log in the batch caused the error.

        Best-effort basis. If another exception occurs while processing the
        input exception, the input will be left unmodified

        Args:
            err (~google.api_core.exceptions.InvalidArgument):
                The original exception object
        c              3   B   K   | ]  }t        |t              s|  y wrr   )r=   r   ).0xs     r%   	<genexpr>z1Batch._append_context_to_error.<locals>.<genexpr>  s     QA
1i8PaQs   z(?<=key: )[0-9]+r   z: z.2000z...N)nextdetailsresearchdetailgrouprP   intr>   rD   r^   	Exception)r#   err
debug_info	error_idxfound_entry	str_entrys         r%   r   zBatch._append_context_to_error  s    	QQQJ		"4j6G6GHNNqQI,,s9~6KK3356I [[MIe+<C@CK 		s   BB 	B#"B#rr   )rs   rt   ru   r&   r|   r   rS   rV   r[   r_   rc   r~   r   r:   r'   r%   r6   r6   x  s@    37 !0,;=0B?$  $T %Nr'   r6   )rv   r@   r   google.protobuf.messagerE   google.api_core.exceptionsr   google.rpc.error_details_pb2r   google.cloud.logging_v2 google.cloud.logging_v2._helpersr   (google.cloud.logging_v2._instrumentationr   google.cloud.logging_v2.entriesr   r   r	   r
   5google.cloud.logging_v2.handlers._monitored_resourcesr    google.cloud.logging_v2.resourcer   _GLOBAL_RESOURCE_OUTBOUND_ENTRY_FIELDSrX   objectr   r6   r:   r'   r%   <module>r      s      	  6 2  D I  R 5"5  !"   > {
V {
|	fF fr'   