a
    Sic                  	   @   s  d Z ddlZddlmZ ddlZddlZddlZddlZddlZddlZddl	Z	ddl
Z
ddl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 zddlmZ W n ey   Y n0 ejZejZejZejZejZej Z!ej"Z#dZ$de	%d	d
  d Z&dZ'dZ(ej)*ddZ+da,da-dddddddZ.dddddZ/G dd dej0Z1G dd dej0Z2G dd dej3Z4G d d! d!e5Z6G d"d# d#ej0Z7ej8d$d%d&d'd( ej8d)d%d*d'd( ej9d+e:d,d-d.d'd( e;e1d/d0d1d2d'd3 e;e2d4i d5 e;e7d6dd7d'd8 e8d9d'd: d;d< Z<d=d> Z=d?d@ Z>dAd Z?dBd Z@dCd ZAdDdE ZBdFd ZCdGdH ZDdIdJ ZEi ZFdKdL ZGdMdN ZHi ZIdOdP ZJdQdR ZKdSdT ZLdUdV ZMdWdX ZNdYdZ ZOd[d\ ZPd]d^ ZQd_d` ZRdadb ZSdcdd ZTeTZUdedf ZVe!fdgdhZWddidjZXddkdlZYdmdn ZZdodp Z[dqdr Z\dsdt Z]d'a^G dudv dvej_Z`G dwdx dxejaZbG dydz dzejcZdG d{d| d|ee Zfd}d~ Zgdd Zhdd ZidddZjd%akdd Zldd Zmem  dS )a%  Abseil Python logging module implemented on top of standard logging.

Simple usage::

    from absl import logging

    logging.info('Interesting Stuff')
    logging.info('Interesting Stuff with Arguments: %d', 42)

    logging.set_verbosity(logging.INFO)
    logging.log(logging.DEBUG, 'This will *not* be printed')
    logging.set_verbosity(logging.DEBUG)
    logging.log(logging.DEBUG, 'This will be printed')

    logging.warning('Worrying Stuff')
    logging.error('Alarming Stuff')
    logging.fatal('AAAAHHHHH!!!!')  # Process exits.

Usage note: Do not pre-format the strings in your program code.
Instead, let the logging module perform argument interpolation.
This saves cycles because strings that don't need to be printed
are never formatted.  Note that this module does not attempt to
interpolate arguments when no arguments are given.  In other words::

    logging.info('Interesting Stuff: %s')

does not raise an exception because logging.info() has only one
argument, the message string.

"Lazy" evaluation for debugging
-------------------------------

If you do something like this::

    logging.debug('Thing: %s', thing.ExpensiveOp())

then the ExpensiveOp will be evaluated even if nothing
is printed to the log. To avoid this, use the level_debug() function::

  if logging.level_debug():
    logging.debug('Thing: %s', thing.ExpensiveOp())

Per file level logging is supported by logging.vlog() and
logging.vlog_is_on(). For example::

    if logging.vlog_is_on(2):
      logging.vlog(2, very_expensive_debug_message())

Notes on Unicode
----------------

The log output is encoded as UTF-8.  Don't pass data in other encodings in
bytes() instances -- instead pass unicode string instances when you need to
(for both the format string and arguments).

Note on critical and fatal:
Standard logging module defines fatal as an alias to critical, but it's not
documented, and it does NOT actually terminate the program.
This module only defines fatal but not critical, and it DOES terminate the
program.

The differences in behavior are historical and unfortunate.
    N)abc)flags)	converter)NoReturnz^(?P<severity>[IWEF])(?P<month>\d\d)(?P<day>\d\d) (?P<hour>\d\d):(?P<minute>\d\d):(?P<second>\d\d)\.(?P<microsecond>\d\d\d\d\d\d) +(?P<thread_id>-?\d+) (?P<filename>[a-zA-Z<][\w._<>-]+):(?P<line>\d+)   L      Z_absl_log_fatalzCRITICAL - loggingz	__init__.0123)debuginfowarningwarnerrorfatalr   r   r   r   )r   r   r   r   c                       sB   e Zd ZdZ fddZedd Zejdd Zdd Z  Z	S )	_VerbosityFlagzFlag class for -v/--verbosity.c                    s,   t t| jt t g|R i | d S N)superr   __init__r   ZIntegerParserArgumentSerializerselfargskwargs	__class__ Q/var/www/html/django/DPS/env/lib/python3.9/site-packages/absl/logging/__init__.pyr      s    
z_VerbosityFlag.__init__c                 C   s   | j S r   _valuer   r    r    r!   value   s    z_VerbosityFlag.valuec                 C   s   || _ |   d S r   )r#   _update_logging_levelsr   vr    r    r!   r%      s    c                 C   sf   t sdS | jtjkr"t| j}ntj| jd  }ttjj	v rXt 
tj tj
| n
t 
| dS )zZUpdates absl logging levels to the current verbosity.

    Visibility: module-private
    Nr	   )_absl_loggerr#   r   
ABSL_DEBUGabsl_to_standardr
   DEBUG_absl_handlerroothandlerssetLevelNOTSET)r   Zstandard_verbosityr    r    r!   r&      s    z%_VerbosityFlag._update_logging_levels)
__name__
__module____qualname____doc__r   propertyr%   setterr&   __classcell__r    r    r   r!   r      s   

r   c                       sB   e Zd ZdZ fddZedd Zejdd Zdd Z  Z	S )	_LoggerLevelsFlagzFlag class for --logger_levels.c                    s(   t t| jt t g|R i | d S r   )r   r9   r   _LoggerLevelsParser_LoggerLevelsSerializerr   r   r    r!   r      s    
z_LoggerLevelsFlag.__init__c                 C   s
   | j  S r   )r#   copyr$   r    r    r!   r%      s    z_LoggerLevelsFlag.valuec                 C   s   |d u ri n|| _ |   d S r   )r#   _update_logger_levelsr'   r    r    r!   r%      s    c                 C   s(   | j  D ]\}}t|| q
d S r   )r#   itemsr
   	getLoggerr0   )r   namelevelr    r    r!   r=      s    z'_LoggerLevelsFlag._update_logger_levels)
r2   r3   r4   r5   r   r6   r%   r7   r=   r8   r    r    r   r!   r9      s   

r9   c                   @   s   e Zd ZdZdd ZdS )r:   z Parser for --logger_levels flag.c                 C   sb   t |tjr|S dd |dD }t }|D ],}|dd\}}| }| }|||< q0|S )Nc                 S   s   g | ]}|  r|  qS r    )strip).0pairr    r    r!   
<listcomp>       z-_LoggerLevelsParser.parse.<locals>.<listcomp>,:r	   )
isinstancer   MappingsplitcollectionsOrderedDictrB   )r   r%   pairslevelsZ
name_levelr@   rA   r    r    r!   parse   s    
z_LoggerLevelsParser.parseN)r2   r3   r4   r5   rP   r    r    r    r!   r:      s   r:   c                   @   s   e Zd ZdZdd ZdS )r;   z$Serializer for --logger_levels flag.c                 C   s&   t |tr|S ddd | D S )NrG   c                 s   s   | ]\}}d  ||V  qdS )z{}:{}N)format)rC   r@   rA   r    r    r!   	<genexpr>  s   z4_LoggerLevelsSerializer.serialize.<locals>.<genexpr>)rI   strjoinr>   )r   r%   r    r    r!   	serialize   s
    

z!_LoggerLevelsSerializer.serializeN)r2   r3   r4   r5   rU   r    r    r    r!   r;      s   r;   c                       s:   e Zd ZdZ fddZedd Zejdd Z  ZS )_StderrthresholdFlagz!Flag class for --stderrthreshold.c                    s,   t t| jt t g|R i | d S r   )r   rV   r   r   ArgumentParserr   r   r   r    r!   r   	  s    
z_StderrthresholdFlag.__init__c                 C   s   | j S r   r"   r$   r    r    r!   r%     s    z_StderrthresholdFlag.valuec                 C   s^   |t v rt|}t | }n:| tv rH| }|dkr:d}tt| }ntd| || _d S )Nr   r   z--stderrthreshold must be one of (case-insensitive) 'debug', 'info', 'warning', 'error', 'fatal', or '0', '1', '2', '3', not '%s')_CPP_LEVEL_TO_NAMESintlower_CPP_NAME_TO_LEVELS
ValueErrorr#   )r   r(   Z	cpp_valuer    r    r!   r%     s    
)	r2   r3   r4   r5   r   r6   r%   r7   r8   r    r    r   r!   rV     s   
rV   logtostderrFzShould only log to stderr?T)Zallow_override_cppalsologtostderrzalso log to stderr?log_dirZTEST_TMPDIR z directory to write logfiles into	verbosityzLogging verbosity level. Messages logged at this level or lower will be included. Set to 1 for debug logging. If the flag was not set or supplied, the value will be changed from the default of -1 (warning) to 0 (info) after flags are parsed.r(   )Z
short_nameallow_hide_cpplogger_levelszSpecify log level of loggers. The format is a CSV list of `name:level`. Where `name` is the logger name used with `logging.getLogger()`, and `level` is a level name  (INFO, DEBUG, etc). e.g. `myapp.foo:INFO,other.logger:DEBUG`stderrthresholdaM  log messages at this level, or more severe, to stderr in addition to the logfile.  Possible values are 'debug', 'info', 'warning', 'error', and 'fatal'.  Obsoletes --alsologtostderr. Using --alsologtostderr cancels the effect of this flag. Please also note that this flag is subject to --verbosity and requires logfile not be stderr.)rc   showprefixforinfozIf False, do not prepend prefix to info messages when it's logged to stderr, --verbosity is set to INFO level, and python logging is used.c                   C   s
   t d jS )zReturns the logging verbosity.ra   )FLAGSr%   r    r    r    r!   get_verbosityP  s    rh   c                 C   s8   zt | }W n  ty,   tj|   }Y n0 |t_dS )ao  Sets the logging verbosity.

  Causes all messages of level <= v to be logged,
  and all messages of level > v to be silently discarded.

  Args:
    v: int|str, the verbosity level as an integer or string. Legal string values
        are those that can be coerced to an integer as well as case-insensitive
        'debug', 'info', 'warning', 'error', and 'fatal'.
  N)rY   r\   r   
ABSL_NAMESupperrg   ra   )r(   	new_levelr    r    r!   set_verbosityU  s
    rl   c                 C   sP   | t jv rt j|  t_n4t| tr8|  t jv r8| t_ntd	| t
| dS )a:  Sets the stderr threshold to the value passed in.

  Args:
    s: str|int, valid strings values are case-insensitive 'debug',
        'info', 'warning', 'error', and 'fatal'; valid integer values are
        logging.DEBUG|INFO|WARNING|ERROR|FATAL.

  Raises:
      ValueError: Raised when s is an invalid value.
  zset_stderrthreshold only accepts integer absl logging level from -3 to 1, or case-insensitive string values 'debug', 'info', 'warning', 'error', and 'fatal'. But found "{}" ({}).N)r   ABSL_LEVELSrg   re   rI   rS   rj   ri   r\   rQ   type)sr    r    r!   set_stderrthresholdg  s    
rp   c                 O   s   t t| g|R i | dS )zLogs a fatal message.N)logFATALmsgr   r   r    r    r!   r   ~  s    c                 O   s   t t| g|R i | dS )zLogs an error message.N)rq   ERRORrs   r    r    r!   r     s    c                 O   s   t t| g|R i | dS )zLogs a warning message.N)rq   WARNINGrs   r    r    r!   r     s    c                 O   s*   t dtd tt| g|R i | dS )z"Deprecated, use 'warning' instead.z8The 'warn' function is deprecated, use 'warning' insteadr   N)warningsr   DeprecationWarningrq   rv   rs   r    r    r!   r     s    r   c                 O   s   t t| g|R i | dS )zLogs an info message.N)rq   INFOrs   r    r    r!   r     s    c                 O   s   t t| g|R i | dS )zLogs a debug message.N)rq   r,   rs   r    r    r!   r     s    r   c                 O   s"   t | g|R i |ddi dS )z.Logs an exception, with traceback and message.exc_infoTN)r   rs   r    r    r!   	exception  s    r{   c                 C   s   t t| t S )zWrapper for _log_counter_per_token. Thread-safe.

  Args:
    token: The token for which to look up the count.

  Returns:
    The number of times this function has been called with
    *token* as an argument (starting at 0).
  )next_log_counter_per_token
setdefault	itertoolscount)tokenr    r    r!   _get_next_log_count_per_token  s    r   c                 G   s,   t t  }t| |||  g|R   dS )an  Logs ``msg % args`` at level 'level' once per 'n' times.

  Logs the 1st call, (N+1)st call, (2N+1)st call,  etc.
  Not threadsafe.

  Args:
    level: int, the absl logging level at which to log.
    msg: str, the message to be logged.
    n: int, the number of times this should be called before it is logged.
    *args: The args to be substituted into the msg.
  Nr   get_absl_logger
findCallerlog_ifrA   rt   nr   r   r    r    r!   log_every_n  s    r   c                 C   s<   t  }t| d}|du s(|| |kr4|t| < dS dS dS )a  Tests if 'num_seconds' have passed since 'token' was requested.

  Not strictly thread-safe - may log with the wrong frequency if called
  concurrently from multiple threads. Accuracy depends on resolution of
  'timeit.default_timer()'.

  Always returns True on the first call for a given 'token'.

  Args:
    token: The token for which to look up the count.
    num_seconds: The number of seconds to test for.

  Returns:
    Whether it has been >= 'num_seconds' since 'token' was last requested.
  NTF)timeitZdefault_timer_log_timer_per_tokenget)r   Znum_secondsnowthenr    r    r!   _seconds_have_elapsed  s    r   c                 G   s(   t t  |}t| ||g|R   dS )a  Logs ``msg % args`` at level ``level`` iff ``n_seconds`` elapsed since last call.

  Logs the first call, logs subsequent calls if 'n' seconds have elapsed since
  the last logging call from the same call site (file + line). Not thread-safe.

  Args:
    level: int, the absl logging level at which to log.
    msg: str, the message to be logged.
    n_seconds: float or int, seconds which should elapse before logging again.
    *args: The args to be substituted into the msg.
  N)r   r   r   r   )rA   rt   Z	n_secondsr   Z
should_logr    r    r!   log_every_n_seconds  s    r   c                 G   s*   t t  }t| |||k g|R   dS )a0  Logs ``msg % args`` at level ``level`` only first ``n`` times.

  Not threadsafe.

  Args:
    level: int, the absl logging level at which to log.
    msg: str, the message to be logged.
    n: int, the maximal number of times the message is logged.
    *args: The args to be substituted into the msg.
  Nr   r   r    r    r!   log_first_n  s    r   c                 G   s   |rt | |g|R   dS )zFLogs ``msg % args`` at level ``level`` only if condition is fulfilled.Nrq   )rA   rt   	conditionr   r    r    r!   r     s    r   c                 O   sb   | t jkrt j| d  }n| t jk r*t j} t | }tjjsDt  t	j
||g|R i | dS )aD  Logs ``msg % args`` at absl logging level ``level``.

  If no args are given just print msg, ignoring any interpolation specifiers.

  Args:
    level: int, the absl logging level at which to log the message
        (logging.DEBUG|INFO|WARNING|ERROR|FATAL). While some C++ verbose logging
        level constants are also supported, callers should prefer explicit
        logging.vlog() calls for such purpose.

    msg: str, the message to be logged.
    *args: The args to be substituted into the msg.
    **kwargs: May contain exc_info to add exception traceback to message.
  r	   N)r   r*   STANDARD_DEBUG
ABSL_FATALr+   r
   r.   r/   basicConfigr)   rq   )rA   rt   r   r   standard_levelr    r    r!   rq     s    


rq   c                 O   s   t | |g|R i | dS )a  Log ``msg % args`` at C++ vlog level ``level``.

  Args:
    level: int, the C++ verbose logging level at which to log the message,
        e.g. 1, 2, 3, 4... While absl level constants are also supported,
        callers should prefer logging.log|debug|info|... calls for such purpose.
    msg: str, the message to be logged.
    *args: The args to be substituted into the msg.
    **kwargs: May contain exc_info to add exception traceback to message.
  Nr   )rA   rt   r   r   r    r    r!   vlog-  s    r   c                 C   s>   | t jkrt j| d  }n| t jk r*t j} t | }t|S )a  Checks if vlog is enabled for the given level in caller's source file.

  Args:
    level: int, the C++ verbose logging level at which to log the message,
        e.g. 1, 2, 3, 4... While absl level constants are also supported,
        callers should prefer level_debug|level_info|... calls for
        checking those.

  Returns:
    True if logging is turned on for that level.
  r	   )r   r*   r   r   r+   r)   isEnabledFor)rA   r   r    r    r!   
vlog_is_on;  s    


r   c                   C   s   t    dS zFlushes all log files.N)get_absl_handlerflushr    r    r    r!   r   T  s    r   c                   C   s
   t  tkS )z+Returns True if debug logging is turned on.)rh   r,   r    r    r    r!   level_debugY  s    r   c                   C   s
   t  tkS )z*Returns True if info logging is turned on.)rh   ry   r    r    r    r!   
level_info^  s    r   c                   C   s
   t  tkS )z-Returns True if warning logging is turned on.)rh   rv   r    r    r    r!   level_warningc  s    r   c                   C   s
   t  tkS )z+Returns True if error logging is turned on.)rh   ru   r    r    r    r!   level_errork  s    r   c                 C   sN   | t jvrtd| t jj}|tjks@|tj	ks@t
|dsDdS |jS dS )aD  Returns the name of the log file.

  For Python logging, only one file is used and level is ignored. And it returns
  empty string if it logs to stderr/stdout or the log stream has no `name`
  attribute.

  Args:
    level: int, the absl.logging level.

  Raises:
    ValueError: Raised when `level` has an invalid value.
  zInvalid absl.logging level {}r@   r`   N)r   rm   r\   rQ   r   python_handlerstreamsysstderrstdouthasattrr@   )rA   r   r    r    r!   get_log_file_namep  s    

