Skip to content

program_name

ProgramNameField

Bases: DataProvider

Selects a suitable program-name and adds it to the LogRecord as programName

Example

>>> import logging
>>> ProgramNameField().install()
Source code in src/loggext/extradata/program_name.py
class ProgramNameField(DataProvider):
    r"""
    Selects a suitable program-name and adds it to the LogRecord as `programName`

    !!! example
        ```pycon
        >>> import logging
        >>> ProgramNameField().install()
        ```
    """

    @cache
    def _program_name(self) -> str:
        import sys
        import os.path as p

        if sys.argv and sys.argv[0] != "-c":
            return p.basename(sys.argv[0])
        main = sys.modules.get('__main__')
        if main and hasattr(main, '__file__'):
            return p.basename(main.__file__)
        if sys.executable:
            return p.basename(sys.executable)
        return "python"

    def add_data(self, record):
        record.programName = self._program_name()