
    &`iaJ                        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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 d dlmZ d dlmZmZmZmZmZmZmZmZmZmZmZmZm Z m!Z!m"Z"m#Z# d dl$m%Z% d d	l&m'Z'm(Z( e j)        Z*d
ej+        de,fdZ- G d de
          Z. G d dej/                  Z0 G d dej/                  Z1 G d dej/                  Z2 G d de          Z3de4de4de4de5fdZ6d
ej+        de,fdZ7d
ej+        de,fdZ8dee4         fdZ9 G d d e:          Z;d!d"dd#d$d%Z<dddd#d&d'd(e4d)e4d*e(d+ee         d,ee=         d-ee=         d.e,d/e=fd0Z>d1 Z?	 d6d(e4d)e4d+ee         fd2Z@de4fd3ZA G d4 d5          ZBdS )7    N)AnyOptional)CoreContextFilter)JSONFormatterTextFormatter)LOGGING_ROTATE_BACKUP_COUNTLOGGING_ROTATE_BYTES)ServeComponentType)RAY_SERVE_ENABLE_JSON_LOGGING!RAY_SERVE_ENABLE_MEMORY_PROFILINGRAY_SERVE_LOG_TO_STDERRSERVE_LOG_APPLICATIONSERVE_LOG_COMPONENTSERVE_LOG_COMPONENT_IDSERVE_LOG_DEPLOYMENTSERVE_LOG_LEVEL_NAMESERVE_LOG_MESSAGESERVE_LOG_RECORD_FORMATSERVE_LOG_REPLICASERVE_LOG_REQUEST_IDSERVE_LOG_ROUTESERVE_LOG_TIMESERVE_LOG_UNWANTED_ATTRSSERVE_LOGGER_NAME)get_component_file_name)EncodingTypeLoggingConfigrecordreturnc                 $    t          | dd          S )z7Check if the log record should skip the context filter.skip_context_filterF)getattrr   s    t/home/jaya/work/projects/VOICE-AGENT/VIET/agent-env/lib/python3.11/site-packages/ray/serve/_private/logging_utils.pyshould_skip_context_filterr%   %   s    60%888    c                   2     e Zd Zdej        def fdZ xZS )ServeCoreContextFilterr   r   c                 h    t          |          rdS t                                          |          S NT)r%   superfilter)selfr   	__class__s     r$   r,   zServeCoreContextFilter.filter+   s.    %f-- 	4ww~~f%%%r&   )__name__
__module____qualname__logging	LogRecordboolr,   __classcell__r.   s   @r$   r(   r(   *   sN        &W. &4 & & & & & & & & & &r&   r(   c                   P    e Zd ZdZ	 d
dededee         fdZdej	        de
fd	ZdS )ServeComponentFilterziServe component filter.

    The filter will add the component name, id, and type to the log record.
    Ncomponent_namecomponent_idcomponent_typec                 0    || _         || _        || _        d S N)r9   r:   r;   )r-   r9   r:   r;   s       r$   __init__zServeComponentFilter.__init__7   s"     -(,r&   r   r   c                 p   t          |          rdS | j        rg| j        t          j        k    rRt	          |t
          | j                   t	          |t          | j                   t	          |t          | j                   n6t	          |t          | j                   t	          |t          | j                   dS )zAdd component attributes to the log record.

        Note: the filter doesn't do any filtering, it only adds the component
        attributes.
        T)r%   r;   r
   REPLICAsetattrr   r9   r   r:   r   r   r-   r   s     r$   r,   zServeComponentFilter.filterA   s     &f-- 	4 	G4#6:L:T#T#TF0$2EFFFF-t/@AAAF/1DEEEEF/1DEEEF2D4EFFFtr&   r=   )r/   r0   r1   __doc__strr   r
   r>   r2   r3   r4   r,    r&   r$   r8   r8   1   s          8<	- -- - !!34	- - - -W. 4      r&   r8   c                       e Zd ZdZd ZdS )ServeContextFilterzServe context filter.

    The filter will add the route, request id, app name to the log record.

    Note: the filter doesn't do any filtering, it only adds the serve request context
    attributes.
    c                 :   t          |          rdS t          j        j                                        }|j        rt          |t          |j                   |j        rt          |t          |j                   |j
        rt          |t          |j
                   dS r*   )r%   rayservecontext_get_serve_request_contextrouterA   r   
request_idr   app_namer   )r-   r   request_contexts      r$   r,   zServeContextFilter.filter]   s    %f-- 	4)+FFHH  	DFO_-BCCC% 	NF0/2LMMM# 	MF1?3KLLLtr&   Nr/   r0   r1   rC   r,   rE   r&   r$   rG   rG   T   s-             r&   rG   c                       e Zd ZdZd ZdS )ServeLogAttributeRemovalFilterzServe log attribute removal filter.

    The filter will remove unwanted attributes on the log record so they won't be
    included in the structured logs.

    Note: the filter doesn't do any filtering, it only removes unwanted attributes.
    c                 Z    t           D ]"}t          ||          rt          ||           #dS r*   )r   hasattrdelattr)r-   r   keys      r$   r,   z%ServeLogAttributeRemovalFilter.filtert   s9    + 	% 	%Cvs## %$$$tr&   NrQ   rE   r&   r$   rS   rS   k   s-             r&   rS   c                        e Zd ZdZde de de de d	Z	 	 	 	 dd
e	de	de
e	         de
e	         de	def fdZ fdZd Zdedej        fdZdej        de	fdZ xZS )ServeFormatterzServe Logging Formatter

    The formatter will generate the log format on the fly based on the field of record.
    Optimized to pre-compute format strings and formatters for better performance.
    %(z)s %(z)s {z} {z} N%Tr9   r:   fmtdatefmtstylevalidatec                     t                                          ||||           t          j                            ||          | _        |                                  d S )N)r9   r:   )r+   r>   rY   COMPONENT_LOG_FMTformatcomponent_log_fmt_precompute_formatters)r-   r9   r:   r\   r]   r^   r_   r.   s          r$   r>   zServeFormatter.__init__   sc     	guh777!/!A!H!H) "I "
 "

 	##%%%%%r&   c                 b     t                      j        |i | |                                  d S r=   )r+   !set_additional_log_standard_attrsrd   )r-   argskwargsr.   s      r$   rf   z0ServeFormatter.set_additional_log_standard_attrs   s7    114B6BBB##%%%%%r&   c                     |                      g           | _        |                      t          t                   g          | _        d S r=   )_create_formatterbase_formatterr   r   request_formatterr-   s    r$   rd   z%ServeFormatter._precompute_formatters   sB    "44R88!%!7!7$%9:;"
 "
r&   initial_attrsr   c                    |                                 }|                    d | j        D                        |                    t          t
                              | j        d                    |          z   }t          j	        |          S )Nc                     g | ]}d | d	S )rZ   z)srE   ).0ks     r$   
<listcomp>z4ServeFormatter._create_formatter.<locals>.<listcomp>   s     MMMQj1jjjMMMr&    )
copyextendadditional_log_standard_attrsappendr   r   rc   joinr2   	Formatter)r-   rn   attrsformat_strings       r$   rj   z ServeFormatter._create_formatter   sx    ""$$MM$*LMMMNNN,->?@@@.%@ ///r&   r   c                     t           |j        v r| j                            |          S | j                            |          S )zFormat the log record into the format string.

        Args:
            record: The log record to be formatted.
            Returns:
                The formatted log record in string format.
        )r   __dict__rl   rb   rk   rB   s     r$   rb   zServeFormatter.format   s?      6?22)00888&--f555r&   )NNr[   T)r/   r0   r1   rC   r   r   r   r   ra   rD   r   r4   r>   rf   rd   listr2   rz   rj   r3   rb   r5   r6   s   @r$   rY   rY   |   sX         C1  C  C  C  CM`  C  Cg}  C  C  C "!%& && & c]	&
 #& & & & & & & &"& & & & &
 
 