r   c                 C   s   | s*t jt jtjd d } d|  } t|d}zt }W n. t	yn   t
t drftt  }nd}Y n0 t }d| ||f }||| fS )a  Computes the directory and filename prefix for log file.

  Args:
    program_name: str|None, the filename part of the path to the program that
        is running without its extension.  e.g: if your program is called
        ``usr/bin/foobar.py`` this method should probably be called with
        ``program_name='foobar`` However, this is just a convention, you can
        pass in any string you want, and it will be used as part of the
        log filename. If you don't pass in anything, the default behavior
        is as described in the example.  In python standard logging mode,
        the program_name will be prepended with ``py_`` if it is the
        ``program_name`` argument is omitted.
    log_dir: str|None, the desired log directory.

  Returns:
    (log_dir, file_prefix, symlink_prefix)

  Raises:
    FileNotFoundError: raised in Python 3 when it cannot find a log directory.
    OSError: raised in Python 2 when it cannot find a log directory.
  r   zpy_%s)r_   getuidunknownz%s.%s.%s.log)ospathsplitextbasenamer   argvfind_log_dirgetpassgetuserKeyErrorr   rS   r   socketgethostname)program_namer_   actual_log_dirusernamehostnamefile_prefixr    r    r!   find_log_dir_and_names  s    


