U
    �AcjÚ   ã                   @   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eedœdd„Z eedœ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#ee$dœdd„Z%e$edœd d!„Z&eed"œd#d$„Z'eed%œd&d'„Z(d1ee eed)œd*d+„Z)d2ee e
e e*e	e d.œd/d0„Z+d,S )3zA
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   ú8/tmp/pip-unpacked-wheel-nrvc_22y/twisted/logger/_json.pyÚfailureAsJSON   s    	þþr   )ÚfailureDictr   c                 C   s4   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   Ú__setstate__)r    ÚfZtypeInfor   r   r   ÚfailureFromJSON.   s
    	

r$   c                 C   s   t | tƒott| jd ƒ| k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   ó    c                 C   s   t t| d d ƒS )Nr(   )r'   r   r)   r   r   r   r+   F   r,   c                 C   s
   t | tƒS r%   )r&   r   )Úor   r   r   r+   I   r,   z$E76887E2-20ED-49BF-A8F8-BA25CC586F2Dc                 C   s   i | ]\}}}}||“qS r   r   )Ú.0Ú	predicateÚuuidÚsaverÚloaderr   r   r   Ú
<dictcomp>Q   s    
  r3   )ÚaDictr   c                 C   s    d| k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   )ÚpythonObjectr   c                 C   s>   t D ]0\}}}}|| ƒ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   ZunpersistableT)Ú	classInfoÚstr)r8   r/   r0   r1   r2   Úresultr   r   r   ÚobjectSaveHookd   s    
r<   )Úeventr   c                 C   s.   t tttf dœ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)rB   Úskipkeys)Úobjectr
   ÚJSONDictr:   r   r   )r=   rB   r   r   r   ÚeventAsJSONy   s    rF   )Ú	eventTextr   c                 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   rE   r   r7   )rG   r   r   r   ÚeventFromJSON˜   s    rI   ú)ÚoutFileÚrecordSeparatorr   c                    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Ú
)rF   )r=   ©rL   r   r   r+   º   r,   z%jsonFileLogObserver.<locals>.<lambda>r   )rK   rL   r   rN   r   ÚjsonFileLogObserver£   s     
ÿrO   Né   )ÚinFilerL   Ú
bufferSizer   c                 #   s  t tdœdd„}ttt dœdd„‰ |dkrN||  d¡ƒ}|d	krH|}qZd
}n||ƒ}d
}|d
krld}ˆ }nttt dœ‡ fdd„}t|ƒ}|  |¡}|sÀt|ƒdkr¼||ƒ}	|	dk	r¼|	V  �q|||ƒ7 }| |¡}
|
dd… D ]&}t|ƒdkrâ||ƒ}	|	dk	râ|	V  qâ|
d }qŒdS )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 d S )Núutf-8)r&   r@   Úencode)rS   r   r   r   ÚasBytesÒ   s    
z&eventsFromJSONLogFile.<locals>.asBytes)Úrecordr   c                 S   st   zt | ƒ d¡}W n( tk
r:   tjdt | ƒd� Y d S X z
t|ƒW S  tk
rn   tjdt | ƒd� Y d S X d S )NrT   z2Unable to decode UTF-8 for JSON record: {record!r}©rW   z&Unable to read JSON record: {record!r})r@   rA   ÚUnicodeDecodeErrorÚlogÚerrorrI   Ú
ValueError)rW   Útextr   r   r   ÚeventFromBytearrayØ   s    þ
z1eventsFromJSONLogFile.<locals>.eventFromBytearrayNr   ó   r,   ó   
c                    s.   | d t dƒkrˆ | ƒS tjdt| ƒd� d S )NéÿÿÿÿrM   z0Unable to read truncated JSON record: {record!r}rX   )ÚordrZ   r[   r@   rX   ©r^   r   r   ÚeventFromRecordþ   s    þz.eventsFromJSONLogFile.<locals>.eventFromRecordr   ra   )r   r@   Ú	bytearrayr	   r   ÚreadÚlenÚsplit)rQ   rL   rR   rV   ÚfirstZrecordSeparatorBytesrd   ÚbufferZnewDatar=   ÚrecordsrW   r   rc   r   ÚeventsFromJSONLogFile¾   s:    


rl   )rJ   )NrP   ),Ú__doc__Újsonr   r   Útypingr   r   r   r   r   r	   r
   r   r0   r   Z
constantlyr   Ztwisted.python.failurer   Ú_filer   Ú_flattenr   Z_interfacesr   Z_levelsr   Z_loggerr   rZ   r:   rE   r   r$   r9   r6   rD   r7   r<   rF   rI   rO   Úintrl   r   r   r   r   Ú<module>   sX   (ù
üö ÿ þ  ýü