o
    3gOY                     @   s  d 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	 ddl
mZmZ ddlmZmZmZmZmZmZmZ zddlZW n eyI   dZY nw dZdZd	ZeZejd
kr^eZeZeZ ne!Ze"ZdZ#dZ$eej%eej&eej'eej(eej(iZ)dZ*dZ+dZ,da-ea.da/da0ej1dkrddl2m3Z4 e4  e5deddddddddfddZ6G dd dej7Z8dd Z9ee:dfZ;dd Z<dd Z=deddddfddZ>dd  Z?e?  edfd!d"Z@d5d#d$ZAd6d&d'ZBd7d)d*ZCt-ejDd(fd+d,ZEd8d-d.ZFd/d0 ZGd1d2 ZHe5d3kre6 ZIeIJd4 dS dS )9a  
This helper provides a versatile yet easy to use and beautiful logging setup.
You can use it to log to the console and optionally to a logfile. This project
is heavily inspired by the Tornado web framework.

* https://logzero.readthedocs.io
* https://github.com/metachris/logzero

The call `logger.info("hello")` prints log messages in this format:

    [I 170213 15:02:00 test:203] hello

Usage:

    from logzero import logger

    logger.debug("hello")
    logger.info("info")
    logger.warning("warn")
    logger.error("error")

In order to also log to a file, just use `logzero.logfile(..)`:

    logzero.logfile("/tmp/test.log")

If you want to use specific loggers instead of the global default logger, use
`setup_logger(..)`:

    logger = logzero.setup_logger(logfile="/tmp/test.log")

The default loglevel is `DEBUG`. You can set it with the
parameter `level`.

See the documentation for more information: https://logzero.readthedocs.io
    N)Fore)JsonFormatter)RotatingFileHandlerSysLogHandler)CRITICALERRORWARNINGWARNINFODEBUGNOTSETzChris Hagerzchris@linuxuser.atz1.7.0)   zV%(color)s[%(levelname)1.1s %(asctime)s %(module)s:%(lineno)d]%(end_color)s %(message)sz%y%m%d %H:%M:%Slogzero_default_is_logzero_internal,_is_logzero_internal_handler_custom_loglevelnt)initFc                 C   s<  t |rdn| }d|_|r||k r|n|}|| |	r!t|
n|p%t }d}t|jD ]%}t|t	rHt
|t jr@|| q-t
|t jrH|}|| || q-|r_|dur^|| n|du r|t  }t|t	d || || || |rt|||d}t|t	d ||p| || || |S )ul	  
    Configures and returns a fully configured logger instance, no hassles.
    If a logger with the specified name already exists, it returns the existing instance,
    else creates a new one.

    If you set the ``logfile`` parameter with a filename, the logger will save the messages to the logfile,
    but does not rotate by default. If you want to enable log rotation, set both ``maxBytes`` and ``backupCount``.

    Usage:

    .. code-block:: python

        from logzero import setup_logger
        logger = setup_logger()
        logger.info("hello")

    :arg string name: Name of the `Logger object <https://docs.python.org/2/library/logging.html#logger-objects>`_. Multiple calls to ``setup_logger()`` with the same name will always return a reference to the same Logger object. (default: ``__name__``)
    :arg string logfile: If set, also write logs to the specified filename.
    :arg int level: Minimum `logging-level <https://docs.python.org/2/library/logging.html#logging-levels>`_ to display (default: ``DEBUG``).
    :arg Formatter formatter: `Python logging Formatter object <https://docs.python.org/2/library/logging.html#formatter-objects>`_ (by default uses the internal LogFormatter).
    :arg int maxBytes: Size of the logfile when rollover should occur. Defaults to 0, rollover never occurs.
    :arg int backupCount: Number of backups to keep. Defaults to 0, rollover never occurs.
    :arg int fileLoglevel: Minimum `logging-level <https://docs.python.org/2/library/logging.html#logging-levels>`_ for the file logger (is not set, it will use the loglevel from the ``level`` argument)
    :arg bool disableStderrLogger: Should the default stderr logger be disabled. Defaults to False.
    :arg bool isRootLogger: If True then returns a root logger. Defaults to False. (see also the `Python docs <https://docs.python.org/3/library/logging.html#logging.getLogger>`_).
    :arg bool json: If True then log in JSON format. Defaults to False. (uses `python-json-logger <https://github.com/madzak/python-json-logger>`_).
    :arg bool json_ensure_ascii: Passed to json.dumps as `ensure_ascii`, default: False (if False: writes utf-8 characters, if True: ascii only representation of special characters - eg. 'Öß')
    :return: A fully configured Python logging `Logger object <https://docs.python.org/2/library/logging.html#logger-objects>`_ you can use with ``.debug("msg")``, etc.
    NFT)filenamemaxBytesbackupCount)logging	getLogger	propagatesetLevel_get_json_formatterLogFormatterlisthandlershasattrLOGZERO_INTERNAL_LOGGER_ATTR
