
    	]j1                         d Z ddlZddlZddlZddlmZmZmZ ddlm	Z	 ddl
mZmZ ddlmZmZ ddlmZ dZ	 d	Z	 d
Z	 dZ G d dej,                        Z G d dej0                        Zd Zeej6                  ddZy)z1Python :mod:`logging` handlers for Cloud Logging.    N)IOOptionalType)get_request_data)add_resource_labelsdetect_resource)BackgroundThreadTransport	Transport)Resourcepython)zgoogle.api_core.bidiwerkzeug)zgoogle.cloudzgoogle.authgoogle_auth_httplib2)gae_appcloud_functionc                   .    e Zd ZdZddZed        Zd Zy)CloudLoggingFiltera5  Python standard ``logging`` Filter class to add Cloud Logging
    information to each LogRecord.

    When attached to a LogHandler, each incoming log will be modified
    to include new Cloud Logging relevant data. This data can be manually
    overwritten using the `extras` argument when writing logs.
    Nc                 4    || _         |r|| _        y i | _        y )Nprojectdefault_labels)selfr   r   s      S/root/env/lib/python3.12/site-packages/google/cloud/logging_v2/handlers/handlers.py__init__zCloudLoggingFilter.__init__=   s    0>nB    c                     t        | d      r| j                  S g d}i }|D ]  \  }}t        | |d      }||||<    |r|S dS )zHelper function to infer source location data from a LogRecord.
        Will default to record.source_location if already set
        source_location))linelineno)filepathname)functionfuncNameN)hasattrr   getattr)recordname_mapoutputgcp_namestd_lib_namevalues         r   _infer_source_locationz)CloudLoggingFilter._infer_source_locationA   sj    
 6,-)))H
 F*2 -&,d;$',F8$- $6--r   c                 n   t        |di       }t               \  }}}}|| j                  d| j                   d| }t        |dd      |_        t        |d|      xs d|_        t        |d|      xs d|_        t        t        |d|            |_        t        |d	|      |_        t        j                  |      |_        |j                  rd
|j                  ini }i || j                  |xs d|_        |j                  xs d|_        |j
                  xs d|_        |j                  rdnd|_        t%        j&                  |j                  xs i d      |_        t%        j&                  |j                  xs i d      |_        t%        j&                  |j                  xs i d      |_        y)zM
        Add new Cloud Logging data to each LogRecord as it comes in
        labelsNz	projects/z/traces/resourcetracespan_idtrace_sampledhttp_requestpython_logger truefalseF)ensure_asciiT)r$   r   r   	_resource_trace_span_idbool_trace_sampled_http_requestr   r+   _source_locationnamer   _labels
_trace_str_span_id_str_trace_sampled_strjsondumps_http_request_str_source_location_str_labels_str)r   r%   user_labelsinferred_httpinferred_traceinferred_spaninferred_sampledlogger_labels           r   filterzCloudLoggingFilter.filterU   s    fh3 	
%$,,*B(h~>NON"6:t<@HD!&)]CKt $WV_FV%W X&v~}M"4"K"KF"S9?5"OLOD,?,?O;OWSW"MM/R$oo3.4.C.CF!#'::  &BU$
  '+jj##)r'
# "ZZ(<"5Qr   )NN)__name__
__module____qualname____doc__r   staticmethodr+   rO    r   r   r   r   4   s&    G . .&$r   r   c                   n     e Zd ZdZeedddddedee   de	de
e   de
e   f
 fd	Zd
 Z fdZd Z xZS )CloudLoggingHandlera6  Handler that directly makes Cloud Logging API calls.

    This is a Python standard ``logging`` handler using that can be used to
    route Python standard logging messages directly to the Stackdriver
    Logging API.

    This handler is used when not in GAE or GKE environment.

    This handler supports both an asynchronous and synchronous transport.

    Example:

    .. code-block:: python

        import logging
        import google.cloud.logging
        from google.cloud.logging_v2.handlers import CloudLoggingHandler

        client = google.cloud.logging.Client()
        handler = CloudLoggingHandler(client)

        cloud_logger = logging.getLogger('cloudLogger')
        cloud_logger.setLevel(logging.INFO)
        cloud_logger.addHandler(handler)

        cloud_logger.error('bad news')  # API call
    N)r?   	transportr.   r-   streamr?   rX   r.   r-   rY   c                v   t         t        |   |       |st        |j                        }|| _        || _        |j                  j                  |         ||||      | _	        d| _
        || _        |j                  | _        || _        || _        t        | j                  |      }| j!                  |       y)a  
        Args:
            client (~logging_v2.client.Client):
                The authenticated Google Cloud Logging client for this
                handler to use.
            name (str): the name of the custom log in Cloud Logging.
                Defaults to 'python'. The name of the Python logger will be represented
                in the ``python_logger`` field.
            transport (~logging_v2.transports.Transport):
                Class for creating new transport objects. It should
                extend from the base :class:`.Transport` type and
                implement :meth`.Transport.send`. Defaults to
                :class:`.BackgroundThreadTransport`. The other
                option is :class:`.SyncTransport`.
            resource (~logging_v2.resource.Resource):
                Resource for this Handler. If not given, will be inferred from the environment.
            labels (Optional[dict]): Additional labels to attach to logs.
            stream (Optional[IO]): Stream to be used by the handler.
        r.   Tr   N)superrW   r   r   r   r?   client	_handlersaddrX   _transport_open_transport_cls
