
    A&                         S r SSKJr  SSKJr  SSKJr  SSKJr  SSKJr  SSKJ	r	  SSK
Jr  SS	Kr/ S
QrSrSrSSS\\/rSS/rSS jrS rS rS rS rS r " S S\5      rg	)z9General formatting utils, App Engine specific formatters.    )absolute_import)division)unicode_literals)util)log)	resources)timesN)criticalerrorwarninginfodebuganyznginx.requestrequest_logstderrstdoutz	crash.logz&appengine.googleapis.com/nginx.requestz+appengine.googleapis.com/nginx.health_checkc                 6   S/nU(       a   UR                  SR                  U5      5        U(       a   UR                  SR                  U5      5        US:w  a.  UR                  SR                  UR                  5       5      5        / n[        U5       H<  nUR                  SR                  U5      5        US;   d  M+  UR                  U5        M>     [        R
                  R                  U SS	9R                  5       nUR                  [        Xh5      5        U$ )
aY  Returns filters for App Engine app logs.

Args:
  project: string name of project ID.
  log_sources: List of streams to fetch logs from.
  service: String name of service to fetch logs from.
  version: String name of version to fetch logs from.
  level: A string representing the severity of logs to fetch.

Returns:
  A list of filter strings.
zresource.type="gae_app"zresource.labels.module_id="{0}"z resource.labels.version_id="{0}"r   zseverity>={0}zappengine.googleapis.com/{0})r   r   zappengine.projects)
collection)	appendformatuppersortedr   REGISTRYParseRelativeName_LogFilterForIds)	projectlog_sourcesserviceversionlevelfilterslog_idslog_typeress	            +lib/googlecloudsdk/api_lib/app/logs_util.py
GetFiltersr'   (   s     '''NN4;;GDENN5<<WEF
e^NN?))%++-89'%hNN188BC''nnX & 	  . 	! 	00<  
..!'/0	.    c           	          U (       d  gU  Vs/ s H(  nSR                  [        R                  " X5      5      PM*     nnSR                  U5      n[	        U 5      S:  a  SU-  nSU-  $ s  snf )zDConstructs a log filter expression from the log_ids and parent name.Nz"{0}"z OR    z(%s)z
logName=%s)r   r   CreateLogResourceNamejoinlen)r#   parentlog_id	log_namess       r&   r   r   I   sp    	$&$6 ~~d88HI$  &kk)$)\A"I			!!&s   /A(c                 T   U R                   R                  S:w  a  gU R                  (       a!  [        R                  " U R                  5      nO>U R
                  (       a!  [        R                  " U R
                  5      nOU R                  n[        U 5      u  p#SR                  UUUS9$ )zApp Engine formatter for `LogPrinter`.

Args:
  entry: A log entry message emitted from the V2 API client.

Returns:
  A string representing the entry or None if there was no text payload.
gae_appNz{service}[{version}]  {text})r   r    text)	resourcetypeprotoPayloadsix	text_typejsonPayloadtextPayload_ExtractServiceAndVersionr   )entryr3   r   r    s       r&   FormatAppEntryr=   U   s     ^^I%
==++,D==**+DD.u5'	'	.	.w7>48 
/ 
: :r(   c                 0  ^  T R                   R                  S:w  a  g[        R                  " T R                  5      nUS:w  a  g[        T 5      u  p#U 4S jnU 4S jnSR                  U" S5      U" S5      U" S	5      U" S
5      S9nSR                  UUUS9$ )zApp Engine request_log formatter for `LogPrinter`.

Args:
  entry: A log entry message emitted from the V2 API client.

Returns:
  A string representing the entry if it is a request entry.
r2   Nz$appengine.googleapis.com/request_logc                 Z   >^  [        U 4S jTR                  R                   5       S5      $ )Nc              3   t   >#    U  H-  nUR                   T:X  d  M  UR                  R                  v   M/     g 7fN)keyvaluestring_value.0xrB   s     r&   	<genexpr>8FormatRequestLogEntry.<locals>.GetStr.<locals>.<genexpr>}   s2      "8 +,EESL &%%8   88-nextr6   additionalPropertiesrB   r<   s   `r&   GetStr%FormatRequestLogEntry.<locals>.GetStr|   ,     "##88"#&( (r(   c                 Z   >^  [        U 4S jTR                  R                   5       S5      $ )Nc              3   t   >#    U  H-  nUR                   T:X  d  M  UR                  R                  v   M/     g 7frA   )rB   rC   integer_valuerE   s     r&   rH   8FormatRequestLogEntry.<locals>.GetInt.<locals>.<genexpr>   s2      "8 ,-EESL '&&8rJ   rK   rL   rO   s   `r&   GetInt%FormatRequestLogEntry.<locals>.GetInt   rR   r(   z-"{method} {resource} {http_version}" {status}methodr4   httpVersionstatus)rY   r4   http_versionr[   {service}[{version}]  {msg}r   r    msg)r4   r5   r   ExtractLogIdlogNamer;   r   )r<   r/   r   r    rP   rW   r_   s   `      r&   FormatRequestLogEntryrb   m   s     ^^I%U]]+&55.u5'(( 
9
&8$Z( /8$	  &  
'	-	-g6=25 
. 
7 7r(   c                    U R                   R                  S:w  a  g[        R                  " U R                  5      nU[
        ;  a  g[        U 5      u  p#SR                  U R                  R                  =(       d    SU R                  R                  =(       d    SU R                  R                  =(       d    SS9nSR                  UUUS9$ )zApp Engine nginx.* formatter for `LogPrinter`.

Args:
  entry: A log entry message emitted from the V2 API client.

Returns:
  A string representing the entry if it is a request entry.
r2   Nz"{method} {resource}" {status}rK   )rY   r4   r[   r]   r^   )r4   r5   r   r`   ra   
NGINX_LOGSr;   r   httpRequestrequestMethod
requestUrlr[   )r<   r/   r   r    r_   s        r&   FormatNginxLogEntryrh      s     ^^I%U]]+&:.u5'	)
&%%33:s''229c%%,,3  5 
 
'	-	-g6=25 
. 
7 7r(   c                     U R                   R                  R                  n[        S U 5       5      n[        S U 5       5      nX#4$ )zExtract service and version from a App Engine log entry.

Args:
  entry: An App Engine log entry.

Returns:
  A 2-tuple of the form (service_id, version_id)
c              3   ^   #    U  H#  nUR                   S :X  d  M  UR                  v   M%     g7f)	module_idNrB   rC   rF   rG   s     r&   rH   ,_ExtractServiceAndVersion.<locals>.<genexpr>   s)      *!QEE[( !   --c              3   ^   #    U  H#  nUR                   S :X  d  M  UR                  v   M%     g7f)
version_idNrl   rm   s     r&   rH   rn      s)      +!QEE\) !ro   )r4   labelsrN   rM   )r<   ad_propr   r    s       r&   r;   r;      sT     NN!!66' *!* *'  +!+ +' 	r(   c                   :    \ rS rSrSrS
S jrS rS rS rS r	S	r
g)
LogPrinter   a  Formats V2 API log entries to human readable text on a best effort basis.

A LogPrinter consists of a collection of formatter functions which attempts
to format specific log entries in a human readable form. The `Format` method
safely returns a human readable string representation of a log entry, even if
the provided formatters fails.

The output format is `{timestamp} {log_text}`, where `timestamp` has a
configurable but consistent format within a LogPrinter whereas `log_text` is
emitted from one of its formatters (and truncated if necessary).

See https://cloud.google.com/logging/docs/api/introduction_v2

Attributes:
  api_time_format: str, the output format to print. See datetime.strftime()
  max_length: The maximum length of a formatted log entry after truncation.
Nc                 *    / U l         Xl        X l        g rA   )
formattersapi_time_format
max_length)selfry   rz   s      r&   __init__LogPrinter.__init__   s    DO* Or(   c                    U R                  U5      nUR                  5       R                  SS5      n [        R                  " [        R
                  " UR                  5      U R                  5      nSR                  UUS9nU R                  (       a.  [        U5      U R                  :  a  USU R                  S-
   S	-   nU$ ! [        R                   a4    [        R                  " SR                  UR                  5      5        Sn Nf = f)
zSafely formats a log entry into human readable text.

Args:
  entry: A log entry message emitted from the V2 API client.

Returns:
  A string without line breaks respecting the `max_length` property.

z  z8Received timestamp [{0}] does not match expected format.z????-??-?? ??:??:??z{timestamp} {log_text})	timestamplog_textN   z...)_LogEntryToTextstripreplacer	   FormatDateTimeParseDateTimer   ry   Errorr   r   r   rz   r-   )r{   r<   r3   timeouts        r&   FormatLogPrinter.Format   s     &D::<d+D#!!%"5"5eoo"F"&"6"68d #
)
) * C 3s8doo5$1$%-cJ ;; #	kk #VEOO46"d#s   ?C AD
Dc                 :    U R                   R                  U5        g)a  Attach a log entry formatter function to the printer.

Note that if multiple formatters are attached to the same printer, the first
added formatter that successfully formats the entry will be used.

Args:
  formatter: A formatter function which accepts a single argument, a log
      entry. The formatter must either return the formatted log entry as a
      string, or None if it is unable to format the log entry.
      The formatter is allowed to raise exceptions, which will be caught and
      ignored by the printer.
N)rx   r   )r{   	formatters     r&   RegisterFormatterLogPrinter.RegisterFormatter   s     	OO9%r(   c                 P   SnU R                   U R                  /-    H  n U" U5      nU(       a    OM     U(       dR  [        R                  " SUR
                  UR                  UR                  5        SR                  UR                  5      nU$ ! [         a  nUeSnAf   M  = f)z>Use the formatters to convert a log entry to unprocessed text.Nz$Could not format log entry: %s %s %szD< UNREADABLE LOG ENTRY {0}. OPEN THE DEVELOPER CONSOLE TO INSPECT. >)	rx   _FallbackFormatterKeyboardInterruptr   r   r   ra   insertIdr   )r{   r<   r   fnes        r&   r   LogPrinter._LogEntryToText   s    
Coo!8!8 99i
 	 : 	ii6u~~/ &0 
J  s   B
B%BB%c                     UR                   (       a   [        R                  " UR                   5      $ UR                  (       a   [        R                  " UR                  5      $ UR                  $ rA   )r6   r7   r8   r9   r:   )r{   r<   s     r&   r   LogPrinter._FallbackFormatter  sL     ]]5--..			]]5,,--r(   )ry   rx   rz   )z%Y-%m-%d %H:%M:%SN)__name__
__module____qualname____firstlineno____doc__r|   r   r   r   r   __static_attributes__ r(   r&   ru   ru      s     $!
6&(r(   ru   )NNr   )r   
__future__r   r   r   googlecloudsdk.api_lib.loggingr   googlecloudsdk.corer   r   googlecloudsdk.core.utilr	   r7   
LOG_LEVELSFLEX_REQUESTSTANDARD_REQUESTDEFAULT_LOGSrd   r'   r   r=   rb   rh   r;   objectru   r   r(   r&   <module>r      s    @ &  ' / # ) * 
 F
   (K.0 -13

B	":07D72(^ ^r(   