0t 08I 0 0 0 06W. 63 6 6 6 6 6 6 6 6r&   rY   methodrM   status
latency_msc                      |  d| d| d|ddS )zBReturns a formatted message for an HTTP or ServeHandle access log.rt   z.1fmsrE   )r   rM   r   r   s       r$   access_log_msgr      s,    ::u::v::
:::::r&   c                 B    t          | d          r| j        dS | j        S )zCFilters log records based on a parameter in the `extra` dictionary.log_to_stderrNT)rU   r   r#   s    r$   log_to_stderr_filterr      s*    6?++ v/C/Ktr&   c                 D    t          | d          r| j        dS | j         S )zMFilters ray serve access log based on 'serve_access_log' key in `extra` dict.serve_access_logNT)rU   r   r#   s    r$   log_access_log_filterr      s.    6-.. &2I2Qt&&&r&   c                  N   t          j        t                    } | j        D ]}t	          |t           j        j                  rb|j        j        }t          j	        j
        j                                        }|                    |          r|t          |          d         c S dS )a  Returns the relative file path for the Serve logger, if it exists.

    If a logger was configured through configure_component_logger() for the Serve
    component that's calling this function, this returns the location of the log file
    relative to the ray logs directory.
    N)r2   	getLoggerr   handlers
isinstanceMemoryHandlertargetbaseFilenamerI   _privateworker_global_nodeget_logs_dir_path
startswithlen)loggerhandlerabsolute_pathray_logs_dirs       r$   get_component_logger_file_pathr      s     011F? : :gw/=>> 	:#N7M<.;MMOOL''55 :$S%6%6%8%89999: :r&   c                   z    e Zd ZdZdej        dedefdZde	defdZ
edefd	            Zd
e	fdZd ZdefdZdS )StreamToLoggerz
    Fake file-like stream object that redirects writes to a logger instance.

    This comes from https://stackoverflow.com/a/36296215 directly.
    r   	log_leveloriginal_objectc                 >    || _         || _        || _        d| _        d S )N )_logger
