U
    luf1                     @   s  d 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 zddl	Z	W n e
k
r\   dZ	Y nX zddlZW n e
k
r   dZY nX ddlmZmZmZmZ edZedZedZed	d
dZeedddZG dd dejZdeeej ddddZdeddddZdS )aH  Logging support for Tornado.

Tornado uses three logger streams:

* ``tornado.access``: Per-request logging for Tornado's HTTP servers (and
  potentially other servers in the future)
* ``tornado.application``: Logging of errors from application code (i.e.
  uncaught exceptions from callbacks)
* ``tornado.general``: General-purpose logging, including any errors
  or warnings from Tornado itself.

These streams may be configured independently using the standard library's
`logging` module.  For example, you may wish to send ``tornado.access`` logs
to a separate file for analysis.
    N)_unicode)unicode_typebasestring_type)DictAnycastOptionalztornado.accessztornado.applicationztornado.general)returnc                   C   sv   z\t tjdrZtj rZtr:t  tddkrZW dS n trZtjttj	dt
 krZW dS W n tk
rp   Y nX dS )Nisattycolorsr   Twrapped_stderrF)hasattrsysstderrr
   cursesZ	setuptermZtigetnumcoloramagetattr
initialiseobject	Exception r   r   //tmp/pip-unpacked-wheel-bmg6zs32/tornado/log.py_stderr_supports_color7   s       
r   )sr	   c                 C   s,   z
t | W S  tk
r&   t|  Y S X d S N)r   UnicodeDecodeErrorrepr)r   r   r   r   _safe_unicodeJ   s    
r   c                
   @   sv   e Zd ZdZdZdZejdejdej	dej
dejdiZeed	d
efeeeeeeef ddddZeedddZdS )LogFormatterap  Log formatter used in Tornado.

    Key features of this formatter are:

    * Color support when logging to a terminal that supports it.
    * Timestamps on every log line.
    * Robust against str/bytes encoding problems.

    This formatter is enabled automatically by
    `tornado.options.parse_command_line` or `tornado.options.parse_config_file`
    (unless ``--logging=none`` is used).

    Color support on Windows versions that do not support ANSI color codes is
    enabled by use of the colorama__ library. Applications that wish to use
    this must first initialize colorama with a call to ``colorama.init``.
    See the colorama documentation for details.

    __ https://pypi.python.org/pypi/colorama

    .. versionchanged:: 4.5
       Added support for ``colorama``. Changed the constructor
       signature to be compatible with `logging.config.dictConfig`.
    zV%(color)s[%(levelname)1.1s %(asctime)s %(module)s:%(lineno)d]%(end_color)s %(message)sz%y%m%d %H:%M:%S               %TN)fmtdatefmtstylecolorr   r	   c           
      C   s   t jj| |d || _i | _|rt rtdk	rtdpDtdpDd}| D ] \}}t	t
||d| j|< qNtd}	|	dk	rt	|	d| _qd| _q| D ]\}}d	| | j|< qd
| _nd| _dS )aX  
        :arg bool color: Enables color support.
        :arg str fmt: Log message format.
          It will be applied to the attributes dict of log records. The
          text between ``%(color)s`` and ``%(end_color)s`` will be colored
          depending on the level if color support is on.
        :arg dict colors: color mappings from logging level to terminal color
          code
        :arg str datefmt: Datetime format.
          Used for formatting ``(asctime)`` placeholder in ``prefix_fmt``.

        .. versionchanged:: 3.2

           Added ``fmt`` and ``datefmt`` arguments.
        )r&   NZsetafZsetf    asciiZsgr0 z[2;3%dmz[0m)logging	Formatter__init___fmt_colorsr   r   Ztigetstritemsr   Ztparm_normal)
selfr%   r&   r'   r(   r   Zfg_colorlevelnocodenormalr   r   r   r.   t   s&    

 
zLogFormatter.__init__)recordr	   c              
   C   s  z$|  }t|tstt||_W n2 tk
