
    9gN                        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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mZ 	 e dZg dZda G d de      Z  G d de      Z! G d dejD                        Z# e#       Zd Z$d Z% ejL                         Z' G d de'      Z( G d dejR                        Z) G d d      Z* G d dejV                        Z,y# e$ r dZY w xY w)zThis module defines a logging class based on the built-in logging module.

.. note::

    This module is meant for internal ``astropy`` usage. For use in other
    packages, we recommend implementing your own logger instead.

    N)contextmanager)CRITICALDEBUGERRORFATALINFONOTSETWARNING)Path   )conf)config)find_current_module)AstropyUserWarningAstropyWarningTF)Confr   logAstropyLoggerLoggingErrorr	   r   r   r
   r   r   r   c                       e Zd ZdZy)r   z
    This exception is for various errors that occur in the astropy logger,
    typically when activating or deactivating logger-related features.
    N__name__
__module____qualname____doc__     .lib/python3.12/site-packages/astropy/logger.pyr   r   6   s    r   r   c                       e Zd ZdZy)_AstLogIPYExcz
    An exception that is used only as a placeholder to indicate to the
    IPython exception-catching mechanism that the astropy
    exception-capturing is activated. It should not actually be used as
    an exception anywhere.
    Nr   r   r   r   r    r    =   s    r   r    c                   @   e Zd ZdZ ej
                  dd      Z ej
                  dd      Z ej
                  dd      Z ej
                  dd      Z	 ej
                  d	d
      Z
 ej
                  dd      Z ej
                  dd      Z ej
                  d	d      Zy)r   z8
    Configuration parameters for `astropy.logger`.
    r   zThreshold for the logging messages. Logging messages that are less severe than this level will be ignored. The levels are ``'DEBUG'``, ``'INFO'``, ``'WARNING'``, ``'ERROR'``.Tz%Whether to log `warnings.warn` calls.Fz.Whether to log exceptions before raising them.z-Whether to always log messages to a log file. zThe file to log messages to.  If empty string is given, it defaults to a file ``'astropy.log'`` in the astropy config directory.z2Threshold for logging messages to `log_file_path`.z3%(asctime)r, %(origin)r, %(levelname)r, %(message)rzFormat for log file entries.z~The encoding (e.g., UTF-8) to use for the log file.  If empty string is given, it defaults to the platform-preferred encoding.N)r   r   r   r   _config
ConfigItem	log_levellog_warningslog_exceptionslog_to_filelog_file_pathlog_file_levellog_file_formatlog_file_encodingr   r   r   r   r   F   s     #""	2I &7%%d,STL'W''?N %'$$>K 'G&&
	(M (W''DN )g((=&O +**
	Dr   r   c                     t        j                         } t        j                  t               	 t        j                  d      at
        j                          t        j                  |        t
        S # t        j                  |        w xY w)zpInitializes the Astropy log--in most circumstances this is called
    automatically when importing astropy.
    astropy)logginggetLoggerClasssetLoggerClassr   	getLoggerr   _set_defaults)orig_logger_clss    r   	_init_logr5   p   sf     ,,.O=)0	*/J 	/s   )A3 3B
c                     t         j                         rt         j                          t         j                         rt         j	                          b 	 t        j                          	 t
        j                  j                  j                  } | j                         D ]  }|dk(  s|j                  d      s| |=  	 t        j                          y# t        j                          w xY w# t        $ r Y yw xY w)a  Shut down exception and warning logging (if enabled) and clear all
    Astropy loggers from the logging module's cache.

    This involves poking some logging module internals, so much if it is 'at
    your own risk' and is allowed to pass silently if any exceptions occur.
    r.   zastropy.N)r   exception_logging_enableddisable_exception_loggingwarnings_logging_enableddisable_warnings_loggingr/   _acquireLockLoggermanager
loggerDictkeys
startswith_releaseLock	Exception)r>   keys     r   _teardown_logrD      s     $$&%%'
##%$$&
	# //::J!()#s~~j'A"3 )   "G  " s1   C* (AC 6C <C* C''C* *	C65C6c                       e Zd ZdZ	 	 	 ddZdZd Zd Zd Zd Z	dZ
