Teks sumber — English
Terjemahan — Bahasa Indonesia
This page contains the API reference information. For tutorial information and discussion of more advanced topics, see
Formatters specify the layout of log records in the final output.
Logs a message with level :const:`DEBUG` on this logger. The *msg* is the message format string, and the *args* are the arguments which are merged into *msg* using the string formatting operator. (Note that this means that you can use keywords in the format string, together with a single dictionary argument.) No % formatting operation is performed on *msg* when no *args* are supplied.
If *exc_info* does not evaluate as false, it causes exception information to be added to the logging message. If an exception tuple (in the format returned by :func:`sys.exc_info`) or an exception instance is provided, it is used; otherwise, :func:`sys.exc_info` is called to get the exception information.
The second optional keyword argument is *stack_info*, which defaults to ``False``. If true, stack information is added to the logging message, including the actual logging call. Note that this is not the same stack information as that displayed through specifying *exc_info*: The former is stack frames from the bottom of the stack up to the logging call in the current thread, whereas the latter is information about stack frames which have been unwound, following an exception, while searching for exception handlers.
The third optional keyword argument is *stacklevel*, which defaults to ``1``. If greater than 1, the corresponding number of stack frames are skipped when computing the line number and function name set in the :class:`LogRecord` created for the logging event. This can be used in logging helpers so that the function name, filename and line number recorded are not the information for the helper function/method, but rather its caller. The name of this parameter mirrors the equivalent one in the :mod:`warnings` module.
FORMAT = '%(asctime)s %(clientip)-15s %(user)-8s %(message)s'
logging.basicConfig(format=FORMAT)
d = {'clientip': '192.168.0.1', 'user': 'fbloggs'}
logger = logging.getLogger('tcpserver')
logger.warning('Protocol problem: %s', 'connection reset', extra=d)
The keys in the dictionary passed in *extra* should not clash with the keys used by the logging system. (See the section on :ref:`logrecord-attributes` for more information on which keys are used by the logging system.)
If you choose to use these attributes in logged messages, you need to exercise some care. In the above example, for instance, the :class:`Formatter` has been set up with a format string which expects 'clientip' and 'user' in the attribute dictionary of the :class:`LogRecord`. If these are missing, the message will not be logged because a string formatting exception will occur. So in this case, you always need to pass the *extra* dictionary with these keys.
While this might be annoying, this feature is intended for use in specialized circumstances, such as multi-threaded servers where the same code executes in many contexts, and interesting conditions which arise are dependent on this context (such as remote client IP address and authenticated user name, in the above example). In such circumstances, it is likely that specialized :class:`Formatter`\ s would be used with particular :class:`Handler`\ s.
Finds the caller's source filename and line number. Returns the filename, line number, function name and stack information as a 4-element tuple. The stack information is returned as ``None`` unless *stack_info* is ``True``.
The *stacklevel* parameter is passed from code calling the :meth:`debug` and other APIs. If greater than 1, the excess is used to skip stack frames before determining the values to be returned. This will generally be useful when calling logging APIs from helper/wrapper code, so that the information in the event log refers not to the helper/wrapper code, but to the code that calls it.
Detailed information, typically only of interest to a developer trying to diagnose a problem.
Sets the formatter for this handler to *fmt*. The *fmt* argument must be a :class:`Formatter` instance or ``None``.
Do formatting for a record - if a formatter is set, use it. Otherwise, use the default formatter for the module.
Formatter Objects
A format string in the given *style* for the logged output as a whole. The possible mapping keys are drawn from the :class:`LogRecord` object's :ref:`logrecord-attributes`. If not specified, ``'%(message)s'`` is used, which is just the logged message.
A format string for the date/time portion of the logged output. If not specified, the default described in :meth:`formatTime` is used.
Can be one of ``'%'``, ``'{'`` or ``'$'`` and determines how the format string will be merged with its data: using one of :ref:`old-string-formatting` (``%``), :meth:`str.format` (``{``) or :class:`string.Template` (``$``). This only applies to *fmt* (e.g. ``'%(message)s'`` versus ``'{message}'``), not to the actual log messages passed to the logging methods. However, there are :ref:`other ways <formatting-styles>` to use ``{``- and ``$``-formatting for log messages.
If ``True`` (the default), incorrect or mismatched *fmt* and *style* will raise a :exc:`ValueError`; for example, ``logging.Formatter('%(asctime)s - %(message)s', style='{')``.
A dictionary with default values to use in custom fields. For example, ``logging.Formatter('%(ip)s %(message)s', defaults={"ip": None})``
The record's attribute dictionary is used as the operand to a string formatting operation. Returns the resulting string. Before formatting the dictionary, a couple of preparatory steps are carried out. The *message* attribute of the record is computed using *msg* % *args*. If the formatting string contains ``'(asctime)'``, :meth:`formatTime` is called to format the event time. If there is exception information, it is formatted using :meth:`formatException` and appended to the message. Note that the formatted exception information is cached in attribute *exc_text*. This is useful because the exception information can be pickled and sent across the wire, but you should be careful if you have more than one :class:`Formatter` subclass which customizes the formatting of exception information. In this case, you will have to clear the cached value (by setting the *exc_text* attribute to ``None``) after a formatter has done its formatting, so that the next formatter to handle the event doesn't use the cached value, but recalculates it afresh.
If stack information is available, it's appended after the exception information, using :meth:`formatStack` to transform it if necessary.
This method should be called from :meth:`format` by a formatter which wants to make use of a formatted time. This method can be overridden in formatters to provide for any specific requirement, but the basic behavior is as follows: if *datefmt* (a string) is specified, it is used with :func:`time.strftime` to format the creation time of the record. Otherwise, the format '%Y-%m-%d %H:%M:%S,uuu' is used, where the uuu part is a millisecond value and the other letters are as per the :func:`time.strftime` documentation. An example time in this format is ``2003-01-23 00:29:50,411``. The resulting string is returned.
This function uses a user-configurable function to convert the creation time to a tuple. By default, :func:`time.localtime` is used; to change this for a particular formatter instance, set the ``converter`` attribute to a function with the same signature as :func:`time.localtime` or :func:`time.gmtime`. To change it for all formatters, for example if you want all logging times to be shown in GMT, set the ``converter`` attribute in the ``Formatter`` class.
Previously, the default format was hard-coded as in this example: ``2010-09-06 22:38:15,292`` where the part before the comma is handled by a strftime format string (``'%Y-%m-%d %H:%M:%S'``), and the part after the comma is a millisecond value. Because strftime does not have a format placeholder for milliseconds, the millisecond value is appended using another format string, ``'%s,%03d'`` --- and both of these format strings have been hardcoded into this method. With the change, these strings are defined as class-level attributes which can be overridden at the instance level when desired. The names of the attributes are ``default_time_format`` (for the strftime format string) and ``default_msec_format`` (for appending the millisecond value).
The ``default_msec_format`` can be ``None``.
Formats the specified exception information (a standard exception tuple as returned by :func:`sys.exc_info`) as a string. This default implementation just uses :func:`traceback.print_exception`. The resulting string is returned.
Formats the specified stack information (a string as returned by :func:`traceback.print_stack`, but with the last newline removed) as a string. This default implementation just returns the input value.
A base formatter class suitable for subclassing when you want to format a number of records. You can pass a :class:`Formatter` instance which you want to use to format each line (that corresponds to a single record). If not specified, the default formatter (which just outputs the event message) is used as the line formatter.
Return formatted text for a list of *records*. The base implementation just returns the empty string if there are no records; otherwise, it returns the concatenation of the header, each record formatted with the line formatter, and the footer.
Although filters are used primarily to filter records based on more sophisticated criteria than levels, they get to see every record which is processed by the handler or logger they're attached to: this can be useful if you want to do things like counting how many records were processed by a particular logger or handler, or adding, changing or removing attributes in the :class:`LogRecord` being processed. Obviously changing the LogRecord needs to be done with some care, but it does allow the injection of contextual information into logs (see :ref:`filters-contextual`).
Contains all the information pertinent to the event being logged.
The primary information is passed in *msg* and *args*, which are combined using ``msg % args`` to create the :attr:`!message` attribute of the record.
The event description message, which can be a %-format string with placeholders for variable data, or an arbitrary object (see :ref:`arbitrary-object-messages`).
An exception tuple with the current exception information, as returned by :func:`sys.exc_info`, or ``None`` if no exception information is available.
A text string representing stack information from the base of the stack in the current thread, up to the logging call.
Returns the message for this :class:`LogRecord` instance after merging any user-supplied arguments with the message. If the user-supplied message argument to the logging call is not a string, :func:`str` is called on it to convert it to a string. This allows use of user-defined classes as messages, whose ``__str__`` method can return the actual format string to be used.
The LogRecord has a number of attributes, most of which are derived from the parameters to the constructor. (Note that the names do not always correspond exactly between the LogRecord constructor parameters and the LogRecord attributes.) These attributes can be used to merge data from the record into the format string. The following table lists (in alphabetical order) the attribute names, their meanings and the corresponding placeholder in a %-style format string.
If you are using {}-formatting (:func:`str.format`), you can use ``{attrname}`` as the placeholder in the format string. If you are using $-formatting (:class:`string.Template`), use the form ``${attrname}``. In both cases, of course, replace ``attrname`` with the actual attribute name you want to use.
In the case of {}-formatting, you can specify formatting flags by placing them after the attribute name, separated from it with a colon. For example: a placeholder of ``{msecs:03.0f}`` would format a millisecond value of ``4`` as ``004``. Refer to the :meth:`str.format` documentation for full details on the options available to you.
Format
Format
You shouldn't need to format this yourself.
Exception information formatted as a string. This is set when :meth:`Formatter.format` is invoked, or ``None`` if no exception has occurred.
The logged message, computed as ``msg % args``. This is set when :meth:`Formatter.format` is invoked.
The format string passed in the original logging call. Merged with ``args`` to produce ``message``, or an arbitrary object (see :ref:`arbitrary-object-messages`).
Stack frame information (where available) from the bottom of the stack in the current thread, up to and including the stack frame of the logging call which resulted in the creation of this record.
:class:`LoggerAdapter` instances are used to conveniently pass contextual information into logging calls. For a usage example, see the section on :ref:`adding contextual information to your logging output <context-info>`.
Modifies the message and/or keyword arguments passed to a logging call in order to insert contextual information. This implementation takes the object passed as *extra* to the constructor and adds it to *kwargs* using key 'extra'. The return value is a (*msg*, *kwargs*) tuple which has the (possibly modified) versions of the arguments passed in.
See :func:`setLogRecordFactory` for more information about the how the factory is called.
The *level* parameter was defaulted to level ``CRITICAL``. See :issue:`28524` for more information about this change.
Associates level *level* with text *levelName* in an internal dictionary, which is used to map numeric levels to a textual representation, for example when a :class:`Formatter` formats a message. This function can also be used to define your own levels. The only constraints are that all levels used must be registered using this function, levels should be positive integers and they should increase in increasing order of severity.
Levels are internally integers (as they need to be compared in the logging logic). This function is used to convert between an integer level and the level name displayed in the formatted log output by means of the ``%(levelname)s`` format specifier (see :ref:`logrecord-attributes`), and vice versa.
Does basic configuration for the logging system by either creating a :class:`StreamHandler` with a default :class:`Formatter` or using the given *formatter* instance, and adding it to the root logger. The functions :func:`debug`, :func:`info`, :func:`warning`, :func:`error` and :func:`critical` will call :func:`basicConfig` automatically if no handlers are defined for the root logger.
*format*
Use the specified format string for the handler. Defaults to attributes ``levelname``, ``name`` and ``message`` separated by colons.
Use the specified date/time format, as accepted by :func:`time.strftime`.
If *format* is specified, use this style for the format string. One of ``'%'``, ``'{'`` or ``'$'`` for :ref:`printf-style <old-string-formatting>`, :meth:`str.format` or :class:`string.Template` respectively. Defaults to ``'%'``.
If specified, this should be an iterable of already created handlers to add to the root logger. Any handlers which don't already have a formatter set will be assigned the default formatter created in this function. Note that this argument is incompatible with *filename* or *stream* - if both are present, a ``ValueError`` is raised.
*formatter*
If specified, set this formatter instance (see :ref:`formatter-objects`) for all involved handlers. If not specified, the default is to create and use an instance of :class:`logging.Formatter` based on arguments *format*, *datefmt* and *style*. When *formatter* is specified together with any of the three arguments *format*, *datefmt* and *style*, a ``ValueError`` is raised to signal that these arguments would lose meaning otherwise.
The *formatter* argument was added.
If *capture* is ``True``, warnings issued by the :mod:`warnings` module will be redirected to the logging system. Specifically, a warning will be formatted using :func:`warnings.formatwarning` and the resulting string logged to a logger named ``'py.warnings'`` with a severity of :const:`WARNING`.