_log_level_original_object_linebuf)r-   r   r   r   s       r$   r>   zStreamToLogger.__init__   s#    # /r&   attrr   c                 ,    t          | j        |          S r=   )r"   r   )r-   r   s     r$   __getattr__zStreamToLogger.__getattr__   s    t,d333r&   c                      t          j                    ddd         } t          |           D ]\  }}d|j        vrd|j        vr|c S dS )zRewind stack to get the stacklevel for the user code.

        Going from the back of the traceback and traverse until it's no longer in
        logging_utils.py or site-packages.
        Nzlogging_utils.pyzsite-packages   )	tracebackextract_stack	enumeratefilename)reverse_tracesindextraces      r$   get_stacklevelzStreamToLogger.get_stacklevel   sa     #02244R48%n55 	 	LE5"%.88#5>99qr&   bufc                    | j         |z   }d| _         |                    d          D ]e}|d         dk    rG| j                            | j        |                                |                                            U| xj         |z  c_         fd S )Nr   Tr   

stacklevel)r   
splitlinesr   logr   rstripr   )r-   r   temp_linebuflines       r$   writezStreamToLogger.write   s    }s* ++D11 	& 	&D Bx4  OKKMM#2244 !     %	& 	&r&   c                     | j         dk    rK| j                            | j        | j                                         |                                            d| _         d S )Nr   r   )r   r   r   r   r   r   rm   s    r$   flushzStreamToLogger.flush  s`    =BL$$&&..00    
 r&   c                     dS r*   rE   rm   s    r$   isattyzStreamToLogger.isatty  s    tr&   N)r/   r0   r1   rC   r2   Loggerintr   r>   rD   r   staticmethodr   r   r   r4   r   rE   r&   r$   r   r      s         w~ # PS    4 4 4 4 4 4 C    \& & & & &$        r&   r   rt   r   Fsependfiler   c                 0   |t           j        t           j        dfvrt          || |||          S t	          j        t                    }|                     t          t          |                    |z   }|
                    t          j        |d           dS )a*  Implement python's print function to redirect logs to Serve's logger.

    If the file is set to anything other than stdout, stderr, or None, call the
    builtin print. Else, construct the message and redirect to Serve's logger.

    See https://docs.python.org/3/library/functions.html#print
    Nr      r   )sysstdoutstderrbuildin_printr2   r   r   ry   maprD   r   INFO)r   r   r   r   objectsserve_loggermessages          r$   redirected_printr     s     CJ