r   c                 C   sh   | r| g}n t d jr$t d jg}nddg}|D ]&}tj|r0t|tjr0|  S q0td| dS )a  Returns the most suitable directory to put log files into.

  Args:
    log_dir: str|None, if specified, the logfile(s) will be created in that
        directory.  Otherwise if the --log_dir command-line flag is provided,
        the logfile will be created in that directory.  Otherwise the logfile
        will be created in a standard location.

  Raises:
    FileNotFoundError: raised in Python 3 when it cannot find a log directory.
    OSError: raised in Python 2 when it cannot find a log directory.
  r_   z/tmp/z./z2Can't find a writable directory for logs, tried %sN)rg   r%   r   r   isdiraccessW_OKFileNotFoundError)r_   dirsdr    r    r!   r     s    

r   c                 C   sr   t | j}t| jd d }d}| j}t| r:tj}t}t	
|}d||j|j|j|j|j|t | j| j|f S )zxReturns the absl log prefix for the log record.

  Args:
    record: logging.LogRecord, the record to get prefix for.
  g      ?g    .Ar`   z,%c%02d%02d %02d:%02d:%02d.%06d %5d %s:%d] %s)time	localtimecreatedrY   levelno_is_non_absl_fatal_recordr
   ru   _CRITICAL_PREFIXr   Zget_initial_for_leveltm_montm_mdaytm_hourtm_mintm_sec_get_thread_idfilenamelineno)recordZcreated_tupleZcreated_microsecondZcritical_prefixrA   Zseverityr    r    r!   get_absl_log_prefix  s*    
r   c                 C   st   t | r8t| dd}|du r$td|j}|j}|j}n*t| trZt 	 d }| }d}nt
dt||| | S )a  Skips reporting the prefix of a given function or name by :class:`~absl.logging.ABSLLogger`.

  This is a convenience wrapper function / decorator for
  :meth:`~absl.logging.ABSLLogger.register_frame_to_skip`.

  If a callable function is provided, only that function will be skipped.
  If a function name is provided, all functions with the same name in the
  file that this is called in will be skipped.

  This can be used as a decorator of the intended function to be skipped.

  Args:
    func: Callable function or its name as a string.

  Returns:
    func (the input, unchanged).

  Raises:
    ValueError: The input is callable but does not have a function code object.
    TypeError: The input is neither callable nor a string.
  __code__Nz4Input callable does not have a function code object.r   z'Input is neither callable nor a string.)callablegetattrr\   co_filenameco_nameco_firstlinenorI   rS   r   r   	TypeError
ABSLLoggerregister_frame_to_skip)func	func_code	file_name	func_nameZfunc_linenor    r    r!   skip_log_prefix  s    
r   c                 C   s   | j tjko| jtd S NFr   r
   rr   __dict__r   _ABSL_LOG_FATALZ
log_recordr    r    r!   r     s    r   c                 C   s   | j tjko| jtdS r   r   r   r    r    r!   _is_absl_fatal_record$  s    r   c                       sb   e Zd ZdZd fdd	ZdddZdddZd	d
 Z fddZ fddZ	 fddZ
  ZS )PythonHandlerz?The handler class used by Abseil Python logging implementation.Nc                    s$   t t| | | |pt  d S r   )r   r   r   setFormatterPythonFormatter)r   r   	formatterr   r    r!   r   0  s    zPythonHandler.__init__c           	   	   C   s   dt _t||d\}}}d|tdtt t f }tj	||}t
|ddd| _ttdd	rtj	||d
 }z.tj|rt| ttj|| W n ty   Y n0 d	S )z;Starts logging messages to files instead of standard error.Fr   r_   z%s.INFO.%s.%dz%Y%m%d-%H%M%Sazutf-8)encodingsymlinkNz.INFO)rg   r]   r   r   strftimer   r   getpidr   rT   openr   r   islinkunlinkr   r   EnvironmentError)	r   r   r_   r   r   Zsymlink_prefixr   r   r   r    r    r!   start_logging_to_file4  s&    
z#PythonHandler.start_logging_to_filec                 C   s&   t d jrtj| _n| j||d dS )z4Conditionally logs to files, based on --logtostderr.r]   r   N)rg   r%   r   r   r   r   r   r   r_   r    r    r!   use_absl_log_fileQ  s    

zPythonHandler.use_absl_log_filec              	   C   sJ   |    z2z| j  W n ttfy.   Y n0 W |   n
|   0 dS r   )acquirer   r   r   r\   releaser$   r    r    r!   r   X  s    zPythonHandler.flushc                    s6   | j }tj| _ ztt| | W || _ n|| _ 0 dS )zEmits the record to stderr.

    This temporarily sets the handler stream to stderr, calls
    StreamHandler.emit, then reverts the stream back.

    Args:
      record: logging.LogRecord, the record to log.
    N)r   r   r   r   r   emit)r   r   
old_streamr   r    r!   _log_to_stderrc  s
    zPythonHandler._log_to_stderrc                    s   |j }t s.tr"tjd da| | n^td jrD| | nHt	t
| | ttd j}td jsv||kr| jtjkr| | t|r|   t  dS )a  Prints a record out to some streams.

    1. If ``FLAGS.logtostderr`` is set, it will print to ``sys.stderr`` ONLY.
    2. If ``FLAGS.alsologtostderr`` is set, it will print to ``sys.stderr``.
    3. If ``FLAGS.logtostderr`` is not set, it will log to the stream
        associated with the current thread.

    Args:
      record: :class:`logging.LogRecord`, the record to emit.
    z5WARNING: Logging before flag parsing goes to stderr.
Fr]   re   r^   N)r   rg   Z	is_parsed_warn_preinit_stderrr   r   writer   r%   r   r   r   r   Zstring_to_standardr   r   r   r   abort)r   r   rA   Zstderr_thresholdr   r    r!   r   u  s*    


zPythonHandler.emitc                    s   |    zx|   zBtjtjtjtjf}| j|vrRt| jdrH| j	 sR| j
  W n tyf   Y n0 tt| 
  W |   n
|   0 dS )z*Closes the stream to which we are writing.isattyN)r   r   r   r   r   
__stderr__
__stdout__r   r   r   closer\   r   r   r   )r   Zuser_managedr   r    r!   r    s    

zPythonHandler.close)NN)NN)NN)r2   r3   r4   r5   r   r   r   r   r   r   r  r8   r    r    r   r!   r   -  s   

*r   c                       s|   e Zd ZdZ fddZdd Zdd Zdd	 Zd
d Z fddZ	dd Z
edd Zdd ZdddZdddZ  ZS )ABSLHandlerz+Abseil Python logging module's log handler.c                    s&   t t|   t|d| _|   d S )N)r   )r   r  r   r   _python_handleractivate_python_handler)r   python_logging_formatterr   r    r!   r     s    zABSLHandler.__init__c                 C   s   | j |S r   )_current_handlerrQ   r   r   r    r    r!   rQ     s    zABSLHandler.formatc                 C   s   | j | d S r   )r  r   )r   fmtr    r    r!   r     s    zABSLHandler.setFormatterc                 C   s   | j | d S r   )r  r   r  r    r    r!   r     s    zABSLHandler.emitc                 C   s   | j   d S r   )r  r   r$   r    r    r!   r     s    zABSLHandler.flushc                    s   t t|   | j  d S r   )r   r  r  r  r$   r   r    r!   r    s    zABSLHandler.closec                 C   s   |  |}|r| j|S |S r   )filterr  handle)r   r   rvr    r    r!   r    s    
zABSLHandler.handlec                 C   s   | j S r   )r  r$   r    r    r!   r     s    zABSLHandler.python_handlerc                 C   s   | j | _dS )z?Uses the Python logging handler as the current logging handler.N)r  r  r$   r    r    r!   r    s    z#ABSLHandler.activate_python_handlerNc                 C   s   | j || d S r   )r  r   r   r    r    r!   r     s    zABSLHandler.use_absl_log_filec                 C   s   | j || d S r   )r  r   r   r    r    r!   r     s    z!ABSLHandler.start_logging_to_file)NN)NN)r2   r3   r4   r5   r   rQ   r   r   r   r  r  r6   r   r  r   r   r8   r    r    r   r!   r    s   

r  c                       s    e Zd ZdZ fddZ  ZS )r   z=Formatter class used by :class:`~absl.logging.PythonHandler`.c                    sV   t d js:t d jtjkr:|jtjkr:tjj	t
jkr:d}nt|}|tt| | S )zAppends the message from the record to the results of the prefix.

    Args:
      record: logging.LogRecord, the record to be formatted.

    Returns:
      The formatted string representing the record.
    rf   ra   r`   )rg   r%   r   	ABSL_INFOr   r
   ry   r-   r   r   r   r   r   r   r   rQ   )r   r   prefixr   r    r!   rQ     s    	

