o
    ¯bñ   ã                
   @   s¦  d 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mZ ddlmZ ddlmZ ddlmZ ddlmZ dd	lmZ dd
lmZ ddlmZ ddlmZ eƒ Zeeef Zdedefdd„Z dedefdd„Z!dd„ edƒdd„ dd„ fdd„ edƒe e!fgZ"dd„ e"D ƒZ#dede$fdd„Z%d e$defd!d"„Z&d#edefd$d%„Z'd&edefd'd(„Z(	)d4d*ee d+edefd,d-„Z)	.	/d5d0ee d+e
e d1e*de	e fd2d3„Z+d.S )6zA
Tools for saving and loading log events in a structured format.
é    )ÚdumpsÚloads)ÚIOÚAnyÚAnyStrÚDictÚIterableÚOptionalÚUnionÚcast)ÚUUID)ÚNamedConstant)ÚFailureé   ©ÚFileLogObserver)ÚflattenEvent)ÚLogEvent)ÚLogLevel)ÚLoggerÚfailureÚreturnc                 C   s    t |  ¡ t | jj| jjd�d�S )zÖ
    Convert a failure to a JSON-serializable data structure.

    @param failure: A failure to serialize.

    @return: a mapping of strings to ... stuff, mostly reminiscent of
        L{Failure.__getstate__}
    )Ú
__module__Ú__name__)Útype)ÚdictÚ__getstate__r   r   r   )r   © r   ú6/usr/lib/python3/dist-packages/twisted/logger/_json.pyÚfailureAsJSON   s   	þþr   ÚfailureDictc                 C   s0   t  t ¡}| d }t|d d|ƒ| d< | |_|S )zÌ
    Load a L{Failure} from a dictionary deserialized from JSON.

    @param failureDict: a JSON-deserialized object like one previously returned
        by L{failureAsJSON}.

    @return: L{Failure}
    r   r   r   )r   Ú__new__r   Ú__dict__)r    ÚfÚtypeInfor   r   r   ÚfailureFromJSON.   s
   
	r%   c                 C   s   t | tƒott| jd ƒ| u S ©N)Ú
isinstancer   Úgetattrr   Úname©Úlevelr   r   r   Ú<lambda>@   s   
r,   z$02E59486-F24D-46AD-8224-3ACDF2A5732Ac                 C   s   t | jd�S )N)r)   )r   r)   r*   r   r   r   r,   E   s    c                 C   s   t t| d d ƒS )Nr)   )r(   r   r*   r   r   r   r,   F   s    c                 C   s
   t | tƒS r&   )r'   r   )Úor   r   r   r,   I   s   
 z$E76887E2-20ED-49BF-A8F8-BA25CC586F2Dc                 C   s   i | ]	\}}}}||“qS r   r   )Ú.0Ú	predicateÚuuidÚsaverÚloaderr   r   r   Ú
<dictcomp>Q   s    r3   ÚaDictc                 C   s    d| v rt t| d ƒ | ƒS | S )a#  
    Dictionary-to-object-translation hook for certain value types used within
    the logging system.

    @see: the C{object_hook} parameter to L{json.load}

    @param aDict: A dictionary loaded from a JSON object.

    @return: C{aDict} itself, or the object represented by C{aDict}
    Ú__class_uuid__)ÚuuidToLoaderr   )r4   r   r   r   ÚobjectLoadHookT   s   r7   ÚpythonObjectc                 C   s>   t D ]\}}}}|| ƒr|| ƒ}t|ƒ|d< |  S qddiS )a�  
    Object-to-serializable hook for certain value types used within the logging
    system.

    @see: the C{default} parameter to L{json.dump}

    @param pythonObject: Any object.

    @return: If the object is one of the special types the logging system
        supports, a specially-formatted dictionary; otherwise, a marker
        dictionary indicating that it could not be serialized.
    r5   ÚunpersistableT)Ú	classInfoÚstr)r8   r/   r0   r1   r2   Úresultr   r   r   ÚobjectSaveHookd   s   ýr=   Úeventc                 C   s0   dt dtttf fdd„}t| ƒ t| |dd�S )a˜  
    Encode an event as JSON, flattening it if necessary to preserve as much
    structure as possible.

    Not all structure from the log event will be preserved when it is
    serialized.

    @param event: A log event dictionary.

    @return: A string of the serialized JSON; note that this will contain no
        newline characters, and may thus safely be stored in a line-delimited
        file.
    Úunencodabler   c                 S   s   t | tƒr
|  d¡S t| ƒS )z®
        Serialize an object not otherwise serializable by L{dumps}.

        @param unencodable: An unencodable object.

        @return: C{unencodable}, serialized
        Úcharmap)r'   ÚbytesÚdecoder=   )r?   r   r   r   Údefaultˆ   s   