isinstanceFileHandlerremoveHandlerStreamHandlersetFormattersetattr
addHandlerr   )namelogfilelevel	formatterr   r   fileLogleveldisableStderrLoggerisRootLoggerjsonjson_ensure_ascii_loggerminLevel
_formatterstderr_stream_handlerhandlerrotating_filehandler r6   H/home/garg/my-data/venv/lib/python3.10/site-packages/logzero/__init__.pysetup_loggere   s@   









r8   c                   @   s*   e Zd ZdZdeeefddZdd ZdS )r   z
    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.
    Tc                 C   sF   t jj| |d || _i | _d| _|rt r!|| _tj| _dS dS dS )a\  
        :arg bool color: Enables color support.
        :arg string 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 string datefmt: Datetime format.
          Used for formatting ``(asctime)`` placeholder in ``prefix_fmt``.
        .. versionchanged:: 3.2
           Added ``fmt`` and ``datefmt`` arguments.
        )datefmt N)	r   	Formatter__init___fmt_colors_normal_stderr_supports_colorForegroundColorsRESET)selfcolorfmtr9   colorsr6   r6   r7   r<      s   
zLogFormatter.__init__c              
   C   s  z|  }t|tsJ t||_W n ty, } zd||jf |_W Y d }~nd }~ww | || j|_	|j
| jv rG| 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 N)_safe_unicode).0lnr6   r6   r7   	<genexpr>   s    
z&LogFormatter.format.<locals>.<genexpr>
z
    )
getMessager    basestring_typerH   message	Exception__dict__
formatTimer9   asctimelevelnor>   rD   r?   	end_colorr=   exc_infoexc_textformatExceptionrstripextendsplitjoinreplace)rC   recordrO   e	formattedlinesr6   r6   r7   format   s4   




zLogFormatter.formatN)	__name__
__module____qualname____doc__DEFAULT_FORMATDEFAULT_DATE_FORMATDEFAULT_COLORSr<   rb   r6   r6   r6   r7   r      s    
r   c                   C   sv   t ddkr	dS t jdkrdS tr9ttjdr9tj r9zt  t	ddkr,W dS W dS  t
y8   Y dS w dS )	NLOGZERO_FORCE_COLOR1Tr   isattyrF   r   F)osgetenvr'   cursesr   sysstderrrl   	setuptermtigetnumrP   r6   r6   r6   r7   r@     s    
r@   c                 C   s2   t | tr| S t | tstdt|  | dS )z
    Converts a string argument to a unicode string.
    If the argument is already a unicode string or None, it is returned
    unchanged.  Otherwise it must be a byte string and is decoded as utf8.
    z(Expected bytes, unicode, or None; got %rzutf-8)r    _TO_UNICODE_TYPESbytes	TypeErrortypedecode)valuer6   r6   r7   
to_unicode  s   



rz   c                 C   s&   zt | W S  ty   t|  Y S w rG   )rz   UnicodeDecodeErrorrepr)sr6   r6   r7   rH   -  s
   
