
    	]j&                         d 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
mZ dZ eh d      Z G d dej                        Zy)	zJLogging handler for printing formatted structured logs to standard output.    N)_create_diagnostic_entry)CloudLoggingFilter_format_and_parse_messageap  {%(_payload_str)s"severity": "%(levelname)s", "logging.googleapis.com/labels": %(_labels_str)s, "logging.googleapis.com/trace": "%(_trace_str)s", "logging.googleapis.com/spanId": "%(_span_id_str)s", "logging.googleapis.com/trace_sampled": %(_trace_sampled_str)s, "logging.googleapis.com/sourceLocation": %(_source_location_str)s, "httpRequest": %(_http_request_str)s }>   logging.googleapis.com/tracelogging.googleapis.com/labelslogging.googleapis.com/spanIdlogging.googleapis.com/insertId logging.googleapis.com/operation$logging.googleapis.com/trace_sampled%logging.googleapis.com/sourceLocationtimeseverity	timestamphttpRequesttimestampNanostimestampSecondsc                   H     e Zd ZdZddddd fd
Z fdZ fdZd Z xZS )StructuredLogHandlerzoHandler to format logs into the Cloud Logging structured log format,
    and write them to standard output
    N)labelsstream
project_idjson_encoder_clsc                    t         t        |   |       || _        t	        ||      }| j                  |        G d dt        j                        } |t              | _	        |xs t        j                  | _        y)a^  
        Args:
            labels (Optional[dict]): Additional labels to attach to logs.
            stream (Optional[IO]): Stream to be used by the handler.
            project (Optional[str]): Project Id associated with the logs.
            json_encoder_cls (Optional[Type[JSONEncoder]]): Custom JSON encoder. Defaults to json.JSONEncoder
        )r   )projectdefault_labelsc                       e Zd ZdZd Zy)1StructuredLogHandler.__init__.<locals>._Formatterz1Formatter to format log message without tracebackc                 N    |j                         |_        | j                  |      S )zIgnore exception info to avoid duplicating it
                https://github.com/googleapis/python-logging/issues/382
                )
getMessagemessageformatMessage)selfrecords     Y/root/env/lib/python3.12/site-packages/google/cloud/logging_v2/handlers/structured_log.pyformatz8StructuredLogHandler.__init__.<locals>._Formatter.format]   s%     "(!2!2!4))&11    N)__name__
__module____qualname____doc__r%    r&   r$   
_Formatterr   Z   s
    C2r&   r,   N)superr   __init__r   r   	addFilterlogging	Formatter
GCP_FORMAT_gcp_formatterjsonJSONEncoder_json_encoder_cls)	r"   r   r   r   r   kwargs
log_filterr,   	__class__s	           r$   r.   zStructuredLogHandler.__init__C   sm      	"D2&2A$ (
6R
z"	2** 	2 )4!1!ET5E5Er&   c                    d}t        |t        t        |             }t        |t        j
                  j                        rct        |j                               D ]  }|t        v s||=  t        j                  |d| j                        }t        |      dkD  r>|dd dz   }n5|r3t        j                  |d| j                        }dj                  |      }|xs d	|_        | j                   j                  |      }|S )
zFormat the message into structured log JSON.
        Args:
            record (logging.LogRecord): The log record.
        Returns:
            str: A JSON string formatted for GCP structured logging.
        NF)ensure_asciicls      ,z"message": {}, )r   r-   r   
isinstancecollectionsabcMappinglistkeysGCP_STRUCTURED_LOGGING_FIELDSr4   dumpsr6   lenr%   _payload_strr3   )	r"   r#   payloadr    keyencoded_msgencoded_messagegcp_payloadr9   s	           r$   r%   zStructuredLogHandler.formati   s     +FE:NPT4UVg{667GLLN+ %77% **e1G1GK
 ;!#%a+c1"jje1G1GO '--o>G%m))008r&   c                     t         j                  j                  j                  du r| j	                          t
        |   |       y )NF)googlecloud
logging_v2_instrumentation_emittedemit_instrumentation_infor-   emit)r"   r#   r9   s     r$   rW   zStructuredLogHandler.emit   s3    <<"";;uD**,Vr&   c                 R   dt         j                  j                  _        t	               }t        j                  t              }|j                  |        |j                  t
        j                         |j                  |j                         |j                  j                          y )NT)rR   rS   rT   rU   r   r0   	getLoggerr'   
addHandlersetLevelINFOinforL   handlersclear)r"   diagnostic_objectstruct_loggers      r$   rV   z.StructuredLogHandler.emit_instrumentation_info   st    ;?846))(3  &w||,,445$$&r&   )	r'   r(   r)   r*   r.   r%   rW   rV   __classcell__)r9   s   @r$   r   r   >   s-     $FL!F
'r&   r   )r*   rC   r4   r0   logging.handlersgoogle.cloud.logging_v2rR   (google.cloud.logging_v2._instrumentationr   )google.cloud.logging_v2.handlers.handlersr   r   r2   	frozensetrH   StreamHandlerr   r+   r&   r$   <module>ri      sR    Q      M  !*! &Z'700 Z'r&   