zPythonFormatter.format)r2   r3   r4   r5   rQ   r8   r    r    r   r!   r     s   r   c                       s~   e Zd ZdZe ZdddZdd Zdd	 Zd
d Z	dd Z
dd Zdd Zdd Z fddZdd ZedddZ  ZS )r   a  A logger that will create LogRecords while skipping some stack frames.

  This class maintains an internal list of filenames and method names
  for use when determining who called the currently executing stack
  frame.  Any method names from specific source files are skipped when
  walking backwards through the stack.

  Client code should use the register_frame_to_skip method to let the
  ABSLLogger know which method from which file should be
  excluded from the walk backwards through the stack.
  Fr	   c                 C   s   t j}td}|r|j}t|jvr|j|j|jf|vr|j|jf|vrd}|r~t	
 }|d tj||d | d}|j|j|j|fS |j}qdS )a  Finds the frame of the calling method on the stack.

    This method skips any frames registered with the
    ABSLLogger and any methods from this file, and whatever
    method is currently being used to generate the prefix for the log
    line.  Then it returns the file name, line number, and method name
    of the calling method.  An optional fourth item may be returned,
    callers who only need things from the first three are advised to
    always slice or index the result rather than using direct unpacking
    assignment.

    Args:
      stack_info: bool, when True, include the stack trace as a fourth item
          returned.  On Python 3 there are always four items returned - the
          fourth will be None when this is False.  On Python 2 the stdlib
          base class API only returns three items.  We do the same when this
          new parameter is unspecified or False for compatibility.

    Returns:
      (filename, lineno, methodname[, sinfo]) of the calling method.
    r   NzStack (most recent call last):
)file
)r   _frames_to_skipr   	_getframef_code_LOGGING_FILE_PREFIXr   r   r   ioStringIOr   	tracebackprint_stackgetvaluerstripf_linenof_back)r   
stack_info
stacklevelZ	f_to_skipframecodesinfooutr    r    r!   r     s*    