rH   c                 C   s   t t| ||||datS )a<  
    Deprecated. Use `logzero.loglevel(..)`, `logzero.logfile(..)`, etc.

    Globally reconfigures the default `logzero.logger` instance.

    Usage:

    .. code-block:: python

        from logzero import logger, setup_default_logger
        setup_default_logger(level=WARN)
        logger.info("hello")  # this will not be displayed anymore because minimum loglevel was set to WARN

    :arg string logfile: If set, also write logs to the specified filename.
    :arg int level: Minimum `logging-level <https://docs.python.org/2/library/logging.html#logging-levels>`_ to display (default: `DEBUG`).
    :arg Formatter formatter: `Python logging Formatter object <https://docs.python.org/2/library/logging.html#formatter-objects>`_ (by default uses the internal LogFormatter).
    :arg int maxBytes: Size of the logfile when rollover should occur. Defaults to 0, rollover never occurs.
    :arg int backupCount: Number of backups to keep. Defaults to 0, rollover never occurs.
    :arg bool disableStderrLogger: Should the default stderr logger be disabled. Defaults to False.
    )r'   r(   r)   r*   r   r,   )r8   LOGZERO_DEFAULT_LOGGERlogger)r(   r)   r*   r   r   r,   r6   r6   r7   setup_default_logger4  s   r   c                  C   s>   t adadatrttjD ]} t|  qtt	tttdadS )zI
    Resets the internal default logger to the initial configuration
    N)r'   r(   r)   r*   )
r   	_loglevel_logfiler2   r   r   r   r"   r8   r~   )r4   r6   r6   r7   reset_default_loggerN  s   r   c                 C   sF   t |  tt jD ]}t|ts|rt|trq
||  q
| adS )aU  
    Set the minimum loglevel for the default logger (`logzero.logger`) and all handlers.

    This reconfigures only the internal handlers of the default logger (eg. stream and logfile).
    You can also update the loglevel for custom handlers by using `update_custom_handlers=True`.

    :arg int level: Minimum `logging-level <https://docs.python.org/2/library/logging.html#logging-levels>`_ to display (default: `DEBUG`).
    :arg bool update_custom_handlers: If you added custom handlers to this logger and want this to update them too, you need to set `update_custom_handlers` to `True`
    N)r   r   r   r   r   r   +LOGZERO_INTERNAL_HANDLER_IS_CUSTOM_LOGLEVELr   )r)   update_custom_handlersr4   r6   r6   r7   loglevelg  s   



r   c                 C   s0   t tjD ]}t|ts|r||  q| adS )a  
    Set the formatter for all handlers of the default logger (``logzero.logger``).

    This reconfigures only the logzero internal handlers by default, but you can also
    reconfigure custom handlers by using ``update_custom_handlers=True``.

    Beware that setting a formatter which uses colors also may write the color codes
    to logfiles.

    :arg Formatter formatter: `Python logging Formatter object <https://docs.python.org/2/library/logging.html#formatter-objects>`_ (by default uses the internal LogFormatter).
    :arg bool update_custom_handlers: If you added custom handlers to this logger and want this to update them too, you need to set ``update_custom_handlers`` to `True`
    N)r   r   r   r   r   r$   r2   )r*   r   r4   r6   r6   r7   r*     s
   
r*   ac           	      C   s   t t| | s	dS t| ||||d}t|td |r t|td ||p%t ||p1t	p1t
dd t| |rF|tjk rHt| dS dS dS )u  
    Setup logging to file (using a `RotatingFileHandler <https://docs.python.org/2/library/logging.handlers.html#rotatingfilehandler>`_ internally).

    By default, the file grows indefinitely (no rotation). You can use the ``maxBytes`` and
    ``backupCount`` values to allow the file to rollover at a predetermined size. When the
    size is about to be exceeded, the file is closed and a new file is silently opened
    for output. Rollover occurs whenever the current log file is nearly ``maxBytes`` in length;
    if either of ``maxBytes`` or ``backupCount`` is zero, rollover never occurs.

    If ``backupCount`` is non-zero, the system will save old log files by appending the
    extensions ‘.1’, ‘.2’ etc., to the filename. For example, with a ``backupCount`` of 5
    and a base file name of app.log, you would get app.log, app.log.1, app.log.2, up to
    app.log.5. The file being written to is always app.log. When this file is filled,
    it is closed and renamed to app.log.1, and if files app.log.1, app.log.2, etc. exist,
    then they are renamed to app.log.2, app.log.3 etc. respectively.

    :arg string filename: Filename of the logfile. Set to `None` to disable logging to the logfile.
    :arg Formatter formatter: `Python logging Formatter object <https://docs.python.org/2/library/logging.html#formatter-objects>`_ (by default uses the internal LogFormatter).
    :arg string mode: mode to open the file with. Defaults to ``a``
    :arg int maxBytes: Size of the logfile when rollover should occur. Defaults to 0, rollover never occurs.
    :arg int backupCount: Number of backups to keep. Defaults to 0, rollover never occurs.
    :arg string encoding: Used to open the file with that encoding.
    :arg int loglevel: Set a custom loglevel for the file logger, else uses the current global loglevel.
    :arg bool disableStderrLogger: Should the default stderr logger be disabled. Defaults to False.
    N)moder   r   encodingTF)rD   )__remove_internal_loggersr   r   r%   r   r   r   r   r$   r2   r   r&   r)   )	r   r*   r   r   r   r   r   r,   r5   r6   r6   r7   r(     s   

r(   Tc                 C   sd   t | jD ]*}t|tr/t|tr| | qt|tr"| | qt|tj	r/|r/| | qdS )a
  
    Remove the internal loggers (e.g. stderr logger and file logger) from the specific logger
    :param logger_to_update: the logger to remove internal loggers from
    :param disableStderrLogger: should the default stderr logger be disabled? defaults to True
    N)