d Zd	 Zd
 Zd Zd Zd Zedd       Zedd       Zd Zy)r   a  
    This class is used to set up the Astropy logging.

    The main functionality added by this class over the built-in
    logging.Logger class is the ability to keep track of the origin of the
    messages, the ability to enable logging of warnings.warn calls and
    exceptions, and the addition of colorized output and context managers to
    easily capture messages to a file or list.
    Nc                     |	i }	d|	vr&t        dddg      }||j                  |	d<   nd|	d<   t        j                  | |||||||||	|
      S )Noriginr   Tr/   )finddiffunknown)funcextrasinfo)r   r   r<   
makeRecord)selfnamelevelpathnamelinenomsgargsexc_inforJ   rK   rL   current_modules               r   rM   zAstropyLogger.makeRecord   s~     =E5 0dI=NON)"0"9"9h"+h   ! 
 	
r   c                 J   t        |d   t              s | j                  |i |S |d   }t        |      t        t        fvr|j
                  j                   d|d    }nt        |d         }|d   }d }t        |      j                  d      }t        j                  j                         D ];  }	 t        t        |dd            j                  d      }||k(  s/|j                  } n || j                  |d|i       y | j                  |       y # t        $ r Y sw xY w)Nr   :    r"   __file__rG   rK   )
isinstancer   _showwarning_origtyper   	__class__r   strr   with_suffixsysmodulesvaluesgetattrrB   warning)	rN   rT   kwargsrf   messagemod_pathmod_namemodpaths	            r   _showwarningzAstropyLogger._showwarning   s&   $q'>2)4))4:6::q'
 =1C DD **334BtAwi@G$q'lG7 >--b1;;%%'C GCR89EEbI x<< ( LL8(<L=LL!  s   2%D	D"!D"c                     | j                   d uS N)r]   rN   s    r   r9   z&AstropyLogger.warnings_logging_enabled   s    %%T11r   c                     | j                         rt        d      t        j                  | _        | j
                  t        _        y)aG  
        Enable logging of warnings.warn() calls.

        Once called, any subsequent calls to ``warnings.warn()`` are
        redirected to this logger and emitted with level ``WARN``. Note that
        this replaces the output from ``warnings.warn``.

        This can be disabled with ``disable_warnings_logging``.
        z)Warnings logging has already been enabledN)r9   r   warningsshowwarningr]   rm   rp   s    r   enable_warnings_loggingz%AstropyLogger.enable_warnings_logging   s8     ((*JKK!)!5!5#00r   c                     | j                         st        d      t        j                  | j                  k7  rt        d      | j
                  t        _        d| _        y)z
        Disable logging of warnings.warn() calls.

        Once called, any subsequent calls to ``warnings.warn()`` are no longer
        redirected to this logger.

        This can be re-enabled with ``enable_warnings_logging``.
        z%Warnings logging has not been enabledzhCannot disable warnings logging: warnings.showwarning was not set by this logger, or has been overriddenN)r9   r   rr   rs   rm   r]   rp   s    r   r:   z&AstropyLogger.disable_warnings_logging
  sZ     ,,.FGG4#4#441 
  $55!%r   c                    |d }n<|}|j                   |j                   }|j                   t        j                  |      }t        |j                        dkD  r|j
                   dt        |       }nt        |j
                        }| | j                  |d|j
                  i       n| j                  |       | j                  |||       y )Nr   rX   rG   r[   )	tb_nextinspect	getmodulelenrT   r   r`   error_excepthook_orig)rN   etypevalue	tracebackrk   tbrh   s          r   _excepthookzAstropyLogger._excepthook   s    CB**(ZZ **(##B'C uzz?Q(3u:,7G%..)G?JJwx&>J?JJweUI6r   c                 d    t         rddlm} t         |       j                  v S | j
                  duS )z
        Determine if the exception-logging mechanism is enabled.

        Returns
        -------
        exclog : bool
            True if exception logging is on, False if not.
        r   get_ipythonN)_WITHIN_IPYTHONIPythonr   r    custom_exceptionsr|   rN   r   s     r   r7   z'AstropyLogger.exception_logging_enabled5  s.     + KM$C$CCC((44r   c                      j                         rt        d      t        r6ddlm} d fd	} |       j                  t        t        f|       d  _        yt        j                   _         j                  t        _
        y)z
        Enable logging of exceptions.

        Once called, any uncaught exceptions will be emitted with level
        ``ERROR`` by this logger, before being raised.

        This can be disabled with ``disable_exception_logging``.
        z*Exception logging has already been enabledr   r   Nc                 X    j                  |||       | j                  |||f|       y )N)	tb_offset)r   showtraceback)ipyshellr}   evaluer   r   rN   s        r   ipy_exc_handlerz?AstropyLogger.enable_exception_logging.<locals>.ipy_exc_handlerW  s1      3 &&vr':i&Pr   c                      y ro   r   )r}   r   r   s      r   <lambda>z8AstropyLogger.enable_exception_logging.<locals>.<lambda>f  s    dr   ro   )r7   r   r   r   r   set_custom_excBaseExceptionr    r|   rb   
excepthookr   )rN   r   r   s   `  r   enable_exception_loggingz&AstropyLogger.enable_exception_loggingE  sk     ))+KLL+Q M((.
 %CD! %(NND!!--CNr   c                    | j                         st        d      t        r&ddlm}  |       j                  t               d       yt        j                  | j                  k7  rt        d      | j                  t        _        d| _
        y)z
        Disable logging of exceptions.

        Once called, any uncaught exceptions will no longer be emitted by this
        logger.

        This can be re-enabled with ``enable_exception_logging``.
        z&Exception logging has not been enabledr   r   NzcCannot disable exception logging: sys.excepthook was not set by this logger, or has been overridden)r7   r   r   r   r   r   tuplerb   r   r   r|   r   s     r   r8   z'AstropyLogger.disable_exception_loggingl  ss     --/GHH+M(($7 ~~!1!11"- 
 "22CN$(D!r   c                     dt         _        y)z*
        Enable colorized output.
        TN_conf	use_colorrp   s    r   enable_colorzAstropyLogger.enable_color  s     r   c                     dt         _        y)z+
        Disable colorized output.
        FNr   rp   s    r   disable_colorzAstropyLogger.disable_color  s      r   c              #     K   t         j                  rt         j                  nd}t        j                  ||      }||j	                  |       ||j                  t        |             t        j                  t         j                        }|j                  |       | j                  |       d |j                          | j                  |       yw)a  
        Context manager to temporarily log messages to a file.

        Parameters
        ----------
        filename : str
            The file to log messages to.
        filter_level : str
            If set, any log messages less important than ``filter_level`` will
            not be output to the file. Note that this is in addition to the
            top-level filtering for the logger, so if the logger has level
            'INFO', then setting ``filter_level`` to ``INFO`` or ``DEBUG``
            will have no effect, since these messages are already filtered
            out.
        filter_origin : str
            If set, only log messages with an origin starting with
            ``filter_origin`` will be output to the file.

        Notes
        -----
        By default, the logger already outputs log messages to a file set in
        the Astropy configuration file. Using this context manager does not
        stop log messages from being output to that file, nor does it stop log
        messages from being printed to standard output.

        Examples
        --------
        The context manager is used as::

            with logger.log_to_file('myfile.log'):
                # your code here
        Nencoding)r   r,   r/   FileHandlersetLevel	addFilterFilterOrigin	Formatterr+   setFormatter
