pax_global_header00006660000000000000000000000064147245546070014530gustar00rootroot0000000000000052 comment=ae3bfd1b85b6b4a3db535f69b975687c79498be4 loguru-0.7.3/000077500000000000000000000000001472455460700130545ustar00rootroot00000000000000loguru-0.7.3/.codecov.yml000066400000000000000000000002061472455460700152750ustar00rootroot00000000000000comment: false coverage: status: patch: no changes: no project: default: target: 100% threshold: loguru-0.7.3/.github/000077500000000000000000000000001472455460700144145ustar00rootroot00000000000000loguru-0.7.3/.github/SECURITY.md000066400000000000000000000013711472455460700162070ustar00rootroot00000000000000# Security Policy ## Supported Versions As an open source product, only the latest major version will be patched for security vulnerabilities. Previous versions of Loguru will likely not be retroactively patched. ## Reporting a Vulnerability To report a security issue, please email delgan.py@gmail.com with a description of the issue, the steps you took to create the issue, affected versions, and if known, mitigations for the issue. Once the vulnerability has been confirmed, it will be fixed as soon as possible if feasible. Alternatively, mitigating solutions will be detailed in the documentation: [Security considerations when using Loguru](https://loguru.readthedocs.io/en/stable/resources/recipes.html#security-considerations-when-using-loguru). loguru-0.7.3/.github/dependabot.yml000066400000000000000000000005051472455460700172440ustar00rootroot00000000000000version: 2 updates: - package-ecosystem: github-actions directory: / schedule: interval: monthly labels: [] - package-ecosystem: pip directory: / schedule: interval: monthly allow: - dependency-type: direct labels: [] ignore: - dependency-name: '*' update-types: [version-update:semver-patch] loguru-0.7.3/.github/workflows/000077500000000000000000000000001472455460700164515ustar00rootroot00000000000000loguru-0.7.3/.github/workflows/codeql-analysis.yml000066400000000000000000000013511472455460700222640ustar00rootroot00000000000000name: CodeQL on: push: pull_request: schedule: - cron: 0 0 * * 0 jobs: analyze: if: github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name != github.repository runs-on: ubuntu-22.04 permissions: actions: read contents: read security-events: write strategy: fail-fast: false matrix: language: [python] steps: - name: Checkout repository uses: actions/checkout@v4 - name: Initialize CodeQL uses: github/codeql-action/init@v3 with: languages: ${{ matrix.language }} - name: Autobuild uses: github/codeql-action/autobuild@v3 - name: Perform CodeQL Analysis uses: github/codeql-action/analyze@v3 loguru-0.7.3/.github/workflows/docs.yml000066400000000000000000000010611472455460700201220ustar00rootroot00000000000000name: Docs on: [push, pull_request] jobs: docs: if: github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name != github.repository runs-on: ubuntu-22.04 steps: - name: Checkout repository uses: actions/checkout@v4 - name: Set up Python uses: actions/setup-python@v5 with: python-version: '3.11' - name: Install dependencies run: | python -m pip install --upgrade pip python -m pip install tox - name: Build documentation run: | tox -e docs loguru-0.7.3/.github/workflows/lint.yml000066400000000000000000000010511472455460700201370ustar00rootroot00000000000000name: Lint on: [push, pull_request] jobs: lint: if: github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name != github.repository runs-on: ubuntu-22.04 steps: - name: Checkout repository uses: actions/checkout@v4 - name: Set up Python uses: actions/setup-python@v5 with: python-version: '3.11' - name: Install dependencies run: | python -m pip install --upgrade pip python -m pip install tox - name: Run linters run: | tox -e lint loguru-0.7.3/.github/workflows/packaging.yml000066400000000000000000000022021472455460700211140ustar00rootroot00000000000000name: Packaging on: [push, pull_request] jobs: build: if: github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name != github.repository runs-on: ubuntu-22.04 steps: - name: Checkout repository uses: actions/checkout@v4 - name: Set up Python uses: actions/setup-python@v5 with: python-version: '3.11' - name: Install dependencies run: | python -m pip install --upgrade pip python -m pip install tox - name: Build package run: | tox -e build - name: Upload package uses: actions/upload-artifact@v4 with: name: python-package-distributions path: dist/ publish: if: startsWith(github.ref, 'refs/tags/') runs-on: ubuntu-22.04 needs: build environment: name: pypi url: https://pypi.org/project/loguru/ permissions: id-token: write steps: - name: Download package uses: actions/download-artifact@v4 with: name: python-package-distributions path: dist/ - name: Publish package uses: pypa/gh-action-pypi-publish@release/v1 loguru-0.7.3/.github/workflows/tests.yml000066400000000000000000000035311472455460700203400ustar00rootroot00000000000000name: Tests on: push: pull_request: schedule: - cron: 0 0 * * 0 jobs: tests: if: github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name != github.repository strategy: fail-fast: false matrix: os: - ubuntu-22.04 python-version: - '3.7' - '3.8' - '3.9' - '3.10' - '3.11' - '3.12' - '3.13' - pypy-3.10 allow-failure: - false include: - os: ubuntu-20.04 python-version: '3.5' allow-failure: false - os: ubuntu-20.04 python-version: '3.6' allow-failure: false - os: windows-2022 python-version: '3.12' allow-failure: false - os: macos-13 python-version: '3.12' allow-failure: false - os: ubuntu-22.04 python-version: 3.14-dev allow-failure: true runs-on: ${{ matrix.os }} steps: - name: Checkout repository uses: actions/checkout@v4 - name: Set up Python uses: actions/setup-python@v5 with: python-version: ${{ matrix.python-version }} env: # Workaround for https://github.com/actions/setup-python/issues/866 PIP_TRUSTED_HOST: pypi.python.org pypi.org files.pythonhosted.org - name: Install dependencies run: | python -m pip install --upgrade pip python -m pip install tox - name: Run tests run: | tox -e tests continue-on-error: ${{ matrix.allow-failure }} - name: Upload coverage to Codecov uses: codecov/codecov-action@v5 with: token: ${{ secrets.CODECOV_TOKEN }} flags: ${{ matrix.os }}_${{ matrix.python-version }} verbose: true fail_ci_if_error: true continue-on-error: ${{ matrix.allow-failure }} loguru-0.7.3/.gitignore000066400000000000000000000022301472455460700150410ustar00rootroot00000000000000# Byte-compiled / optimized / DLL files __pycache__/ *.py[cod] *$py.class # C extensions *.so # Distribution / packaging .Python env/ build/ develop-eggs/ dist/ downloads/ eggs/ .eggs/ lib/ lib64/ parts/ sdist/ var/ wheels/ *.egg-info/ .installed.cfg *.egg # PyInstaller # Usually these files are written by a python script from a template # before PyInstaller builds the exe, so as to inject date/other infos into it. *.manifest *.spec # Installer logs pip-log.txt pip-delete-this-directory.txt # Unit test / coverage reports htmlcov/ .tox/ .coverage .coverage.* .cache nosetests.xml coverage.xml *.cover .hypothesis/ # Translations *.mo *.pot # Django stuff: *.log local_settings.py # Flask stuff: instance/ .webassets-cache # Scrapy stuff: .scrapy # Sphinx documentation docs/_build/ # PyBuilder target/ # Jupyter Notebook .ipynb_checkpoints # pyenv .python-version # celery beat schedule file celerybeat-schedule # SageMath parsed files *.sage.py # dotenv .env # virtualenv .venv venv/ ENV/ # Spyder project settings .spyderproject .spyproject # Rope project settings .ropeproject # mkdocs documentation /site # mypy .mypy_cache/ # Idea IDE .idea/ loguru-0.7.3/.pre-commit-config.yaml000066400000000000000000000014541472455460700173410ustar00rootroot00000000000000repos: - repo: https://github.com/pre-commit/pre-commit-hooks rev: v5.0.0 hooks: - id: end-of-file-fixer - id: trailing-whitespace - id: check-added-large-files - id: mixed-line-ending args: [--fix=lf] - repo: https://github.com/crate-ci/typos rev: v1.26.0 hooks: - id: typos - repo: https://github.com/macisamuele/language-formatters-pre-commit-hooks rev: v2.14.0 hooks: - id: pretty-format-ini args: [--autofix] - id: pretty-format-yaml args: [--autofix, --indent, '2'] - repo: https://github.com/ComPWA/taplo-pre-commit rev: v0.9.3 hooks: - id: taplo-format - repo: https://github.com/ambv/black rev: 24.10.0 hooks: - id: black - repo: https://github.com/astral-sh/ruff-pre-commit rev: v0.8.0 hooks: - id: ruff args: [--fix, --exit-non-zero-on-fix] loguru-0.7.3/.readthedocs.yml000066400000000000000000000003541472455460700161440ustar00rootroot00000000000000version: 2 build: os: ubuntu-20.04 tools: python: '3.11' python: install: - method: pip path: . extra_requirements: - dev sphinx: builder: html configuration: docs/conf.py formats: - htmlzip - pdf - epub loguru-0.7.3/.vscode/000077500000000000000000000000001472455460700144155ustar00rootroot00000000000000loguru-0.7.3/.vscode/settings.json000066400000000000000000000002241472455460700171460ustar00rootroot00000000000000{ "python.testing.pytestArgs": [ "tests" ], "python.testing.unittestEnabled": false, "python.testing.pytestEnabled": true } loguru-0.7.3/CHANGELOG.rst000066400000000000000000000547361472455460700151140ustar00rootroot00000000000000`0.7.3`_ (2024-12-06) ===================== - Fix Cython incompatibility caused by the absence of underlying stack frames, which resulted in a ``ValueError`` during logging (`#88 `_). - Fix possible ``RuntimeError`` when removing all handlers with ``logger.remove()`` due to thread-safety issue (`#1183 `_, thanks `@jeremyk `_). - Fix ``diagnose=True`` option of exception formatting not working as expected with Python 3.13 (`#1235 `_, thanks `@etianen `_). - Fix non-standard level names not fully compatible with ``logging.Formatter()`` (`#1231 `_, thanks `@yechielb2000 `_). - Fix inability to display a literal ``"\"`` immediately before color markups (`#988 `_). - Fix possible infinite recursion when an exception is raised from a ``__repr__`` method decorated with ``logger.catch()`` (`#1044 `_). - Improve performance of ``datetime`` formatting while logging messages (`#1201 `_, thanks `@trim21 `_). - Reduce startup time in the presence of installed but unused ``IPython`` third-party library (`#1001 `_, thanks `@zakstucke `_). `0.7.2`_ (2023-09-11) ===================== - Add support for formatting of ``ExceptionGroup`` errors (`#805 `_). - Fix possible ``RuntimeError`` when using ``multiprocessing.set_start_method()`` after importing the ``logger`` (`#974 `_). - Fix formatting of possible ``__notes__`` attached to an ``Exception`` (`#980 `_). `0.7.1`_ (2023-09-04) ===================== - Add a new ``context`` optional argument to ``logger.add()`` specifying ``multiprocessing`` context (like ``"spawn"`` or ``"fork"``) to be used internally instead of the default one (`#851 `_). - Add support for true colors on Windows using ANSI/VT console when available (`#934 `_, thanks `@tunaflsh `_). - Fix possible deadlock when calling ``logger.complete()`` with concurrent logging of an asynchronous sink (`#906 `_). - Fix file possibly rotating too early or too late when re-starting an application around midnight (`#894 `_). - Fix inverted ``""`` and ``""`` color tags (`#943 `_, thanks `@tunaflsh `_). - Fix possible untraceable errors raised when logging non-unpicklable ``Exception`` instances while using ``enqueue=True`` (`#329 `_). - Fix possible errors raised when logging non-picklable ``Exception`` instances while using ``enqueue=True`` (`#342 `_, thanks `@ncoudene `_). - Fix missing seconds and microseconds when formatting timezone offset that requires such accuracy (`#961 `_). - Raise ``ValueError`` if an attempt to use nanosecond precision for time formatting is detected (`#855 `_). `0.7.0`_ (2023-04-10) ===================== - Update ``InterceptHandler`` recipe to make it compatible with Python 3.11 (`#654 `_). - Add a new ``watch`` optional argument to file sinks in order to automatically re-create possibly deleted or changed file (`#471 `_). - Make ``patch()`` calls cumulative instead of overriding the possibly existing patching function (`#462 `_). - Make sinks added with ``enqueue=True`` and ``catch=False`` still process logged messages in case of internal exception (`#833 `_). - Avoid possible deadlocks caused by re-using the logger inside a sink, a signal handler or a ``__del__`` method. Since the logger is not re-entrant, such misuse will be detected and will now generate a ``RuntimeError`` (`#712 `_, thanks `@jacksmith15 `_). - Fix file sink rotation using an aware ``datetime.time`` for which the timezone was ignored (`#697 `_). - Fix logs colorization not automatically enabled for Jupyter Notebook and Google Colab (`#494 `_). - Fix logs colorization not automatically enabled for Github Actions and others CI platforms (`#604 `_). - Fix ``logger.complete()`` possibly hanging forever when ``enqueue=True`` and ``catch=False`` if internal thread killed due to ``Exception`` raised by sink (`#647 `_). - Fix incompatibility with ``freezegun`` library used to simulate time (`#600 `_). - Raise exception if ``logger.catch()`` is used to wrap a class instead of a function to avoid unexpected behavior (`#623 `_). `0.6.0`_ (2022-01-29) ===================== - Remove internal use of ``pickle.loads()`` to fix the (finally rejected) security vulnerability referenced as `CVE-2022-0329 `_ (`#563 `_). - Modify coroutine sink to make it discard log messages when ``loop=None`` and no event loop is running (due to internally using ``asyncio.get_running_loop()`` in place of ``asyncio.get_event_loop()``). - Remove the possibility to add a coroutine sink with ``enqueue=True`` if ``loop=None`` and no event loop is running. - Change default encoding of file sink to be ``utf8`` instead of ``locale.getpreferredencoding()`` (`#339 `_). - Prevent non-ascii characters to be escaped while logging JSON message with ``serialize=True`` (`#575 `_, thanks `@ponponon `_). - Fix ``flake8`` errors and improve code readability (`#353 `_, thanks `@AndrewYakimets `_). `0.5.3`_ (2020-09-20) ===================== - Fix child process possibly hanging at exit while combining ``enqueue=True`` with third party library like ``uwsgi`` (`#309 `_, thanks `@dstlmrk `_). - Fix possible exception during formatting of non-string messages (`#331 `_). `0.5.2`_ (2020-09-06) ===================== - Fix ``AttributeError`` within handlers using ``serialize=True`` when calling ``logger.exception()`` outside of the context of an exception (`#296 `_). - Fix error while logging an exception containing a non-picklable ``value`` to a handler with ``enqueue=True`` (`#298 `_). - Add support for async callable classes (with ``__call__`` method) used as sinks (`#294 `_, thanks `@jessekrubin `_). `0.5.1`_ (2020-06-12) ===================== - Modify the way the ``extra`` dict is used by ``LogRecord`` in order to prevent possible ``KeyError`` with standard ``logging`` handlers (`#271 `_). - Add a new ``default`` optional argument to ``logger.catch()``, it should be the returned value by the decorated function in case an error occurred (`#272 `_). - Fix ``ValueError`` when using ``serialize=True`` in combination with ``logger.catch()`` or ``logger.opt(record=True)`` due to circular reference of the ``record`` dict (`#286 `_). `0.5.0`_ (2020-05-17) ===================== - Remove the possibility to modify the severity ``no`` of levels once they have been added in order to prevent surprising behavior (`#209 `_). - Add better support for "structured logging" by automatically adding ``**kwargs`` to the ``extra`` dict besides using these arguments to format the message. This behavior can be disabled by setting the new ``.opt(capture=False)`` parameter (`#2 `_). - Add a new ``onerror`` optional argument to ``logger.catch()``, it should be a function which will be called when an exception occurs in order to customize error handling (`#224 `_). - Add a new ``exclude`` optional argument to ``logger.catch()``, is should be a type of exception to be purposefully ignored and propagated to the caller without being logged (`#248 `_). - Modify ``complete()`` to make it callable from non-asynchronous functions, it can thus be used if ``enqueue=True`` to make sure all messages have been processed (`#231 `_). - Fix possible deadlocks on Linux when ``multiprocessing.Process()`` collides with ``enqueue=True`` or ``threading`` (`#231 `_). - Fix ``compression`` function not executable concurrently due to file renaming (to resolve conflicts) being performed after and not before it (`#243 `_). - Fix the filter function listing files for ``retention`` being too restrictive, it now matches files based on the pattern ``"basename(.*).ext(.*)"`` (`#229 `_). - Fix the impossibility to ``remove()`` a handler if an exception is raised while the sink' ``stop()`` function is called (`#237 `_). - Fix file sink left in an unstable state if an exception occurred during ``retention`` or ``compression`` process (`#238 `_). - Fix situation where changes made to ``record["message"]`` were unexpectedly ignored when ``opt(colors=True)``, causing "out-of-date" ``message`` to be logged due to implementation details (`#221 `_). - Fix possible exception if a stream having an ``isatty()`` method returning ``True`` but not being compatible with ``colorama`` is used on Windows (`#249 `_). - Fix exceptions occurring in coroutine sinks never retrieved and hence causing warnings (`#227 `_). `0.4.1`_ (2020-01-19) ===================== - Deprecate the ``ansi`` parameter of ``.opt()`` in favor of ``colors`` which is a name more appropriate. - Prevent unrelated files and directories to be incorrectly collected thus causing errors during the ``retention`` process (`#195 `_, thanks `@gazpachoking `_). - Strip color markups contained in ``record["message"]`` when logging with ``.opt(ansi=True)`` instead of leaving them as is (`#198 `_). - Ignore color markups contained in ``*args`` and ``**kwargs`` when logging with ``.opt(ansi=True)``, leave them as is instead of trying to use them to colorize the message which could cause undesirable errors (`#197 `_). `0.4.0`_ (2019-12-02) ===================== - Add support for coroutine functions used as sinks and add the new ``logger.complete()`` asynchronous method to ``await`` them (`#171 `_). - Add a way to filter logs using one level per module in the form of a ``dict`` passed to the ``filter`` argument (`#148 `_). - Add type hints to annotate the public methods using a ``.pyi`` stub file (`#162 `_). - Add support for ``copy.deepcopy()`` of the ``logger`` allowing multiple independent loggers with separate set of handlers (`#72 `_). - Add the possibility to convert ``datetime`` to UTC before formatting (in logs and filenames) by adding ``"!UTC"`` at the end of the time format specifier (`#128 `_). - Add the level ``name`` as the first argument of namedtuple returned by the ``.level()`` method. - Remove ``class`` objects from the list of supported sinks and restrict usage of ``**kwargs`` in ``.add()`` to file sink only. User is in charge of instantiating sink and wrapping additional keyword arguments if needed, before passing it to the ``.add()`` method. - Rename the ``logger.configure()`` keyword argument ``patch`` to ``patcher`` so it better matches the signature of ``logger.patch()``. - Fix incompatibility with ``multiprocessing`` on Windows by entirely refactoring the internal structure of the ``logger`` so it can be inherited by child processes along with added handlers (`#108 `_). - Fix ``AttributeError`` while using a file sink on some distributions (like Alpine Linux) missing the ``os.getxattr`` and ``os.setxattr`` functions (`#158 `_, thanks `@joshgordon `_). - Fix values wrongly displayed for keyword arguments during exception formatting with ``diagnose=True`` (`#144 `_). - Fix logging messages wrongly chopped off at the end while using standard ``logging.Handler`` sinks with ``.opt(raw=True)`` (`#136 `_). - Fix potential errors during rotation if destination file exists due to large resolution clock on Windows (`#179 `_). - Fix an error using a ``filter`` function "by name" while receiving a log with ``record["name"]`` equals to ``None``. - Fix incorrect record displayed while handling errors (if ``catch=True``) occurring because of non-picklable objects (if ``enqueue=True``). - Prevent hypothetical ``ImportError`` if a Python installation is missing the built-in ``distutils`` module (`#118 `_). - Raise ``TypeError`` instead of ``ValueError`` when a ``logger`` method is called with argument of invalid type. - Raise ``ValueError`` if the built-in ``format()`` and ``filter()`` functions are respectively used as ``format`` and ``filter`` arguments of the ``add()`` method. This helps the user to understand the problem, as such a mistake can quite easily occur (`#177 `_). - Remove inheritance of some record dict attributes to ``str`` (for ``"level"``, ``"file"``, ``"thread"`` and ``"process"``). - Give a name to the worker thread used when ``enqueue=True`` (`#174 `_, thanks `@t-mart `_). `0.3.2`_ (2019-07-21) ===================== - Fix exception during import when executing Python with ``-s`` and ``-S`` flags causing ``site.USER_SITE`` to be missing (`#114 `_). `0.3.1`_ (2019-07-13) ===================== - Fix ``retention`` and ``rotation`` issues when file sink initialized with ``delay=True`` (`#113 `_). - Fix ``"sec"`` no longer recognized as a valid duration unit for file ``rotation`` and ``retention`` arguments. - Ensure stack from the caller is displayed while formatting exception of a function decorated with ``@logger.catch`` when ``backtrace=False``. - Modify datetime used to automatically rename conflicting file when rotating (it happens if file already exists because ``"{time}"`` not presents in filename) so it's based on the file creation time rather than the current time. `0.3.0`_ (2019-06-29) ===================== - Remove all dependencies previously needed by ``loguru`` (on Windows platform, it solely remains ``colorama`` and ``win32-setctime``). - Add a new ``logger.patch()`` method which can be used to modify the record dict on-the-fly before it's being sent to the handlers. - Modify behavior of sink option ``backtrace`` so it only extends the stacktrace upward, the display of variables values is now controlled with the new ``diagnose`` argument (`#49 `_). - Change behavior of ``rotation`` option in file sinks: it is now based on the file creation time rather than the current time, note that proper support may differ depending on your platform (`#58 `_). - Raise errors on unknowns color tags rather than silently ignoring them (`#57 `_). - Add the possibility to auto-close color tags by using ```` (e.g. ``message``). - Add coloration of exception traceback even if ``diagnose`` and ``backtrace`` options are ``False``. - Add a way to limit the depth of formatted exceptions traceback by setting the conventional ``sys.tracebacklimit`` variable (`#77 `_). - Add ``__repr__`` value to the ``logger`` for convenient debugging (`#84 `_). - Remove colors tags mixing directives (e.g. ````) for simplification. - Make the ``record["exception"]`` attribute unpackable as a ``(type, value, traceback)`` tuple. - Fix error happening in some rare circumstances because ``frame.f_globals`` dict did not contain ``"__name__"`` key and hence prevented Loguru to retrieve the module's name. From now, ``record["name"]`` will be equal to ``None`` in such case (`#62 `_). - Fix logging methods not being serializable with ``pickle`` and hence raising exception while being passed to some ``multiprocessing`` functions (`#102 `_). - Fix exception stack trace not colorizing source code lines on Windows. - Fix possible ``AttributeError`` while formatting exceptions within a ``celery`` task (`#52 `_). - Fix ``logger.catch`` decorator not working with generator and coroutine functions (`#75 `_). - Fix ``record["path"]`` case being normalized for no necessary reason (`#85 `_). - Fix some Windows terminal emulators (mintty) not correctly detected as supporting colors, causing ansi codes to be automatically stripped (`#104 `_). - Fix handler added with ``enqueue=True`` stopping working if exception was raised in sink although ``catch=True``. - Fix thread-safety of ``enable()`` and ``disable()`` being called during logging. - Use Tox to run tests (`#41 `_). `0.2.5`_ (2019-01-20) ===================== - Modify behavior of sink option ``backtrace=False`` so it doesn't extend traceback upward automatically (`#30 `_). - Fix import error on some platforms using Python 3.5 with limited ``localtime()`` support (`#33 `_). - Fix incorrect time formatting of locale month using ``MMM`` and ``MMMM`` tokens (`#34 `_, thanks `@nasyxx `_). - Fix race condition permitting writing on a stopped handler. `0.2.4`_ (2018-12-26) ===================== - Fix adding handler while logging which was not thread-safe (`#22 `_). `0.2.3`_ (2018-12-16) ===================== - Add support for PyPy. - Add support for Python 3.5. - Fix incompatibility with ``awscli`` by downgrading required ``colorama`` dependency version (`#12 `_). `0.2.2`_ (2018-12-12) ===================== - Deprecate ``logger.start()`` and ``logger.stop()`` methods in favor of ``logger.add()`` and ``logger.remove()`` (`#3 `_). - Fix ignored formatting while using ``logging.Handler`` sinks (`#4 `_). - Fix impossibility to set empty environment variable color on Windows (`#7 `_). `0.2.1`_ (2018-12-08) ===================== - Fix typo preventing README to be correctly displayed on PyPI. `0.2.0`_ (2018-12-08) ===================== - Remove the ``parser`` and refactor it into the ``logger.parse()`` method. - Remove the ``notifier`` and its dependencies (``pip install notifiers`` should be used instead). `0.1.0`_ (2018-12-07) ===================== - Add logger. - Add notifier. - Add parser. `0.0.1`_ (2017-09-04) ===================== Initial release. .. _Unreleased: https://github.com/delgan/loguru/compare/0.7.3...master .. _0.7.3: https://github.com/delgan/loguru/releases/tag/0.7.3 .. _0.7.2: https://github.com/delgan/loguru/releases/tag/0.7.2 .. _0.7.1: https://github.com/delgan/loguru/releases/tag/0.7.1 .. _0.7.0: https://github.com/delgan/loguru/releases/tag/0.7.0 .. _0.6.0: https://github.com/delgan/loguru/releases/tag/0.6.0 .. _0.5.3: https://github.com/delgan/loguru/releases/tag/0.5.3 .. _0.5.2: https://github.com/delgan/loguru/releases/tag/0.5.2 .. _0.5.1: https://github.com/delgan/loguru/releases/tag/0.5.1 .. _0.5.0: https://github.com/delgan/loguru/releases/tag/0.5.0 .. _0.4.1: https://github.com/delgan/loguru/releases/tag/0.4.1 .. _0.4.0: https://github.com/delgan/loguru/releases/tag/0.4.0 .. _0.3.2: https://github.com/delgan/loguru/releases/tag/0.3.2 .. _0.3.1: https://github.com/delgan/loguru/releases/tag/0.3.1 .. _0.3.0: https://github.com/delgan/loguru/releases/tag/0.3.0 .. _0.2.5: https://github.com/delgan/loguru/releases/tag/0.2.5 .. _0.2.4: https://github.com/delgan/loguru/releases/tag/0.2.4 .. _0.2.3: https://github.com/delgan/loguru/releases/tag/0.2.3 .. _0.2.2: https://github.com/delgan/loguru/releases/tag/0.2.2 .. _0.2.1: https://github.com/delgan/loguru/releases/tag/0.2.1 .. _0.2.0: https://github.com/delgan/loguru/releases/tag/0.2.0 .. _0.1.0: https://github.com/delgan/loguru/releases/tag/0.1.0 .. _0.0.1: https://github.com/delgan/loguru/releases/tag/0.0.1 loguru-0.7.3/CONTRIBUTING.rst000066400000000000000000000060031472455460700155140ustar00rootroot00000000000000Thank you for considering improving `Loguru`, any contribution is much welcome! .. _minimal reproducible example: https://stackoverflow.com/help/mcve .. _open a new issue: https://github.com/Delgan/loguru/issues/new .. _open a pull request: https://github.com/Delgan/loguru/compare .. _PEP 8: https://www.python.org/dev/peps/pep-0008/ .. _Loguru: https://github.com/Delgan/loguru Asking questions ---------------- If you have any question about `Loguru`, if you are seeking for help, or if you would like to suggest a new feature, you are encouraged to `open a new issue`_ so we can discuss it. Bringing new ideas and pointing out elements needing clarification allows to make this library always better! Reporting a bug --------------- If you encountered an unexpected behavior using `Loguru`, please `open a new issue`_ and describe the problem you have spotted. Be as specific as possible in the description of the trouble so we can easily analyse it and quickly fix it. An ideal bug report includes: * The Python version you are using * The `Loguru` version you are using (you can find it with ``print(loguru.__version__)``) * Your operating system name and version (Linux, MacOS, Windows) * Your development environment and local setup (IDE, Terminal, project context, any relevant information that could be useful) * Some `minimal reproducible example`_ Implementing changes -------------------- If you are willing to enhance `Loguru` by implementing non-trivial changes, please `open a new issue`_ first to keep a reference about why such modifications are made (and potentially avoid unneeded work). Prefer using a relatively recent Python version as some dependencies required for development may have dropped support for oldest Python versions. Then, the workflow would look as follows: 1. Fork the `Loguru`_ project from GitHub. 2. Clone the repository locally:: $ git clone git@github.com:your_name_here/loguru.git $ cd loguru 3. Activate your virtual environment:: $ python -m venv env $ source env/bin/activate 4. Install `Loguru` in development mode:: $ pip install -e ".[dev]" 5. Install pre-commit hooks that will check your commits:: $ pre-commit install --install-hooks 6. Create a new branch from ``master``:: $ git checkout master $ git branch fix_bug $ git checkout fix_bug 7. Implement the modifications wished. During the process of development, honor `PEP 8`_ as much as possible. 8. Add unit tests (don't hesitate to be exhaustive!) and ensure none are failing using:: $ tox -e tests 9. Remember to update documentation if required. 10. If your development modifies `Loguru` behavior, update the ``CHANGELOG.rst`` file with what you improved. 11. ``add`` and ``commit`` your changes, then ``push`` your local project:: $ git add . $ git commit -m 'Add succinct explanation of what changed' $ git push origin fix_bug 12. If previous step failed due to the pre-commit hooks, fix reported errors and try again. 13. Finally, `open a pull request`_ before getting it merged! loguru-0.7.3/LICENSE000066400000000000000000000020401472455460700140550ustar00rootroot00000000000000MIT License Copyright (c) 2017 Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. loguru-0.7.3/README.md000066400000000000000000000447251472455460700143470ustar00rootroot00000000000000