rV } zd||jf |_W 5 d }~X Y nX | |t	t
| j|_|j| jkr| j|j |_| j|_nd |_|_| j|j }|jr|js| |j|_|jr| g}|dd |jdD  d|}|ddS )NzBad message (%r): %rr+   c                 s   s   | ]}t |V  qd S r   )r   ).0lnr   r   r   	<genexpr>   s     z&LogFormatter.format.<locals>.<genexpr>
z
    )
getMessage
isinstancer   AssertionErrorr   messager   __dict__
formatTimer   strr&   asctimer4   r0   r(   r2   Z	end_colorr/   exc_infoexc_textformatExceptionrstripextendsplitjoinreplace)r3   r7   r?   e	formattedlinesr   r   r   format   s(    "


zLogFormatter.format)__name__
__module____qualname____doc__DEFAULT_FORMATZDEFAULT_DATE_FORMATr,   DEBUGINFOWARNINGERRORCRITICALZDEFAULT_COLORSrB   boolr   intr.   r   rO   r   r   r   r   r   Q   s8        

4r   )optionsloggerr	   c                 C   s  | dkrddl }|jj} | jdks0| j dkr4dS |dkrDt }|tt| j  | jr| j	}|dkrtj
j| j| j| jdd}n<|dkrtj
j| j| j| j| jdd}nd	d
|  }t||tdd || | js| jdkr|j
st }|t  || dS )zTurns on formatted logging output as configured.

    This is called automatically by `tornado.options.parse_command_line`
    and `tornado.options.parse_config_file`.
    Nr   nonesizezutf-8)filenamemaxBytesbackupCountencodingtime)r`   whenintervalrb   rc   z.The value of log_rotate_mode option should be z"size" or "time", not "%s".F)r(   )tornado.optionsr\   r,   lower	getLoggersetLevelr   upperlog_file_prefixlog_rotate_modehandlersRotatingFileHandlerlog_file_max_sizelog_file_num_backupsTimedRotatingFileHandlerlog_rotate_whenlog_rotate_interval
ValueErrorsetFormatterr   
addHandlerlog_to_stderrStreamHandler)r\   r]   tornadoZrotate_modeZchannelerror_messager   r   r   enable_pretty_logging   sH    	
r|   )r\   r	   c                    s    dkrddl }|jj  jddddd  jdtdd	d
  jdtdddd  jdtddd
  jdtddd
  jdtddd
  jdtddd
  jdtddd
   fdd dS ) aB  Add logging-related flags to ``options``.

    These options are present automatically on the default options instance;
    this method is only necessary if you have created your own `.OptionParser`.

    .. versionadded:: 4.2
        This function existed in prior versions but was broken and undocumented until 4.2.
    Nr   r,   infozSSet the Python log level. If 'none', tornado won't touch the logging configuration.zdebug|info|warning|error|none)defaulthelpmetavarrx   zSend log output to stderr (colorized if possible). By default use stderr if --log_file_prefix is not set and no other logging is configured.)typer~   r   rl   PATHzPath prefix for log files. Note that if you are running multiple tornado processes, log_file_prefix must be different for each of them (e.g. include the port number))r   r~   r   r   rp   i z%max size of log files before rolloverrq   
   znumber of log files to keeprs   Zmidnightzcspecify the type of TimedRotatingFileHandler interval other options:('S', 'M', 'H', 'D', 'W0'-'W6')rt   r"   z$The interval value of timed rotatingrm   r_   z(The mode of rotating files(time or size)c                      s   t  S r   )r|   r   r\   r   r   <lambda>W  r)   z(define_logging_options.<locals>.<lambda>)rg   r\   ZdefinerZ   rB   r[   Zadd_parse_callback)r\   rz   r   r   r   define_logging_options	  sj    		
   	r   )NN)N)rS   r,   logging.handlersr   Ztornado.escaper   Ztornado.utilr   r   r   ImportErrorr   typingr   r   r   r   ri   Z
access_logZapp_logZgen_logrZ   r   rB   r   r-   r   Loggerr|   r   r   r   r   r   <module>   s:   




     2