addHandlercloseremoveHandler)rN   filenamefilter_levelfilter_originr   fhfs          r   r(   zAstropyLogger.log_to_file  s     D .2-C-C4))  H=#KK%$LLm45d223


2s   CCc              #      K   t               }||j                  |       ||j                  t        |             | j	                  |       |j
                   | j                  |       yw)a  
        Context manager to temporarily log messages to a list.

        Parameters
        ----------
        filename : str
            The file to log messages to.
        filter_level : str
            If set, any log messages less important than ``filter_level`` will
            not be output to the file. Note that this is in addition to the
            top-level filtering for the logger, so if the logger has level
            'INFO', then setting ``filter_level`` to ``INFO`` or ``DEBUG``
            will have no effect, since these messages are already filtered
            out.
        filter_origin : str
            If set, only log messages with an origin starting with
            ``filter_origin`` will be output to the file.

        Notes
        -----
        Using this context manager does not stop log messages from being
        output to standard output.

        Examples
        --------
        The context manager is used as::

            with logger.log_to_list() as log_list:
                # your code here
        N)ListHandlerr   r   r   r   log_listr   )rN   r   r   lhs       r   log_to_listzAstropyLogger.log_to_list  s]     @ ]#KK%$LLm45kk2s   A+A-c           	      f   | j                         r| j                          | j                         r| j                          | j                  dd D ]  }| j                  |        | j                  t        j                         t               }| j                  |       t        j                  rt        j                  }	 t         d}	 |dk(  s|rt        j                   d      dz  }nt#        |      j%                         }t        j&                  rt        j&                  nd}t)        j*                  ||      }t)        j,                  t        j.                        }|j1                  |       |j                  t        j2                         | j                  |       t        j>                  r| jA                          t        jB                  r| jE                          yy# t        $ r d}Y 'w xY w# t4        $ r3}t7        j8                  d|d	t;        |       t<               Y d}~d}~ww xY w)
