logprise 1.0.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
logprise-1.0.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Steven Van Ingelgem
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,128 @@
1
+ Metadata-Version: 2.1
2
+ Name: logprise
3
+ Version: 1.0.0
4
+ Summary: A package integrating loguru and apprise for logging and notifications
5
+ Home-page: https://github.com/svaningelgem/logprise
6
+ License: MIT
7
+ Author: Steven Van Ingelgem
8
+ Author-email: steven@vaningelgem.be
9
+ Requires-Python: >=3.10
10
+ Classifier: License :: OSI Approved :: MIT License
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Programming Language :: Python :: 3.10
13
+ Classifier: Programming Language :: Python :: 3.11
14
+ Requires-Dist: apprise
15
+ Requires-Dist: loguru
16
+ Project-URL: Repository, https://github.com/svaningelgem/logprise
17
+ Description-Content-Type: text/markdown
18
+
19
+ # Logprise
20
+
21
+ Logprise is a Python package that seamlessly integrates [loguru](https://github.com/Delgan/loguru/) and [apprise](https://github.com/caronc/apprise) to provide unified logging and notification capabilities. It allows you to automatically send notifications when specific log levels are triggered, making it perfect for monitoring applications and getting alerts when important events occur.
22
+
23
+ ## Features
24
+
25
+ - Unified logging interface that captures both standard logging and loguru logs
26
+ - Automatic notification delivery based on configurable log levels
27
+ - Batched notifications to prevent notification spam
28
+ - Flexible configuration through apprise's extensive notification service support
29
+ - Easy integration with existing Python applications
30
+
31
+ ## Installation
32
+
33
+ ```bash
34
+ pip install logprise
35
+ ```
36
+
37
+ Or if you're using Poetry:
38
+
39
+ ```bash
40
+ poetry add logprise
41
+ ```
42
+
43
+ ## Quick Start
44
+
45
+ Here's a simple example of how to use Logprise:
46
+
47
+ ```python
48
+ from logprise import logger
49
+
50
+ # Your logs will automatically trigger notifications
51
+ logger.info("This won't trigger a notification")
52
+ logger.warning("This won't trigger a notification")
53
+ logger.error("This will trigger a notification") # Default is ERROR level
54
+
55
+ # Notifications are automatically sent when your program exits
56
+ ```
57
+
58
+ ## Configuration
59
+
60
+ ### Notification Services
61
+
62
+ Logprise uses Apprise for notifications, which supports a wide range of notification services. Create an `apprise.txt` file in one of the default configuration paths:
63
+
64
+ - `~/.apprise`
65
+ - `~/.config/apprise`
66
+
67
+ Example configuration:
68
+
69
+ ```text
70
+ mailto://user:pass@gmail.com
71
+ tgram://bot_token/chat_id
72
+ slack://tokenA/tokenB/tokenC/#channel
73
+ ```
74
+
75
+ See [Apprise's configuration guide](https://github.com/caronc/apprise/wiki/config#cli) for the full list of supported services and their configuration.
76
+
77
+ ### Notification Levels
78
+
79
+ You can set the minimum log level that triggers notifications:
80
+
81
+ ```python
82
+ from logprise import appriser, logger
83
+
84
+ # Using string level names
85
+ appriser.notification_level = "WARNING" # or "DEBUG", "INFO", "ERROR", "CRITICAL"
86
+
87
+ # Using integer level numbers
88
+ appriser.notification_level = 30 # WARNING level
89
+
90
+ # Using loguru Level objects
91
+ appriser.notification_level = logger.level("ERROR")
92
+ ```
93
+
94
+ ### Manual Notification Control
95
+
96
+ While notifications are sent automatically when your program exits, you can control them manually:
97
+
98
+ ```python
99
+ from logprise import appriser
100
+
101
+ # Clear the notification buffer
102
+ appriser.buffer.clear()
103
+
104
+ # Send notifications immediately
105
+ appriser.send_notification()
106
+ ```
107
+
108
+ ## Contributing
109
+
110
+ To contribute to the project:
111
+
112
+ ```bash
113
+ # Clone the repository
114
+ git clone https://github.com/yourusername/logprise.git
115
+ cd logprise
116
+
117
+ # Install dependencies
118
+ poetry install
119
+
120
+ # Run tests
121
+ poetry run pytest
122
+ ```
123
+
124
+ Contributions are welcome! Please feel free to submit a Pull Request.
125
+
126
+ ## License
127
+
128
+ This project is licensed under the MIT License - see the LICENSE file for details.
@@ -0,0 +1,110 @@
1
+ # Logprise
2
+
3
+ Logprise is a Python package that seamlessly integrates [loguru](https://github.com/Delgan/loguru/) and [apprise](https://github.com/caronc/apprise) to provide unified logging and notification capabilities. It allows you to automatically send notifications when specific log levels are triggered, making it perfect for monitoring applications and getting alerts when important events occur.
4
+
5
+ ## Features
6
+
7
+ - Unified logging interface that captures both standard logging and loguru logs
8
+ - Automatic notification delivery based on configurable log levels
9
+ - Batched notifications to prevent notification spam
10
+ - Flexible configuration through apprise's extensive notification service support
11
+ - Easy integration with existing Python applications
12
+
13
+ ## Installation
14
+
15
+ ```bash
16
+ pip install logprise
17
+ ```
18
+
19
+ Or if you're using Poetry:
20
+
21
+ ```bash
22
+ poetry add logprise
23
+ ```
24
+
25
+ ## Quick Start
26
+
27
+ Here's a simple example of how to use Logprise:
28
+
29
+ ```python
30
+ from logprise import logger
31
+
32
+ # Your logs will automatically trigger notifications
33
+ logger.info("This won't trigger a notification")
34
+ logger.warning("This won't trigger a notification")
35
+ logger.error("This will trigger a notification") # Default is ERROR level
36
+
37
+ # Notifications are automatically sent when your program exits
38
+ ```
39
+
40
+ ## Configuration
41
+
42
+ ### Notification Services
43
+
44
+ Logprise uses Apprise for notifications, which supports a wide range of notification services. Create an `apprise.txt` file in one of the default configuration paths:
45
+
46
+ - `~/.apprise`
47
+ - `~/.config/apprise`
48
+
49
+ Example configuration:
50
+
51
+ ```text
52
+ mailto://user:pass@gmail.com
53
+ tgram://bot_token/chat_id
54
+ slack://tokenA/tokenB/tokenC/#channel
55
+ ```
56
+
57
+ See [Apprise's configuration guide](https://github.com/caronc/apprise/wiki/config#cli) for the full list of supported services and their configuration.
58
+
59
+ ### Notification Levels
60
+
61
+ You can set the minimum log level that triggers notifications:
62
+
63
+ ```python
64
+ from logprise import appriser, logger
65
+
66
+ # Using string level names
67
+ appriser.notification_level = "WARNING" # or "DEBUG", "INFO", "ERROR", "CRITICAL"
68
+
69
+ # Using integer level numbers
70
+ appriser.notification_level = 30 # WARNING level
71
+
72
+ # Using loguru Level objects
73
+ appriser.notification_level = logger.level("ERROR")
74
+ ```
75
+
76
+ ### Manual Notification Control
77
+
78
+ While notifications are sent automatically when your program exits, you can control them manually:
79
+
80
+ ```python
81
+ from logprise import appriser
82
+
83
+ # Clear the notification buffer
84
+ appriser.buffer.clear()
85
+
86
+ # Send notifications immediately
87
+ appriser.send_notification()
88
+ ```
89
+
90
+ ## Contributing
91
+
92
+ To contribute to the project:
93
+
94
+ ```bash
95
+ # Clone the repository
96
+ git clone https://github.com/yourusername/logprise.git
97
+ cd logprise
98
+
99
+ # Install dependencies
100
+ poetry install
101
+
102
+ # Run tests
103
+ poetry run pytest
104
+ ```
105
+
106
+ Contributions are welcome! Please feel free to submit a Pull Request.
107
+
108
+ ## License
109
+
110
+ This project is licensed under the MIT License - see the LICENSE file for details.
@@ -0,0 +1,124 @@
1
+ from __future__ import annotations
2
+
3
+ import atexit
4
+ import logging
5
+ from dataclasses import InitVar, dataclass, field
6
+ from pathlib import Path
7
+ from typing import ClassVar
8
+
9
+ import apprise.cli
10
+ import loguru._logger
11
+ from loguru import logger
12
+
13
+
14
+ __all__ = ["appriser", "logger"]
15
+
16
+
17
+ # Intercept standard logging calls and forward them to loguru
18
+ class InterceptHandler(logging.Handler):
19
+ LOGGING_FILENAMES: ClassVar[set[str]] = {
20
+ Path(logging.__file__).parent.resolve().absolute().as_posix().lower(),
21
+ # Path(apprise.__file__).parent.resolve().absolute().as_posix().lower(),
22
+ # Path(loguru.__file__).parent.resolve().absolute().as_posix().lower(),
23
+ }
24
+ CURRENT_FILENAME: ClassVar[str] = Path(__file__).resolve().absolute().as_posix().lower()
25
+
26
+ def _should_ignore_this_frame(self, frame: object) -> bool:
27
+ filename = Path(frame.f_code.co_filename).resolve().absolute().as_posix().lower()
28
+ if filename == self.CURRENT_FILENAME:
29
+ return True
30
+ if "jetbrains/intellij" in filename:
31
+ return True
32
+ if filename == "<string>":
33
+ return True
34
+
35
+ return any(skip_path in filename for skip_path in self.LOGGING_FILENAMES)
36
+
37
+ def emit(self, record: logging.LogRecord) -> None:
38
+ # Skip if this is a propagated record we've already handled
39
+ if hasattr(record, "_has_been_handled_by_interceptor"):
40
+ return
41
+
42
+ # Mark record as handled to prevent duplicate processing
43
+ record._has_been_handled_by_interceptor = True
44
+
45
+ # Get corresponding Loguru level if it exists
46
+ try:
47
+ level = logger.level(record.levelname).name
48
+ except ValueError:
49
+ level = record.levelno
50
+
51
+ # Find caller from where originated the logged message
52
+ frame, depth = logging.currentframe(), 0
53
+ while self._should_ignore_this_frame(frame):
54
+ frame = frame.f_back
55
+ depth += 1
56
+
57
+ # Get the actual logger name instead of 'logging'
58
+ logger_opt = logger.opt(depth=depth + 2, exception=record.exc_info)
59
+ logger_opt.log(level, record.getMessage())
60
+
61
+
62
+ # Custom Appriser class to manage notifications
63
+ @dataclass
64
+ class Appriser:
65
+ """A wrapper around Apprise to accumulate logs and send notifications."""
66
+
67
+ apprise_trigger_level: InitVar[int | str | loguru.Level] = "ERROR"
68
+
69
+ recursion_depth: int = apprise.cli.DEFAULT_RECURSION_DEPTH
70
+
71
+ apprise_obj: apprise.Apprise = field(init=False, default_factory=apprise.Apprise)
72
+ _notification_level: int = field(init=False, default=logger.level("ERROR").no)
73
+ buffer: list[loguru.Message] = field(init=False, default_factory=list)
74
+
75
+ def _load_default_config_paths(self) -> None:
76
+ config = apprise.AppriseConfig()
77
+ for p in apprise.cli.DEFAULT_CONFIG_PATHS:
78
+ if (resolved := Path(p).expanduser().resolve().absolute()).is_file():
79
+ config.add(str(resolved))
80
+ self.apprise_obj.add(config)
81
+
82
+ def _setup_interception_handler(self) -> None:
83
+ logging.basicConfig(handlers=[InterceptHandler()], level=self._notification_level, force=True)
84
+
85
+ def __post_init__(self, apprise_trigger_level: int | str | loguru.Level) -> None:
86
+ self._load_default_config_paths()
87
+ self.notification_level = apprise_trigger_level or "ERROR"
88
+ logger.add(self.accumulate_log, catch=False)
89
+ self._setup_interception_handler()
90
+
91
+ @property
92
+ def notification_level(self) -> int:
93
+ return self._notification_level
94
+
95
+ @notification_level.setter
96
+ def notification_level(self, value: int | str | loguru.Level) -> None:
97
+ """Set the minimum log level for triggering notifications."""
98
+ if isinstance(value, int):
99
+ self._notification_level = value
100
+ elif isinstance(value, str):
101
+ self._notification_level = logger.level(value).no
102
+ elif isinstance(value, loguru._logger.Level):
103
+ self._notification_level = value.no
104
+ else:
105
+ raise TypeError(f"'{value}' is {type(value)}, expecting int/str/Level")
106
+
107
+ def accumulate_log(self, message: loguru.Message) -> None:
108
+ """Accumulate logs that meet or exceed the notification level."""
109
+ if message.record["level"].no >= self.notification_level:
110
+ self.buffer.append(message)
111
+
112
+ def send_notification(self) -> None:
113
+ """Send a single notification with all accumulated logs."""
114
+ if not self.buffer:
115
+ return
116
+
117
+ # Format the buffered logs into a single message
118
+ message = "".join(self.buffer)
119
+ self.apprise_obj.notify(title="Script Notifications", body=message)
120
+ self.buffer.clear() # Clear the buffer after sending
121
+
122
+
123
+ appriser = Appriser()
124
+ atexit.register(appriser.send_notification)
@@ -0,0 +1,139 @@
1
+ [tool.poetry]
2
+ name = "logprise"
3
+ version = "1.0.0"
4
+ description = "A package integrating loguru and apprise for logging and notifications"
5
+ authors = ["Steven Van Ingelgem <steven@vaningelgem.be>"]
6
+ license = "MIT"
7
+ readme = "README.md"
8
+ repository = "https://github.com/svaningelgem/logprise"
9
+ packages = [
10
+ { include = "logprise" }
11
+ ]
12
+
13
+ [tool.poetry.dependencies]
14
+ python = ">=3.10"
15
+ loguru = "*"
16
+ apprise = "*"
17
+
18
+ [tool.poetry.group.dev.dependencies]
19
+ pytest-cov = "*"
20
+ pytest-mock = "*"
21
+ ruff = "*"
22
+
23
+ [build-system]
24
+ requires = ["poetry-core>=2.0.0,<3.0.0"]
25
+ build-backend = "poetry.core.masonry.api"
26
+
27
+ [tool.ruff.lint]
28
+ # Enable pycodestyle ('E'), pyflakes ('F'), pylint ('PL'), isort ('I'), pep8-naming ('N'),
29
+ # flake8-bugbear ('B'), flake8-comprehensions ('C4'),
30
+ # flake8-quotes ('Q'), flake8-debugger ('T10'), mccabe ('C90'),
31
+ # flake8-type-checking ('TCH'), ruff specific rules ('RUF')
32
+ # flake8-pyi ('PYI')
33
+ select = ["E", "F", "PL", "I", "N", "B", "C4", "Q", "T10", "C90", "TCH", "RUF", "UP", "ANN", "PYI"]
34
+
35
+ # Ignore specific rules
36
+ ignore = [
37
+ "PLR0913", # Too many arguments to function call
38
+ ]
39
+
40
+ # Allow autofix for all enabled rules (when `--fix`) is provided.
41
+ fixable = ["ALL"]
42
+ unfixable = []
43
+
44
+ # Allow unused variables when underscore-prefixed.
45
+ dummy-variable-rgx = "^(_+|(_+[a-zA-Z0-9_]*[a-zA-Z0-9]+?))$"
46
+
47
+ [tool.ruff]
48
+ # Exclude a variety of commonly ignored directories.
49
+ exclude = [
50
+ ".bzr",
51
+ ".direnv",
52
+ ".eggs",
53
+ ".git",
54
+ ".git-rewrite",
55
+ ".hg",
56
+ ".mypy_cache",
57
+ ".nox",
58
+ ".pants.d",
59
+ ".pytype",
60
+ ".ruff_cache",
61
+ ".svn",
62
+ ".tox",
63
+ ".venv",
64
+ "__pypackages__",
65
+ "_build",
66
+ "buck-out",
67
+ "build",
68
+ "dist",
69
+ "node_modules",
70
+ "venv",
71
+ ]
72
+
73
+ # Same as Black.
74
+ line-length = 120
75
+
76
+ fix = true
77
+ unsafe-fixes = true
78
+
79
+ # Assume Python 3.10.
80
+ target-version = "py310"
81
+
82
+ [tool.ruff.lint.per-file-ignores]
83
+ "tests/**/*" = ["ANN", "PLR2004"] # Ignore type annotations and magic numbers in tests
84
+
85
+ [tool.ruff.lint.mccabe]
86
+ # Unlike Flake8, default to a complexity level of 10.
87
+ max-complexity = 10
88
+
89
+ [tool.ruff.lint.pydocstyle]
90
+ convention = "google"
91
+
92
+ [tool.ruff.lint.isort]
93
+ known-first-party = ["minecraft_log_watcher"]
94
+ combine-as-imports = true
95
+ lines-after-imports = 2
96
+
97
+ #[tool.ruff.lint.flake8-quotes]
98
+ #docstring-quotes = "double"
99
+ #inline-quotes = "single"
100
+
101
+ [tool.ruff.lint.flake8-tidy-imports]
102
+ ban-relative-imports = "all"
103
+
104
+ [tool.ruff.lint.flake8-type-checking]
105
+ strict = true
106
+
107
+ [tool.ruff.lint.pyupgrade]
108
+ # Preserve types, even if a file imports `from __future__ import annotations`.
109
+ keep-runtime-typing = true
110
+
111
+ [tool.ruff.lint.pylint]
112
+ max-args = 8 # Maximum number of arguments to a function
113
+
114
+ [tool.ruff.format]
115
+ # Like Black, use double quotes for docstrings
116
+ quote-style = "double"
117
+ # Like Black, indent with spaces, rather than tabs
118
+ indent-style = "space"
119
+ # Like Black, respect magic trailing commas
120
+ skip-magic-trailing-comma = false
121
+ # Like Black, automatically detect the appropriate line ending
122
+ line-ending = "auto"
123
+
124
+ [tool.coverage.run]
125
+ source = ["minecraft_log_watcher"]
126
+ branch = true
127
+
128
+ [tool.coverage.report]
129
+ exclude_lines = [
130
+ "pragma: no cover",
131
+ "def __repr__",
132
+ "raise NotImplementedError",
133
+ "if TYPE_CHECKING:",
134
+ "if typing.TYPE_CHECKING:",
135
+ "if __name__ == .__main__.:",
136
+ "@abstractmethod",
137
+ "@abc.abstractmethod"
138
+ ]
139
+ show_missing = true
@@ -0,0 +1,30 @@
1
+ # -*- coding: utf-8 -*-
2
+ from setuptools import setup
3
+
4
+ packages = \
5
+ ['logprise']
6
+
7
+ package_data = \
8
+ {'': ['*']}
9
+
10
+ install_requires = \
11
+ ['apprise', 'loguru']
12
+
13
+ setup_kwargs = {
14
+ 'name': 'logprise',
15
+ 'version': '1.0.0',
16
+ 'description': 'A package integrating loguru and apprise for logging and notifications',
17
+ 'long_description': '# Logprise\n\nLogprise is a Python package that seamlessly integrates [loguru](https://github.com/Delgan/loguru/) and [apprise](https://github.com/caronc/apprise) to provide unified logging and notification capabilities. It allows you to automatically send notifications when specific log levels are triggered, making it perfect for monitoring applications and getting alerts when important events occur.\n\n## Features\n\n- Unified logging interface that captures both standard logging and loguru logs\n- Automatic notification delivery based on configurable log levels\n- Batched notifications to prevent notification spam\n- Flexible configuration through apprise\'s extensive notification service support\n- Easy integration with existing Python applications\n\n## Installation\n\n```bash\npip install logprise\n```\n\nOr if you\'re using Poetry:\n\n```bash\npoetry add logprise\n```\n\n## Quick Start\n\nHere\'s a simple example of how to use Logprise:\n\n```python\nfrom logprise import logger\n\n# Your logs will automatically trigger notifications\nlogger.info("This won\'t trigger a notification")\nlogger.warning("This won\'t trigger a notification")\nlogger.error("This will trigger a notification") # Default is ERROR level\n\n# Notifications are automatically sent when your program exits\n```\n\n## Configuration\n\n### Notification Services\n\nLogprise uses Apprise for notifications, which supports a wide range of notification services. Create an `apprise.txt` file in one of the default configuration paths:\n\n- `~/.apprise`\n- `~/.config/apprise`\n\nExample configuration:\n\n```text\nmailto://user:pass@gmail.com\ntgram://bot_token/chat_id\nslack://tokenA/tokenB/tokenC/#channel\n```\n\nSee [Apprise\'s configuration guide](https://github.com/caronc/apprise/wiki/config#cli) for the full list of supported services and their configuration.\n\n### Notification Levels\n\nYou can set the minimum log level that triggers notifications:\n\n```python\nfrom logprise import appriser, logger\n\n# Using string level names\nappriser.notification_level = "WARNING" # or "DEBUG", "INFO", "ERROR", "CRITICAL"\n\n# Using integer level numbers\nappriser.notification_level = 30 # WARNING level\n\n# Using loguru Level objects\nappriser.notification_level = logger.level("ERROR")\n```\n\n### Manual Notification Control\n\nWhile notifications are sent automatically when your program exits, you can control them manually:\n\n```python\nfrom logprise import appriser\n\n# Clear the notification buffer\nappriser.buffer.clear()\n\n# Send notifications immediately\nappriser.send_notification()\n```\n\n## Contributing\n\nTo contribute to the project:\n\n```bash\n# Clone the repository\ngit clone https://github.com/yourusername/logprise.git\ncd logprise\n\n# Install dependencies\npoetry install\n\n# Run tests\npoetry run pytest\n```\n\nContributions are welcome! Please feel free to submit a Pull Request.\n\n## License\n\nThis project is licensed under the MIT License - see the LICENSE file for details.',
18
+ 'author': 'Steven Van Ingelgem',
19
+ 'author_email': 'steven@vaningelgem.be',
20
+ 'maintainer': 'None',
21
+ 'maintainer_email': 'None',
22
+ 'url': 'https://github.com/svaningelgem/logprise',
23
+ 'packages': packages,
24
+ 'package_data': package_data,
25
+ 'install_requires': install_requires,
26
+ 'python_requires': '>=3.10',
27
+ }
28
+
29
+
30
+ setup(**setup_kwargs)