zeventAsJSON.<locals>.defaultT)rC   Úskipkeys)Úobjectr
   ÚJSONDictr;   r   r   )r>   rC   r   r   r   ÚeventAsJSONy   s   rG   Ú	eventTextc                 C   s   t tt| td�ƒS )z¦
    Decode a log event from JSON.

    @param eventText: The output of a previous call to L{eventAsJSON}

    @return: A reconstructed version of the log event.
    )Úobject_hook)r   rF   r   r7   )rH   r   r   r   ÚeventFromJSON˜   s   rJ   úÚoutFileÚrecordSeparatorc                    s   t | ‡ fdd„ƒS )aÏ  
    Create a L{FileLogObserver} that emits JSON-serialized events to a
    specified (writable) file-like object.

    Events are written in the following form::

        RS + JSON + NL

    C{JSON} is the serialized event, which is JSON text.  C{NL} is a newline
    (C{"\n"}).  C{RS} is a record separator.  By default, this is a single
    RS character (C{"\x1e"}), which makes the default output conform to the
    IETF draft document "draft-ietf-json-text-sequence-13".

    @param outFile: A file-like object.  Ideally one should be passed which
        accepts L{str} data.  Otherwise, UTF-8 L{bytes} will be used.
    @param recordSeparator: The record separator to use.

    @return: A file log observer.
    c                    s   ˆ › t | ƒ› d�S )NÚ
)rG   )r>   ©rM   r   r   r,   º   s    z%jsonFileLogObserver.<locals>.<lambda>r   )rL   rM   r   rO   r   ÚjsonFileLogObserver£   s   ÿrP   Né   ÚinFileÚ
bufferSizec                 #   s  � dt dtfdd„}dtdtt fdd„‰ |du r*||  d	¡ƒ}|d
kr'|}n	d}n||ƒ}d}|dkr9d}ˆ }ndtdtt f‡ fdd„}t|ƒ}	 |  |¡}|set|ƒdkrc||ƒ}	|	durc|	V  dS |||ƒ7 }| |¡}
|
dd… D ]}t|ƒdkr‰||ƒ}	|	dur‰|	V  qv|
d }qK)aM  
    Load events from a file previously saved with L{jsonFileLogObserver}.
    Event records that are truncated or otherwise unreadable are ignored.

    @param inFile: A (readable) file-like object.  Data read from C{inFile}
        should be L{str} or UTF-8 L{bytes}.
    @param recordSeparator: The expected record separator.
        If L{None}, attempt to automatically detect the record separator from
        one of C{"\x1e"} or C{""}.
    @param bufferSize: The size of the read buffer used while reading from
        C{inFile}.

    @return: Log events as read from C{inFile}.
    Úsr   c                 S   s   t | tƒr| S |  d¡S )Núutf-8)r'   rA   Úencode)rT   r   r   r   ÚasBytesÒ   s   

z&eventsFromJSONLogFile.<locals>.asBytesÚrecordc                 S   sl   z	t | ƒ d¡}W n ty   tjdt | ƒd� Y d S w zt|ƒW S  ty5   tjdt | ƒd� Y d S w )NrU   z2Unable to decode UTF-8 for JSON record: {record!r}©rX   z&Unable to read JSON record: {record!r})rA   rB   ÚUnicodeDecodeErrorÚlogÚerrorrJ   Ú
ValueError)rX   Útextr   r   r   ÚeventFromBytearrayØ   s   þû
þz1eventsFromJSONLogFile.<locals>.eventFromBytearrayNr   ó   ó    ó   
c                    s.   | d t dƒkrˆ | ƒS tjdt| ƒd� d S )NéÿÿÿÿrN   z0Unable to read truncated JSON record: {record!r}rY   )Úordr[   r\   rA   rY   ©r_   r   r   ÚeventFromRecordþ   s   þz.eventsFromJSONLogFile.<locals>.eventFromRecordTr   rc   )r   rA   Ú	bytearrayr	   r   ÚreadÚlenÚsplit)rR   rM   rS   rW   ÚfirstÚrecordSeparatorBytesrf   ÚbufferÚnewDatar>   ÚrecordsrX   r   re   r   ÚeventsFromJSONLogFile¾   sB   €


€írp   )rK   )NrQ   ),Ú__doc__Újsonr   r   Útypingr   r   r   r   r   r	   r
   r   r0   r   Ú
constantlyr   Útwisted.python.failurer   Ú_filer   Ú_flattenr   Ú_interfacesr   Ú_levelsr   Ú_loggerr   r[   r;   rF   r   r%   r:   r6   rE   r7   r=   rG   rJ   rP   Úintrp   r   r   r   r   Ú<module>   sd   (ù
üöÿÿÿ
þýÿþýü