Loguru logo

Pypi version Python versions Documentation Build status Coverage Code quality License

Loguru logo

______________________________________________________________________ **Loguru** is a library which aims to bring enjoyable logging in Python. Did you ever feel lazy about configuring a logger and used `print()` instead?... I did, yet logging is fundamental to every application and eases the process of debugging. Using **Loguru** you have no excuse not to use logging from the start, this is as simple as `from loguru import logger`. Also, this library is intended to make Python logging less painful by adding a bunch of useful functionalities that solve caveats of the standard loggers. Using logs in your application should be an automatism, **Loguru** tries to make it both pleasant and powerful. ## Installation ``` pip install loguru ``` ## Features - [Ready to use out of the box without boilerplate](#ready-to-use-out-of-the-box-without-boilerplate) - [No Handler, no Formatter, no Filter: one function to rule them all](#no-handler-no-formatter-no-filter-one-function-to-rule-them-all) - [Easier file logging with rotation / retention / compression](#easier-file-logging-with-rotation--retention--compression) - [Modern string formatting using braces style](#modern-string-formatting-using-braces-style) - [Exceptions catching within threads or main](#exceptions-catching-within-threads-or-main) - [Pretty logging with colors](#pretty-logging-with-colors) - [Asynchronous, Thread-safe, Multiprocess-safe](#asynchronous-thread-safe-multiprocess-safe) - [Fully descriptive exceptions](#fully-descriptive-exceptions) - [Structured logging as needed](#structured-logging-as-needed) - [Lazy evaluation of expensive functions](#lazy-evaluation-of-expensive-functions) - [Customizable levels](#customizable-levels) - [Better datetime handling](#better-datetime-handling) - [Suitable for scripts and libraries](#suitable-for-scripts-and-libraries) - [Entirely compatible with standard logging](#entirely-compatible-with-standard-logging) - [Personalizable defaults through environment variables](#personalizable-defaults-through-environment-variables) - [Convenient parser](#convenient-parser) - [Exhaustive notifier](#exhaustive-notifier) - [10x faster than built-in logging](#10x-faster-than-built-in-logging) ## Take the tour ### Ready to use out of the box without boilerplate The main concept of Loguru is that **there is one and only one** [`logger`](https://loguru.readthedocs.io/en/stable/api/logger.html#loguru._logger.Logger). For convenience, it is pre-configured and outputs to `stderr` to begin with (but that's entirely configurable). ```python from loguru import logger logger.debug("That's it, beautiful and simple logging!") ``` The [`logger`](https://loguru.readthedocs.io/en/stable/api/logger.html#loguru._logger.Logger) is just an interface which dispatches log messages to configured handlers. Simple, right? ### No Handler, no Formatter, no Filter: one function to rule them all How to add a handler? How to set up logs formatting? How to filter messages? How to set level? One answer: the [`add()`](https://loguru.readthedocs.io/en/stable/api/logger.html#loguru._logger.Logger.add) function. ```python logger.add(sys.stderr, format="{time} {level} {message}", filter="my_module", level="INFO") ``` This function should be used to register [sinks](https://loguru.readthedocs.io/en/stable/api/logger.html#sink) which are responsible for managing [log messages](https://loguru.readthedocs.io/en/stable/api/logger.html#message) contextualized with a [record dict](https://loguru.readthedocs.io/en/stable/api/logger.html#record). A sink can take many forms: a simple function, a string path, a file-like object, a coroutine function or a built-in Handler. Note that you may also a previously added handler by using the identifier returned while adding it. This is particularly useful if you want to supersede the default `stderr` handler: just call [`logger.remove()`](https://loguru.readthedocs.io/en/stable/api/logger.html#loguru._logger.Logger.remove) to make a fresh start. ### Easier file logging with rotation / retention / compression If you want to send logged messages to a file, you just have to use a string path as the sink. It can be automatically timed too for convenience: ```python logger.add("file_{time}.log") ``` It is also [easily configurable](https://loguru.readthedocs.io/en/stable/api/logger.html#file) if you need rotating logger, if you want to remove older logs, or if you wish to compress your files at closure. ```python logger.add("file_1.log", rotation="500 MB") # Automatically rotate too big file logger.add("file_2.log", rotation="12:00") # New file is created each day at noon logger.add("file_3.log", rotation="1 week") # Once the file is too old, it's rotated logger.add("file_X.log", retention="10 days") # Cleanup after some time logger.add("file_Y.log", compression="zip") # Save some loved space ``` ### Modern string formatting using braces style Loguru favors the much more elegant and powerful `{}` formatting over `%`, logging functions are actually equivalent to `str.format()`. ```python logger.info("If you're using Python {}, prefer {feature} of course!", 3.6, feature="f-strings") ``` ### Exceptions catching within threads or main Have you ever seen your program crashing unexpectedly without seeing anything in the log file? Did you ever notice that exceptions occurring in threads were not logged? This can be solved using the [`catch()`](https://loguru.readthedocs.io/en/stable/api/logger.html#loguru._logger.Logger.catch) decorator / context manager which ensures that any error is correctly propagated to the [`logger`](https://loguru.readthedocs.io/en/stable/api/logger.html#loguru._logger.Logger). ```python @logger.catch def my_function(x, y, z): # An error? It's caught anyway! return 1 / (x + y + z) ``` ### Pretty logging with colors Loguru automatically adds colors to your logs if your terminal is compatible. You can define your favorite style by using [markup tags](https://loguru.readthedocs.io/en/stable/api/logger.html#color) in the sink format. ```python logger.add(sys.stdout, colorize=True, format="{time} {message}") ``` ### Asynchronous, Thread-safe, Multiprocess-safe All sinks added to the [`logger`](https://loguru.readthedocs.io/en/stable/api/logger.html#loguru._logger.Logger) are thread-safe by default. They are not multiprocess-safe, but you can `enqueue` the messages to ensure logs integrity. This same argument can also be used if you want async logging. ```python logger.add("somefile.log", enqueue=True) ``` Coroutine functions used as sinks are also supported and should be awaited with [`complete()`](https://loguru.readthedocs.io/en/stable/api/logger.html#loguru._logger.Logger.complete). ### Fully descriptive exceptions Logging exceptions that occur in your code is important to track bugs, but it's quite useless if you don't know why it failed. Loguru helps you identify problems by allowing the entire stack trace to be displayed, including values of variables (thanks [`better_exceptions`](https://github.com/Qix-/better-exceptions) for this!). The code: ```python # Caution, "diagnose=True" is the default and may leak sensitive data in prod logger.add("out.log", backtrace=True, diagnose=True) def func(a, b): return a / b def nested(c): try: func(5, c) except ZeroDivisionError: logger.exception("What?!") nested(0) ``` Would result in: ```none 2018-07-17 01:38:43.975 | ERROR | __main__:nested:10 - What?! Traceback (most recent call last): File "test.py", line 12, in nested(0) └ > File "test.py", line 8, in nested func(5, c) │ └ 0 └ File "test.py", line 4, in func return a / b │ └ 0 └ 5 ZeroDivisionError: division by zero ``` Note that this feature won't work on default Python REPL due to unavailable frame data. See also: [Security considerations when using Loguru](https://loguru.readthedocs.io/en/stable/resources/recipes.html#security-considerations-when-using-loguru). ### Structured logging as needed Want your logs to be serialized for easier parsing or to pass them around? Using the `serialize` argument, each log message will be converted to a JSON string before being sent to the configured sink. ```python logger.add(custom_sink_function, serialize=True) ``` Using [`bind()`](https://loguru.readthedocs.io/en/stable/api/logger.html#loguru._logger.Logger.bind) you can contextualize your logger messages by modifying the `extra` record attribute. ```python logger.add("file.log", format="{extra[ip]} {extra[user]} {message}") context_logger = logger.bind(ip="192.168.0.1", user="someone") context_logger.info("Contextualize your logger easily") context_logger.bind(user="someone_else").info("Inline binding of extra attribute") context_logger.info("Use kwargs to add context during formatting: {user}", user="anybody") ``` It is possible to modify a context-local state temporarily with [`contextualize()`](https://loguru.readthedocs.io/en/stable/api/logger.html#loguru._logger.Logger.contextualize): ```python with logger.contextualize(task=task_id): do_something() logger.info("End of task") ``` You can also have more fine-grained control over your logs by combining [`bind()`](https://loguru.readthedocs.io/en/stable/api/logger.html#loguru._logger.Logger.bind) and `filter`: ```python logger.add("special.log", filter=lambda record: "special" in record["extra"]) logger.debug("This message is not logged to the file") logger.bind(special=True).info("This message, though, is logged to the file!") ``` Finally, the [`patch()`](https://loguru.readthedocs.io/en/stable/api/logger.html#loguru._logger.Logger.patch) method allows dynamic values to be attached to the record dict of each new message: ```python logger.add(sys.stderr, format="{extra[utc]} {message}") logger = logger.patch(lambda record: record["extra"].update(utc=datetime.utcnow())) ``` ### Lazy evaluation of expensive functions Sometime you would like to log verbose information without performance penalty in production, you can use the [`opt()`](https://loguru.readthedocs.io/en/stable/api/logger.html#loguru._logger.Logger.opt) method to achieve this. ```python logger.opt(lazy=True).debug("If sink level <= DEBUG: {x}", x=lambda: expensive_function(2**64)) # By the way, "opt()" serves many usages logger.opt(exception=True).info("Error stacktrace added to the log message (tuple accepted too)") logger.opt(colors=True).info("Per message colors") logger.opt(record=True).info("Display values from the record (eg. {record[thread]})") logger.opt(raw=True).info("Bypass sink formatting\n") logger.opt(depth=1).info("Use parent stack context (useful within wrapped functions)") logger.opt(capture=False).info("Keyword arguments not added to {dest} dict", dest="extra") ``` ### Customizable levels Loguru comes with all standard [logging levels](https://loguru.readthedocs.io/en/stable/api/logger.html#levels) to which [`trace()`](https://loguru.readthedocs.io/en/stable/api/logger.html#loguru._logger.Logger.trace) and [`success()`](https://loguru.readthedocs.io/en/stable/api/logger.html#loguru._logger.Logger.success) are added. Do you need more? Then, just create it by using the [`level()`](https://loguru.readthedocs.io/en/stable/api/logger.html#loguru._logger.Logger.level) function. ```python new_level = logger.level("SNAKY", no=38, color="", icon="🐍") logger.log("SNAKY", "Here we go!") ``` ### Better datetime handling The standard logging is bloated with arguments like `datefmt` or `msecs`, `%(asctime)s` and `%(created)s`, naive datetimes without timezone information, not intuitive formatting, etc. Loguru [fixes it](https://loguru.readthedocs.io/en/stable/api/logger.html#time): ```python logger.add("file.log", format="{time:YYYY-MM-DD at HH:mm:ss} | {level} | {message}") ``` ### Suitable for scripts and libraries Using the logger in your scripts is easy, and you can [`configure()`](https://loguru.readthedocs.io/en/stable/api/logger.html#loguru._logger.Logger.configure) it at start. To use Loguru from inside a library, remember to never call [`add()`](https://loguru.readthedocs.io/en/stable/api/logger.html#loguru._logger.Logger.add) but use [`disable()`](https://loguru.readthedocs.io/en/stable/api/logger.html#loguru._logger.Logger.disable) instead so logging functions become no-op. If a developer wishes to see your library's logs, they can [`enable()`](https://loguru.readthedocs.io/en/stable/api/logger.html#loguru._logger.Logger.enable) it again. ```python # For scripts config = { "handlers": [ {"sink": sys.stdout, "format": "{time} - {message}"}, {"sink": "file.log", "serialize": True}, ], "extra": {"user": "someone"} } logger.configure(**config) # For libraries, should be your library's `__name__` logger.disable("my_library") logger.info("No matter added sinks, this message is not displayed") # In your application, enable the logger in the library logger.enable("my_library") logger.info("This message however is propagated to the sinks") ``` For additional convenience, you can also use the [`loguru-config`](https://github.com/erezinman/loguru-config) library to setup the `logger` directly from a configuration file. ### Entirely compatible with standard logging Wish to use built-in logging `Handler` as a Loguru sink? ```python handler = logging.handlers.SysLogHandler(address=('localhost', 514)) logger.add(handler) ``` Need to propagate Loguru messages to standard `logging`? ```python class PropagateHandler(logging.Handler): def emit(self, record: logging.LogRecord) -> None: logging.getLogger(record.name).handle(record) logger.add(PropagateHandler(), format="{message}") ``` Want to intercept standard `logging` messages toward your Loguru sinks? ```python class InterceptHandler(logging.Handler): def emit(self, record: logging.LogRecord) -> None: # Get corresponding Loguru level if it exists. level: str | int try: level = logger.level(record.levelname).name except ValueError: level = record.levelno # Find caller from where originated the logged message. frame, depth = inspect.currentframe(), 0 while frame and (depth == 0 or frame.f_code.co_filename == logging.__file__): frame = frame.f_back depth += 1 logger.opt(depth=depth, exception=record.exc_info).log(level, record.getMessage()) logging.basicConfig(handlers=[InterceptHandler()], level=0, force=True) ``` ### Personalizable defaults through environment variables Don't like the default logger formatting? Would prefer another `DEBUG` color? [No problem](https://loguru.readthedocs.io/en/stable/api/logger.html#env): ```bash # Linux / OSX export LOGURU_FORMAT="{time} | {message}" # Windows setx LOGURU_DEBUG_COLOR "" ``` ### Convenient parser It is often useful to extract specific information from generated logs, this is why Loguru provides a [`parse()`](https://loguru.readthedocs.io/en/stable/api/logger.html#loguru._logger.Logger.parse) method which helps to deal with logs and regexes. ```python pattern = r"(?P