z4
        Reset logger to its initial state.
        NTFr"   r.   zastropy.logr   z	log file z" could not be opened for writing: )#r9   r:   r7   r8   handlersr   r   r   r%   StreamHandlerr   r(   r)   _ASTROPY_TEST_	NameErrorr#   get_config_dir_pathr   
expanduserr,   r/   r   r   r+   r   r*   OSErrorrr   warnr`   RuntimeWarningr&   rt   r'   r   )	rN   handlershr)   testing_moder   r   	formatteres	            r   r3   zAstropyLogger._set_defaults  s   
 ((*))+))+**, }}Q'Gw' ( 	dnn% _  ..M%#$ B&,33I>N " %)$7$B$B$DM595K5K411QU((J $--d.B.BC		*D//0#((*))+ 9  %$%  0 1Ax!" s+   G" 
A2G4 "G10G14	H0=)H++H0)NNNNN)r   r   r   r   rM   r]   rm   r9   rt   r:   r|   r   r7   r   r8   r   r   r   r(   r   r3   r   r   r   r   r      s    & !
F #"J21&( 7*5 %.N)8  , ,\ & &P;,r   r   c                       e Zd ZdZd Zy)r   z
    A specialized StreamHandler that logs INFO and DEBUG messages to
    stdout, and all other messages to stderr.  Also provides coloring
    of the output, if enabled in the parent logger.
    c                 l   |j                   t        j                  k  rt        j                  }nt        j
                  }|j                   t        j                  k  st        j                  st        |j                  d|       nddlm} |j                   t        j                  k  r ||j                  dd|       n~|j                   t        j                  k  r ||j                  dd|       nJ|j                   t        j                  k  r ||j                  dd|       n ||j                  dd|       |j                  r0|j                   |j                  z   d	|j"                  d
d|_        n"|j                    d	|j"                  d
d|_        t        d|j$                  z   |       y)z+
        The formatter for stderr.
        r"   )endfiler   )color_printmagentagreenbrownredz [s]rX   )r   N)levelnor/   r   rb   stdoutstderrr   r   r   print	levelnameutils.consoler   r
   r   rT   rS   rG   rh   )rN   recordstreamr   s       r   emitzStreamHandler.emit1  s7    >>W\\)ZZFZZF>>GMM)&""8 3~~,F,,iRfM'//1F,,g2FK'--/F,,g2FKF,,e&I ;; &

V[[ 89FMM!;LANFN &

|2fmmA->a@FNdV^^#&1r   N)r   r   r   r   r   r   r   r   r   r   *  s    2r   r   c                       e Zd ZdZd Zd Zy)r   zA filter for the record origin.c                     || _         y ro   )rG   )rN   rG   s     r   __init__zFilterOrigin.__init__U  s	    r   c                 L    |j                   j                  | j                         S ro   )rG   r@   rN   r   s     r   filterzFilterOrigin.filterX  s    }}''44r   N)r   r   r   r   r   r   r   r   r   r   r   R  s    )5r   r   c                       e Zd ZdZddZd Zy)r   z<A handler that can be used to capture the records in a list.Nc                 P    t         j                  j                  |        g | _        y ro   )r/   Handlerr   r   )rN   r   r   s      r   r   zListHandler.__init___  s      &r   c                 :    | j                   j                  |       y ro   )r   appendr   s     r   r   zListHandler.emitc  s    V$r   r   )r   r   r   r   r   r   r   r   r   r   r   \  s    F%r   r   )-r   rx   r/   rb   rr   
contextlibr   r   r   r   r   r   r	   r
   pathlibr   r"   r   r   r   r#   utilsr   utils.exceptionsr   r   __IPYTHON__r   r   __all__r   rB   r   r    ConfigNamespacer   r5   rD   r0   r<   r   r   r   r   r   r   r   r   <module>r      s      
  % H H H    & @ O& 9 I $7"" $N v"> 
 			!D,F D,N%2G)) %2P5 5%'// %C  Os   C C)(C)