logprise 1.0.0__py3-none-any.whl

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/__init__.py ADDED
@@ -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,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,5 @@
1
+ logprise/__init__.py,sha256=TAHLGoo4i9dcwsgPASLWqIyO5s4uy4JO_-IIxygqP5o,4762
2
+ logprise-1.0.0.dist-info/LICENSE,sha256=w-vZiM1CsZLJPlBeYYaApohrFNCkrDe8o7LSD74j_JA,1076
3
+ logprise-1.0.0.dist-info/METADATA,sha256=X_4tZoyHANb-TX4eMpdDohG4WJ1NHZetB1eH3PqZzEg,3540
4
+ logprise-1.0.0.dist-info/WHEEL,sha256=vVCvjcmxuUltf8cYhJ0sJMRDLr1XsPuxEId8YDzbyCY,88
5
+ logprise-1.0.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: poetry-core 1.4.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any