r   r   r   r   r    r   r"   r   r   r#   )logger_to_updater,   r4   r6   r6   r7   r     s   



r   c                 C   s.   t | | t|d}t|td | | |S )aw  
    Setup logging to syslog and disable other internal loggers
    :param logger_to_update: the logger to enable syslog logging for
    :param facility: syslog facility to log to
    :param disableStderrLogger: should the default stderr logger be disabled? defaults to True
    :return the new SysLogHandler, which can be modified externally (e.g. for custom log level)
    )facilityT)r   r   r%   r   r&   )r   r   r,   syslog_handlerr6   r6   r7   syslog  s
   
	

r   c                 C   s   t | rt|nt |d dS )u  
    Enable/disable json logging for all handlers.

    Params:
    * json_ensure_ascii ... Passed to json.dumps as `ensure_ascii`, default: False (if False: writes utf-8 characters, if True: ascii only representation of special characters - eg. 'Öß')
    )r   N)r*   r   r   )enabler/   r   r6   r6   r7   r.     s   r.   c                 C   s*   g d}dd }d ||}t|| dS )N)rS   r   funcName	levelnamerT   linenomodulerO   r'   pathnameprocessprocessName
threadNamec                 S   s   dd | D S )Nc                 S   s   g | ]}d  |qS )z	%({0:s})s)rb   )rI   ir6   r6   r7   
<listcomp>	  s    z;_get_json_formatter.<locals>.log_format.<locals>.<listcomp>r6   )xr6   r6   r7   
log_format  s   z'_get_json_formatter.<locals>.log_format )r/   )r\   r   )r/   supported_keysr   custom_formatr6   r6   r7   r     s   r   c                    s   t   fdd}|S )Nc                     sj   d dd | D }d  fdd D }|r"|r"d ||g}n|p%|}tdj| | i  S )Nz, c                 S   s   g | ]}t |qS r6   )str)rI   argr6   r6   r7   r     s    z3log_function_call.<locals>.wrap.<locals>.<listcomp>c                    s   g | ]
}d | | f qS )z%s=%sr6   )rI   keykwargsr6   r7   r     s    z%s(%s))r\   r   debugrc   )argsr   args_str
kwargs_strall_args_strfuncr   r7   wrap  s   zlog_function_call.<locals>.wrap)	functoolswraps)r   r   r6   r   r7   log_function_call  s   	r   __main__hello)F)Nr   r   r   NNF)T)TFF)Krf   r   rm   rp   r   logzero.colorsr   rA   logzero.jsonloggerr   logging.handlersr   r   r   r   r   r	   r
   r   r   ro   ImportError
__author__	__email____version__ru   
bytes_typeversion_infor   unicode_typerN   rangexrangeunicode
basestringrg   rh   CYANGREENYELLOWREDri   r~   r   r   r   r   r   r2   r'   coloramar   colorama_initrc   r8   r;   r   r@   rw   rt   rz   rH   r   r   r   r*   r(   r   LOG_USERr   r.   r   r   r0   infor6   r6   r6   r7   <module>   s~   #$
	
 MT


4

