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 )NrN   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   (