zABSLLogger.findCallerc                 O   s    | j tj|g|R i | dS )z/Logs ``msg % args`` with severity ``CRITICAL``.N)rq   r
   CRITICALr   rt   r   r   r    r    r!   critical0  s    zABSLLogger.criticalc                 O   s    | j tj|g|R i | dS )z,Logs ``msg % args`` with severity ``FATAL``.N)rq   r
   rr   r$  r    r    r!   r   4  s    zABSLLogger.fatalc                 O   s    | j tj|g|R i | dS )z,Logs ``msg % args`` with severity ``ERROR``.N)rq   r
   ru   r$  r    r    r!   r   8  s    zABSLLogger.errorc                 O   s.   t dtd | jtj|g|R i | dS )z+Logs ``msg % args`` with severity ``WARN``.z6The 'warn' method is deprecated, use 'warning' insteadr   N)rw   r   rx   rq   r
   WARNr$  r    r    r!   r   <  s    zABSLLogger.warnc                 O   s    | j tj|g|R i | dS )z.Logs ``msg % args`` with severity ``WARNING``.N)rq   r
   rv   r$  r    r    r!   r   B  s    zABSLLogger.warningc                 O   s    | j tj|g|R i | dS )z+Logs ``msg % args`` with severity ``INFO``.N)rq   r
   ry   r$  r    r    r!   r   F  s    zABSLLogger.infoc                 O   s    | j tj|g|R i | dS )z,Logs ``msg % args`` with severity ``DEBUG``.N)rq   r
   r,   r$  r    r    r!   r   J  s    zABSLLogger.debugc                    sB   |t jkr|di }d|t< tt| j||g|R i | dS )a  Logs a message at a cetain level substituting in the supplied arguments.

    This method behaves differently in python and c++ modes.

    Args:
      level: int, the standard logging level at which to log the message.
      msg: str, the text of the message to log.
      *args: The arguments to substitute in the message.
      **kwargs: The keyword arguments to substitute in the message.
    extraTN)r
   rr   r~   r   r   r   rq   )r   rA   rt   r   r   r'  r   r    r!   rq   N  s    