D111W#3TOOOO$%677Lhhs3(())C/GW\7q99999r&   r   )r;   	max_bytesbackup_countstream_handler_onlybuffer_sizer9   r:   logging_configr;   r   r   r   r   c                    t          j        t                    }d|_        |                    |j                   |j                                         t          | |          }	t                      }
|j
        r4|
                    |j
                   |	                    |j
                   t          s|rxt          j                    }|                    |	           |                    t                      |                    t#                                 |                    |           |rdS |j        r|j        }nt)                      }t+          j        |d           |t.          j        j        j        j        }|t.          j        j        j        j        }t;          | ||d          }t           j                            t*          j                             ||          ||          }t           j        !                    ||t           j"                  }tF          r|$                    d	           tF          s|j%        tL          j'        k    r||                    tQ                                 |                    t#                                 |                    tS          | ||                     |                    |
           n|                    |	           |j*        du r|                    tV                     n!|                    t#                                 |                    tY                                 t          s|tZ          j.        k    rot^          t`          _1        te          |t           j3        th          j5                  th          _5        te          |t           j3        th          j6                  th          _6        |                    |           dS )
a)  Configure a logger to be used by a Serve component.

    The logger will log using a standard format to make components identifiable
    using the provided name and unique ID for this instance (e.g., replica ID).

    This logger will *not* propagate its log messages to the parent logger(s).
    FNT)exist_okz.logr9   r:   r;   suffix)maxBytesbackupCount)capacityr   