project_idr.   r-   r   	addFilter)
r   r]   r?   rX   r.   r-   rY   kwargs
log_filter	__class__s
            r   r   zCloudLoggingHandler.__init__   s    < 	!41&9&v~~6H	T""64(C#' .. 'PVW
z"r   c                    |j                   xs | j                  }|j                  }t        ||       }i t	        ||      |xs i xs d}| j
                  s>| j                  | j                  | j                  | j                        | _	        d| _        | j                  j                  |||||j                  |j                  |j                  |j                  |j                  	       y)a  Actually log the specified logging record.

        Overrides the default emit behavior of ``StreamHandler``.

        See https://docs.python.org/2/library/logging.html#handler-objects

        Args:
            record (logging.LogRecord): The record to be logged.
        Nr[   T)r.   r-   r/   r0   r1   r2   r   )r8   r.   r@   _format_and_parse_messager   r`   ra   r]   r?   rX   sendr9   r:   r<   r=   r>   )r   r%   r.   r-   messages        r   emitzCloudLoggingHandler.emit   s     ##4t}}+FD9L'&9LflLTPT ##!00TYY 1 DN $(D --OO //--"33 	 
	
r   c                 x    t         t        |           | j                  r| j                  j                          yy)ztForces the Transport object to submit any pending log records.

        For SyncTransport, this is a no-op.
        N)r\   rW   flushr`   rX   )r   rf   s    r   rm   zCloudLoggingHandler.flush   s1    
 	!4.0NN  "  r   c                 n    | j                   r)| j                  j                          d| _        d| _         yy)z@Closes the log handler and cleans up all Transport objects used.NF)r`   rX   close)r   s    r   ro   zCloudLoggingHandler.close   s/    NN  "!DN#(D   r   )rP   rQ   rR   rS   DEFAULT_LOGGER_NAMEr	   strr   r
   r   r   dictr   r   rk   rm   ro   __classcell__)rf   s   @r   rW   rW   |   sn    @ (%>!!%#-# 	-#
 	?-# -# -# -#^!
F#)r   rW   c                 ~   t        | di       }t        | j                  t        j                  j
                        r:| j                  }|r*t        |t        j                  j
                        ri ||}|S |j                  |       }	 |d   dk(  r;t        j                  |      }t        |t        j                  j
                        r|}|r@t        |t        j                  j
                        r|j                         }|dk7  r||d<   |S |dk7  r|S dS # t        j                  j                  t        f$ r Y pw xY w)ae  
    Helper function to apply formatting to a LogRecord message,
    and attempt to parse encoded JSON into a dictionary object.

    Resulting output will be of type (str | dict | None)

    Args:
        record (logging.LogRecord): The record object representing the log
        formatter_handler (logging.Handler): The handler used to format the log
    json_fieldsr   {Nonerj   N)r$   
isinstancemsgcollectionsabcMappingformatrD   loadsdecoderJSONDecodeError
IndexErrorcopy)r%   formatter_handlerpassed_json_fieldspayloadrj   json_messages         r   rh   rh      s"    !;&**koo556*** 7 7#
 87$67G&&v.G1:::g.L,(?(?@&
 j);[__=T=TU/446f,3y)!!'71T1 LL((*5 s   AD #D<;D<)excluded_loggers	log_levelc                B   t        |t        z         }t        j                         }t	               j
                  t        v r|j                  j                          |j                  |       |j                  |        |D ]  }t        j                  |      }d|_          y)a  Attach a logging handler to the Python root logger

    Excludes loggers that this library itself uses to avoid
    infinite recursion.

    Example:

    .. code-block:: python

        import logging
        import google.cloud.logging
        from google.cloud.logging_v2.handlers import CloudLoggingHandler

        client = google.cloud.logging.Client()
        handler = CloudLoggingHandler(client)
        google.cloud.logging.handlers.setup_logging(handler)
        logging.getLogger().setLevel(logging.DEBUG)

        logging.error('bad news')  # API call

    Args:
        handler (logging.handler): the handler to attach to the global handler
        excluded_loggers (Optional[Tuple[str]]): The loggers to not attach the handler
            to. This will always include the loggers in the
            path of the logging client itself.
        log_level (Optional[int]): The logging level threshold of the attached logger,
            as set by the :meth:`logging.Logger.setLevel` method. Defaults to
            :const:`logging.INFO`.
    FN)set_INTERNAL_LOGGERSlogging	getLoggerr   type_CLEAR_HANDLER_RESOURCE_TYPEShandlersclearsetLevel
addHandler	propagate)handlerr   r   all_excluded_loggersloggerlogger_names         r   setup_loggingr   &  s    @ /2CCD F !>>
OOI
g+ !"";/ !r   )rS   rz   rD   r   typingr   r   r   )google.cloud.logging_v2.handlers._helpersr   5google.cloud.logging_v2.handlers._monitored_resourcesr   r   +google.cloud.logging_v2.handlers.transportsr	   r
    google.cloud.logging_v2.resourcer   rp   EXCLUDED_LOGGER_DEFAULTSr   r   Filterr   StreamHandlerrW   rh   INFOr   rU   r   r   <module>r      s    8    % % F 6  . 
 >  F = E EP})'// })@'2V ":W\\,!r   