zABSLLogger.logc                 C   s   |  |r| | dS )a  Calls handlers without checking ``Logger.disabled``.

    Non-root loggers are set to disabled after setup with :func:`logging.config`
    if it's not explicitly specified. Historically, absl logging will not be
    disabled by that. To maintaining this behavior, this function skips
    checking the ``Logger.disabled`` bit.

    This logger can still be disabled by adding a filter that filters out
    everything.

    Args:
      record: logging.LogRecord, the record to handle.
    N)r
  callHandlersr  r    r    r!   r  a  s    
zABSLLogger.handleNc                 C   s0   |dur| j |||f n| j ||f dS )a  Registers a function name to skip when walking the stack.

    The :class:`~absl.logging.ABSLLogger` sometimes skips method calls on the
    stack to make the log messages meaningful in their appropriate context.
    This method registers a function from a particular file as one
    which should be skipped.

    Args:
      file_name: str, the name of the file that contains the function.
      function_name: str, the name of the function to skip.
      line_number: int, if provided, only the function with this starting line
          number will be skipped. Otherwise, all functions with the same name
          in the file will be skipped.
    N)r  add)clsr   function_nameline_numberr    r    r!   r   r  s    z!ABSLLogger.register_frame_to_skip)Fr	   )N)r2   r3   r4   r5   setr  r   r%  r   r   r   r   r   r   rq   r  classmethodr   r8   r    r    r   r!   r     s   