flushLevelz`'RAY_SERVE_ENABLE_JSON_LOGGING' is deprecated, please use 'LoggingConfig' to enable json format.)7r2   r   r   	propagatesetLevelr   r   clearrY   r   rw   rf   r   StreamHandlersetFormatter	addFilterr   rG   
addHandlerlogs_dirget_serve_logs_dirosmakedirsrI   r   r   r   r   r   r   RotatingFileHandlerpathry   r   ERRORr   warningencodingr   JSONr(   r8   enable_access_logr   rS   r
   r@   r   builtinsprintr   r   r   r   r   )r9   r:   r   r;   r   r   r   r   r   serve_formatterjson_formatterstream_handlerr   log_file_namefile_handlermemory_handlers                   r$   configure_component_loggerr   -  s   $ 011FF
OON,---
O$^\BBO"__N3 
888	
 	
 	
 	998	
 	
 	
  *"5 * .00##O444  !5666  !3!5!5666.)))   (!*%''K4((((L'4>	|*7D+%!%	  M #77
X}--  8  L %33= 4  N
 % 
5	
 	
 	

 % 3(?<CT(T(T  !7!9!9:::  !3!5!5666   ~NN	
 	
 	
 	!!.1111!!/222'500  !67777  !3!5!5666 ;==>>> # F~9K9S'S'S)#FGL#*EE
#FGL#*EE
 n%%%%%r&   c                      t          dt          t          j                              t	                      t
          t          d           dS )zmHelper function to configure the default Serve logger that's used outside of
    individual Serve components.rJ   T)r9   r:   r   r   r   r   N)r   rD   r   getpidr   r	   r   rE   r&   r$   configure_default_serve_loggerr    sI     %%$&0      r&   c                    t           rEt          j        t                    }	 ddl}t                      }t          | ||d          }t          j        	                    ||          }d}t          j        
                    |          r[t          | ||d| d          }t          j        	                    ||          }|dz  }t          j        
                    |          [|                    |d	                                           |                    d
| d           dS # t          $ r |                    d           Y dS w xY wdS )zyConfigures the memory logger for this component.

    Does nothing if RAY_SERVE_ENABLE_MEMORY_PROFILING is disabled.
    r   Nz_memray_0.binr   r   _memray_z.binT)native_traceszoRAY_SERVE_ENABLE_MEMORY_PROFILING is enabled. Started a memray tracker on this actor. Tracker file located at ""zRAY_SERVE_ENABLE_MEMORY_PROFILING is enabled, but memray is not installed. No memory profiling is happening. `pip install memray` to enable memory profiling.)r   r2   r   r   memrayr   r   r   r   ry   existsTracker	__enter__infoImportErrorr   )	r9   r:   r;   r   r  r   memray_file_namememray_file_pathrestart_counters	            r$   #configure_component_memory_profilerr    s    ) -"#455*	MMM)++H6-)-&	       "w||H6FGG  O'..!122 %#:#1!-#1;o;;;	$ $ $  $&7<<:J#K#K 1$ '..!122 % NN+4N@@JJLLLKK($( ( (      	 	 	NNC     	Q- -s   DD( (E
Ec                     t           j        j        j        1t          j                            t	          j                    d          S t          j                            t           j        j        j                                        d          S )aK  Get the directory that stores Serve log files.

    If `ray._private.worker._global_node` is None (running outside the context of Ray),
    then the current working directory with subdirectory of serve is used as the logs
    directory. Otherwise, the logs directory is determined by the global node's logs
    directory path.
    NrJ   )	rI   r   r   r   r   r   ry   getcwdr   rE   r&   r$   r   r     sX     |'/w||BIKK1117<<+8JJLLgVVVr&   c                   &    e Zd ZdZddZd Zd ZdS )LoggingContexta  
    Context manager to manage logging behaviors within a particular block, such as:
    1) Overriding logging level

    Source (python3 official documentation)
    https://docs.python.org/3/howto/logging-cookbook.html#using-a-context-manager-for-selective-logging # noqa: E501
    Nc                 "    || _         || _        d S r=   )r   level)r-   r   r  s      r$   r>   zLoggingContext.__init__  s    


r&   c                 x    | j         2| j        j         | _        | j                            | j                    d S d S r=   )r  r   	old_levelr   rm   s    r$   r
  zLoggingContext.__enter__  s<    :!![.DNK  ,,,,, "!r&   c                 V    | j         !| j                            | j                   d S d S r=   )r  r   r   r  )r-   etevtbs       r$   __exit__zLoggingContext.__exit__  s0    :!K  00000 "!r&   r=   )r/   r0   r1   rC   r>   r
  r  rE   r&   r$   r  r    sP            - - -
1 1 1 1 1r&   r  r=   )Cr   r2   r   r   r   typingr   r   rI   ray._common.filtersr   ray._common.formattersr   r   ray._common.ray_constantsr   r	   ray.serve._private.commonr
   ray.serve._private.constantsr   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   ray.serve._private.utilsr   ray.serve.schemar   r   r   r   r3   r4   r%   r(   Filterr8   rG   rS   rY   rD   floatr   r   r   r   objectr   r   r   r   r  r  r   r  rE   r&   r$   <module>r)     s     				 



                     



 1 1 1 1 1 1 ? ? ? ? ? ? ? ? W W W W W W W W 8 8 8 8 8 8                                   $ = < < < < < 8 8 8 8 8 8 8 89w'8 9T 9 9 9 9
& & & & &. & & &         7>      F       .    W^   "86 86 86 86 86] 86 86 86v;c ;# ;s ; ; ; ; ;
 !2  t        ''"3 ' ' ' ' ': : : : : = = = = =V = = =@ $'Dt5 : : : : :, 48#"& %o& o& o&o& o& "	o&
 /0o& }o& 3-o& o& o& o& o& o&d
 
 
  487 777 /07 7 7 7tWC W W W W1 1 1 1 1 1 1 1 1 1r&   