*r   c                  C   s   t  } | t@ S )a[  Gets id of current thread, suitable for logging as an unsigned quantity.

  If pywrapbase is linked, returns GetTID() for the thread ID to be
  consistent with C++ logging.  Otherwise, returns the numeric thread id.
  The quantities are made unsigned by masking with 2*sys.maxint + 1.

  Returns:
    Thread ID unique to this process (unsigned)
  )	threading	get_ident_THREAD_ID_MASK)	thread_idr    r    r!   r     s    
r   c                   C   s   t S )z!Returns the absl logger instance.)r)   r    r    r    r!   r     s    r   c                   C   s   t S )z"Returns the absl handler instance.)r-   r    r    r    r!   r     s    r   c                 C   s   t    | std dS )z{Uses the python implementation of the logging code.

  Args:
    quiet: No logging message about switching logging type.
  zRestoring pure python loggingN)r   r  r   )quietr    r    r!   use_python_logging  s    
r4  c                  C   sj   t s0dd tjjD } | D ]}tj| qda t }|tjjvrftj| td   td 	  dS )zUses the ABSL logging handler for logging.

  This method is called in :func:`app.run()<absl.app.run>` so the absl handler
  is used in absl apps.
  c                 S   s(   g | ] }t |tjr|jtjkr|qS r    )rI   r
   StreamHandlerr   r   r   )rC   hr    r    r!   rE     s   z$use_absl_handler.<locals>.<listcomp>Tra   rd   N)
+_attempted_to_remove_stderr_stream_handlersr
   r.   r/   removeHandlerr   
addHandlerrg   r&   r=   )r/   r6  Zabsl_handlerr    r    r!   use_absl_handler  s    r:  c                  C   s@   t rdS t } tt tda t|  t }t|adS )z!Initializes loggers and handlers.Nabsl)	r)   r
   getLoggerClasssetLoggerClassr   r?   r   r  r-   )Zoriginal_logger_classr  r    r    r!   _initialize  s    


r>  )NN)N)F)nr5   rL   r   r   r  r   r
   r   r   structr   r/  r   r   r  typesrw   r;  r   Zabsl.loggingr   typingr   ImportErrorrg   r   rr   Z
ABSL_ERRORru   ZABSL_WARNINGrv   r&  r  ry   r*   r,   ZABSL_LOGGING_PREFIX_REGEXcalcsizer1  r   r   r   rT   r  r)   r-   r[   rX   Flagr   r9   rW   r:   objectr;   rV   ZDEFINE_booleanZDEFINE_stringgetenvZDEFINE_flagrh   rl   rp   r   r   r   r   r   r   r{   r}   r   r   r   r   r   r   r   rq   r   r   r   r   r   r   Z
level_warnr   r   r   r   r   r   r   r   r   r5  r   Handlerr  	Formatterr   r<  r   r   r   r   r4  r7  r:  r>  r    r    r    r!   <module>   s  @

*
"
	"
1
  ' . 
