telert 0.2.1__tar.gz → 0.2.2__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.
Files changed (29) hide show
  1. {telert-0.2.1/telert.egg-info → telert-0.2.2}/PKG-INFO +103 -49
  2. {telert-0.2.1 → telert-0.2.2}/README.md +102 -48
  3. {telert-0.2.1 → telert-0.2.2}/pyproject.toml +1 -1
  4. {telert-0.2.1 → telert-0.2.2}/telert/__init__.py +1 -1
  5. {telert-0.2.1 → telert-0.2.2}/telert/monitoring/base.py +1 -1
  6. {telert-0.2.1 → telert-0.2.2}/telert/monitoring/cli.py +3 -3
  7. {telert-0.2.1 → telert-0.2.2}/telert/monitoring/cli_logs.py +1 -1
  8. {telert-0.2.1 → telert-0.2.2}/telert/monitoring/network.py +1 -1
  9. {telert-0.2.1 → telert-0.2.2}/telert/monitoring/process.py +80 -69
  10. {telert-0.2.1 → telert-0.2.2/telert.egg-info}/PKG-INFO +103 -49
  11. {telert-0.2.1 → telert-0.2.2}/telert.egg-info/SOURCES.txt +2 -4
  12. telert-0.2.1/telert/monitoring/logs.py +0 -267
  13. {telert-0.2.1 → telert-0.2.2}/LICENSE +0 -0
  14. {telert-0.2.1 → telert-0.2.2}/MANIFEST.in +0 -0
  15. {telert-0.2.1 → telert-0.2.2}/setup.cfg +0 -0
  16. {telert-0.2.1 → telert-0.2.2}/telert/api.py +0 -0
  17. {telert-0.2.1 → telert-0.2.2}/telert/cli.py +0 -0
  18. {telert-0.2.1 → telert-0.2.2}/telert/data/notification-icon.png +0 -0
  19. {telert-0.2.1 → telert-0.2.2}/telert/data/notification.mp3 +0 -0
  20. {telert-0.2.1 → telert-0.2.2}/telert/messaging.py +0 -0
  21. {telert-0.2.1 → telert-0.2.2}/telert/monitoring/__init__.py +0 -0
  22. /telert-0.2.1/telert/monitoring/fixed_logs.py → /telert-0.2.2/telert/monitoring/activity_logs.py +0 -0
  23. {telert-0.2.1 → telert-0.2.2}/telert/monitoring/debug_logs.py +0 -0
  24. {telert-0.2.1 → telert-0.2.2}/telert/monitoring/log.py +0 -0
  25. {telert-0.2.1 → telert-0.2.2}/telert.egg-info/dependency_links.txt +0 -0
  26. {telert-0.2.1 → telert-0.2.2}/telert.egg-info/entry_points.txt +0 -0
  27. {telert-0.2.1 → telert-0.2.2}/telert.egg-info/requires.txt +0 -0
  28. {telert-0.2.1 → telert-0.2.2}/telert.egg-info/top_level.txt +0 -0
  29. {telert-0.2.1 → telert-0.2.2}/telert.png +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: telert
3
- Version: 0.2.1
3
+ Version: 0.2.2
4
4
  Summary: Ultimate command monitoring & notification system: Telegram, Slack, Discord, Teams, Pushover, Email, desktop & more. Monitor Python code and CLI tasks with context managers, decorators, and webhooks.
5
5
  Author-email: Mihir Khandekar <mihirkhandekar@gmail.com>
6
6
  License-Expression: MIT
@@ -54,7 +54,7 @@ Dynamic: license-file
54
54
  <img src="https://github.com/navig-me/telert/raw/main/telert.png" alt="telert logo" width="150">
55
55
  </p>
56
56
 
57
- **Version 0.2.1**
57
+ **Version 0.2.2**
58
58
 
59
59
  [![GitHub Stars](https://img.shields.io/github/stars/navig-me/telert?style=social)](https://github.com/navig-me/telert/stargazers)
60
60
  [![PyPI version](https://img.shields.io/pypi/v/telert)](https://pypi.org/project/telert/)
@@ -87,7 +87,7 @@ find . -name "*.log" | telert "Log files found!"
87
87
  telert monitor log --name "postgres" --file "/var/log/postgresql/postgresql-15-main.log" --pattern "ERROR|FATAL"
88
88
 
89
89
  # Monitor a process and notify on high memory usage
90
- telert monitor process --name "postgres" --command "ps aux | grep postgres" --memory-threshold 2G
90
+ telert monitor process --command-pattern "ps aux | grep postgres" --memory-threshold 2G
91
91
 
92
92
  # Monitor a network endpoint and notify on failure
93
93
  telert monitor network --name "myapp-health" --host "myapp.com" --port 80 --type http --interval 60 --timeout 5 --expected-status 200 --expected-content "healthy"
@@ -155,8 +155,9 @@ For more detailed information, please refer to the [docs](https://github.com/nav
155
155
 
156
156
  ## 🚀 Installation & Quick Start
157
157
 
158
+ Install and configure in seconds:
159
+
158
160
  ```bash
159
- # Install from PyPI (works on any OS with Python 3.8+)
160
161
  pip install telert
161
162
 
162
163
  # Interactive setup wizard - easiest way to get started
@@ -164,13 +165,45 @@ telert init
164
165
 
165
166
  # Or configure a notification provider manually
166
167
  telert config desktop --app-name "My App" --set-default
168
+ ```
169
+
170
+ Use in your shell directly or wrap any command:
167
171
 
168
- # Basic usage - pipe command output
172
+ ```bash
173
+ # Pipe command output for notification
169
174
  long_running_command | telert "Command finished!"
170
175
 
171
- # Or wrap a command to capture status and timing
176
+ # Wrap a command to capture status and timing
172
177
  telert run --label "Database Backup" pg_dump -U postgres mydb > backup.sql
173
178
 
179
+ # Get notified for any command taking longer than 30 seconds
180
+ eval "$(telert hook -l 30)"
181
+ ```
182
+
183
+ Or use in your Python code:
184
+
185
+ ```python
186
+ from telert import send, telert, notify
187
+
188
+ # Simple notification
189
+ send("Script completed successfully!")
190
+
191
+ # Using the context manager
192
+ def process():
193
+ with telert("Data processing", provider="telegram"):
194
+ # Your long-running code here
195
+ process_large_dataset()
196
+
197
+ # Using the function decorator
198
+ @notify("Database backup", provider="email")
199
+ def backup_database():
200
+ # Backup code here
201
+ return "Backup completed"
202
+ ```
203
+
204
+ Or monitor processes, log files, and network endpoints:
205
+
206
+ ```bash
174
207
  # Monitor a process
175
208
  telert monitor process --name "postgres" --command "ps aux | grep postgres" --memory-threshold 2G
176
209
 
@@ -388,7 +421,7 @@ telert monitor process --name "nginx" --notify-on stop,high-cpu --provider slack
388
421
  telert monitor process --name "postgres" --cpu-threshold 80 --memory-threshold 2G --provider telegram
389
422
 
390
423
  # Monitor with custom action on state change
391
- telert monitor process --command "python worker.py" --notify-on crash --action "systemctl restart worker"
424
+ telert monitor process --command-pattern "python worker.py" --notify-on crash --action "systemctl restart worker"
392
425
 
393
426
  # List all monitored processes
394
427
  telert monitor process --list
@@ -737,6 +770,21 @@ curl -X POST https://your-deployment-url.example.com/send \
737
770
 
738
771
  For more details on deployment options and configuration, see the [telert-notifier repository](https://github.com/navig-me/telert-notifier).
739
772
 
773
+ ---
774
+ ## 🌿 Environment Variables
775
+
776
+ Telert can be configured using environment variables, which is especially useful in CI/CD pipelines or containerized environments. Key variables include:
777
+
778
+ - `TELERT_DEFAULT_PROVIDER` - Set default provider(s) to use
779
+ - Provider-specific variables for Telegram, Teams, Slack, Discord, Pushover, etc.
780
+ - Runtime variables like `TELERT_SILENT=1` for output control
781
+
782
+ Environment variables take precedence over the configuration file, making them perfect for temporary overrides.
783
+
784
+ [**See all environment variables**](https://github.com/navig-me/telert/blob/main/docs/ENVIRONMENT_VARIABLES.md)
785
+
786
+ ---
787
+
740
788
  ## 🔧 Troubleshooting
741
789
 
742
790
  ### Desktop Notifications Issues
@@ -768,49 +816,55 @@ For more details on deployment options and configuration, see the [telert-notifi
768
816
  - Install required audio players (macOS: built-in, Linux: mpg123/paplay/aplay, Windows: winsound/playsound)
769
817
  - For MP3 support on Windows: `pip install telert[audio]`
770
818
 
819
+ ### Notification Delivery Failures
820
+ - Verify your internet connection
821
+ - Check provider configuration with `telert status`
822
+ - For cloud services, verify API keys and webhook URLs
823
+ - Check rate limits for your notification provider
824
+
825
+
826
+ ### Monitoring Installation Issues & Commands
827
+
828
+ Telert’s process monitoring depends on the `psutil` library. If you encounter errors related to psutil (such as ImportError, build failures, or missing wheels), follow these platform-specific tips:
829
+
830
+ **Apple Silicon (M1/M2):**
831
+ - Try installing psutil using the native ARM64 architecture:
832
+ ```bash
833
+ arch -arm64 pip install --no-cache-dir psutil
834
+ ```
835
+ - For Intel compatibility (Rosetta):
836
+ ```bash
837
+ arch -x86_64 pip install --no-cache-dir psutil
838
+ ```
839
+ - If you see compilation errors, ensure you have Xcode Command Line Tools installed:
840
+ ```bash
841
+ xcode-select --install
842
+ ```
843
+
844
+ **Linux:**
845
+ - Make sure you have Python development headers and a C compiler installed:
846
+ ```bash
847
+ sudo apt-get install python3-dev gcc
848
+ pip install --upgrade --force-reinstall psutil
849
+ ```
850
+
851
+ **Windows:**
852
+ - You may need to install Visual C++ Build Tools from:
853
+ https://visualstudio.microsoft.com/visual-cpp-build-tools/
854
+ - Then try:
855
+ ```bash
856
+ pip install --upgrade --force-reinstall psutil
857
+ ```
858
+
859
+ **General:**
860
+ - If you still have issues, try upgrading pip and setuptools:
861
+ ```bash
862
+ pip install --upgrade pip setuptools wheel
863
+ ```
864
+ - For more details, see the error message for platform-specific instructions.
865
+
866
+ > **Note:** psutil is required for all process monitoring features in Telert. If import fails, you’ll see a detailed error with platform-specific help.
771
867
 
772
- ---
773
- ## 🌿 Environment Variables
774
-
775
- Telert can be configured using environment variables, which is especially useful in CI/CD pipelines or containerized environments. Key variables include:
776
-
777
- - `TELERT_DEFAULT_PROVIDER` - Set default provider(s) to use
778
- - Provider-specific variables for Telegram, Teams, Slack, Discord, Pushover, etc.
779
- - Runtime variables like `TELERT_SILENT=1` for output control
780
-
781
- Environment variables take precedence over the configuration file, making them perfect for temporary overrides.
782
-
783
- [**See all environment variables**](https://github.com/navig-me/telert/blob/main/docs/ENVIRONMENT_VARIABLES.md)
784
-
785
- ---
786
-
787
- ## 🔍 Troubleshooting
788
-
789
- ### Common Issues and Solutions
790
-
791
- #### Notification Delivery Failures
792
- - **Symptom**: Notifications not being received
793
- - Verify your internet connection
794
- - Check provider configuration with `telert status`
795
- - For cloud services, verify API keys and webhook URLs
796
- - Check rate limits for your notification provider
797
-
798
- #### Audio Notifications Not Working
799
- - **Symptom**: No sound when using audio notifications
800
- - Ensure audio package dependencies are installed: `pip install 'telert[audio]'`
801
- - Check system volume and audio output device
802
- - On Linux, ensure `libasound2` and `libasound2-dev` are installed
803
-
804
- #### Apple Silicon (M1/M2) Installation
805
- - **Symptom**: Installation fails on Apple Silicon Macs
806
- - For Apple Silicon (M-series) users, try:
807
- ```bash
808
- # Native ARM64 installation (recommended)
809
- arch -arm64 pip install --no-cache-dir telert
810
-
811
- # Or for Intel compatibility
812
- arch -x86_64 pip install --no-cache-dir telert
813
- ```
814
868
 
815
869
  ---
816
870
  ## 📝 Message Formatting
@@ -6,7 +6,7 @@
6
6
  <img src="https://github.com/navig-me/telert/raw/main/telert.png" alt="telert logo" width="150">
7
7
  </p>
8
8
 
9
- **Version 0.2.1**
9
+ **Version 0.2.2**
10
10
 
11
11
  [![GitHub Stars](https://img.shields.io/github/stars/navig-me/telert?style=social)](https://github.com/navig-me/telert/stargazers)
12
12
  [![PyPI version](https://img.shields.io/pypi/v/telert)](https://pypi.org/project/telert/)
@@ -39,7 +39,7 @@ find . -name "*.log" | telert "Log files found!"
39
39
  telert monitor log --name "postgres" --file "/var/log/postgresql/postgresql-15-main.log" --pattern "ERROR|FATAL"
40
40
 
41
41
  # Monitor a process and notify on high memory usage
42
- telert monitor process --name "postgres" --command "ps aux | grep postgres" --memory-threshold 2G
42
+ telert monitor process --command-pattern "ps aux | grep postgres" --memory-threshold 2G
43
43
 
44
44
  # Monitor a network endpoint and notify on failure
45
45
  telert monitor network --name "myapp-health" --host "myapp.com" --port 80 --type http --interval 60 --timeout 5 --expected-status 200 --expected-content "healthy"
@@ -107,8 +107,9 @@ For more detailed information, please refer to the [docs](https://github.com/nav
107
107
 
108
108
  ## 🚀 Installation & Quick Start
109
109
 
110
+ Install and configure in seconds:
111
+
110
112
  ```bash
111
- # Install from PyPI (works on any OS with Python 3.8+)
112
113
  pip install telert
113
114
 
114
115
  # Interactive setup wizard - easiest way to get started
@@ -116,13 +117,45 @@ telert init
116
117
 
117
118
  # Or configure a notification provider manually
118
119
  telert config desktop --app-name "My App" --set-default
120
+ ```
121
+
122
+ Use in your shell directly or wrap any command:
119
123
 
120
- # Basic usage - pipe command output
124
+ ```bash
125
+ # Pipe command output for notification
121
126
  long_running_command | telert "Command finished!"
122
127
 
123
- # Or wrap a command to capture status and timing
128
+ # Wrap a command to capture status and timing
124
129
  telert run --label "Database Backup" pg_dump -U postgres mydb > backup.sql
125
130
 
131
+ # Get notified for any command taking longer than 30 seconds
132
+ eval "$(telert hook -l 30)"
133
+ ```
134
+
135
+ Or use in your Python code:
136
+
137
+ ```python
138
+ from telert import send, telert, notify
139
+
140
+ # Simple notification
141
+ send("Script completed successfully!")
142
+
143
+ # Using the context manager
144
+ def process():
145
+ with telert("Data processing", provider="telegram"):
146
+ # Your long-running code here
147
+ process_large_dataset()
148
+
149
+ # Using the function decorator
150
+ @notify("Database backup", provider="email")
151
+ def backup_database():
152
+ # Backup code here
153
+ return "Backup completed"
154
+ ```
155
+
156
+ Or monitor processes, log files, and network endpoints:
157
+
158
+ ```bash
126
159
  # Monitor a process
127
160
  telert monitor process --name "postgres" --command "ps aux | grep postgres" --memory-threshold 2G
128
161
 
@@ -340,7 +373,7 @@ telert monitor process --name "nginx" --notify-on stop,high-cpu --provider slack
340
373
  telert monitor process --name "postgres" --cpu-threshold 80 --memory-threshold 2G --provider telegram
341
374
 
342
375
  # Monitor with custom action on state change
343
- telert monitor process --command "python worker.py" --notify-on crash --action "systemctl restart worker"
376
+ telert monitor process --command-pattern "python worker.py" --notify-on crash --action "systemctl restart worker"
344
377
 
345
378
  # List all monitored processes
346
379
  telert monitor process --list
@@ -689,6 +722,21 @@ curl -X POST https://your-deployment-url.example.com/send \
689
722
 
690
723
  For more details on deployment options and configuration, see the [telert-notifier repository](https://github.com/navig-me/telert-notifier).
691
724
 
725
+ ---
726
+ ## 🌿 Environment Variables
727
+
728
+ Telert can be configured using environment variables, which is especially useful in CI/CD pipelines or containerized environments. Key variables include:
729
+
730
+ - `TELERT_DEFAULT_PROVIDER` - Set default provider(s) to use
731
+ - Provider-specific variables for Telegram, Teams, Slack, Discord, Pushover, etc.
732
+ - Runtime variables like `TELERT_SILENT=1` for output control
733
+
734
+ Environment variables take precedence over the configuration file, making them perfect for temporary overrides.
735
+
736
+ [**See all environment variables**](https://github.com/navig-me/telert/blob/main/docs/ENVIRONMENT_VARIABLES.md)
737
+
738
+ ---
739
+
692
740
  ## 🔧 Troubleshooting
693
741
 
694
742
  ### Desktop Notifications Issues
@@ -720,49 +768,55 @@ For more details on deployment options and configuration, see the [telert-notifi
720
768
  - Install required audio players (macOS: built-in, Linux: mpg123/paplay/aplay, Windows: winsound/playsound)
721
769
  - For MP3 support on Windows: `pip install telert[audio]`
722
770
 
771
+ ### Notification Delivery Failures
772
+ - Verify your internet connection
773
+ - Check provider configuration with `telert status`
774
+ - For cloud services, verify API keys and webhook URLs
775
+ - Check rate limits for your notification provider
776
+
777
+
778
+ ### Monitoring Installation Issues & Commands
779
+
780
+ Telert’s process monitoring depends on the `psutil` library. If you encounter errors related to psutil (such as ImportError, build failures, or missing wheels), follow these platform-specific tips:
781
+
782
+ **Apple Silicon (M1/M2):**
783
+ - Try installing psutil using the native ARM64 architecture:
784
+ ```bash
785
+ arch -arm64 pip install --no-cache-dir psutil
786
+ ```
787
+ - For Intel compatibility (Rosetta):
788
+ ```bash
789
+ arch -x86_64 pip install --no-cache-dir psutil
790
+ ```
791
+ - If you see compilation errors, ensure you have Xcode Command Line Tools installed:
792
+ ```bash
793
+ xcode-select --install
794
+ ```
795
+
796
+ **Linux:**
797
+ - Make sure you have Python development headers and a C compiler installed:
798
+ ```bash
799
+ sudo apt-get install python3-dev gcc
800
+ pip install --upgrade --force-reinstall psutil
801
+ ```
802
+
803
+ **Windows:**
804
+ - You may need to install Visual C++ Build Tools from:
805
+ https://visualstudio.microsoft.com/visual-cpp-build-tools/
806
+ - Then try:
807
+ ```bash
808
+ pip install --upgrade --force-reinstall psutil
809
+ ```
810
+
811
+ **General:**
812
+ - If you still have issues, try upgrading pip and setuptools:
813
+ ```bash
814
+ pip install --upgrade pip setuptools wheel
815
+ ```
816
+ - For more details, see the error message for platform-specific instructions.
817
+
818
+ > **Note:** psutil is required for all process monitoring features in Telert. If import fails, you’ll see a detailed error with platform-specific help.
723
819
 
724
- ---
725
- ## 🌿 Environment Variables
726
-
727
- Telert can be configured using environment variables, which is especially useful in CI/CD pipelines or containerized environments. Key variables include:
728
-
729
- - `TELERT_DEFAULT_PROVIDER` - Set default provider(s) to use
730
- - Provider-specific variables for Telegram, Teams, Slack, Discord, Pushover, etc.
731
- - Runtime variables like `TELERT_SILENT=1` for output control
732
-
733
- Environment variables take precedence over the configuration file, making them perfect for temporary overrides.
734
-
735
- [**See all environment variables**](https://github.com/navig-me/telert/blob/main/docs/ENVIRONMENT_VARIABLES.md)
736
-
737
- ---
738
-
739
- ## 🔍 Troubleshooting
740
-
741
- ### Common Issues and Solutions
742
-
743
- #### Notification Delivery Failures
744
- - **Symptom**: Notifications not being received
745
- - Verify your internet connection
746
- - Check provider configuration with `telert status`
747
- - For cloud services, verify API keys and webhook URLs
748
- - Check rate limits for your notification provider
749
-
750
- #### Audio Notifications Not Working
751
- - **Symptom**: No sound when using audio notifications
752
- - Ensure audio package dependencies are installed: `pip install 'telert[audio]'`
753
- - Check system volume and audio output device
754
- - On Linux, ensure `libasound2` and `libasound2-dev` are installed
755
-
756
- #### Apple Silicon (M1/M2) Installation
757
- - **Symptom**: Installation fails on Apple Silicon Macs
758
- - For Apple Silicon (M-series) users, try:
759
- ```bash
760
- # Native ARM64 installation (recommended)
761
- arch -arm64 pip install --no-cache-dir telert
762
-
763
- # Or for Intel compatibility
764
- arch -x86_64 pip install --no-cache-dir telert
765
- ```
766
820
 
767
821
  ---
768
822
  ## 📝 Message Formatting
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "telert"
3
- version = "0.2.1"
3
+ version = "0.2.2"
4
4
  description = "Ultimate command monitoring & notification system: Telegram, Slack, Discord, Teams, Pushover, Email, desktop & more. Monitor Python code and CLI tasks with context managers, decorators, and webhooks."
5
5
  authors = [{name = "Mihir Khandekar", email = "mihirkhandekar@gmail.com"}]
6
6
  license = "MIT"
@@ -19,7 +19,7 @@ __all__ = [
19
19
  "set_default_providers",
20
20
  "list_providers",
21
21
  ]
22
- __version__ = "0.2.1"
22
+ __version__ = "0.2.2"
23
23
 
24
24
  from telert.api import (
25
25
  configure,
@@ -10,7 +10,7 @@ from datetime import datetime
10
10
  from typing import Any, Dict, List, Optional, Union, TypeVar, Generic
11
11
 
12
12
  from telert.messaging import Provider, send_message
13
- from telert.monitoring.fixed_logs import MonitorLogger, LogLevel
13
+ from telert.monitoring.activity_logs import MonitorLogger, LogLevel
14
14
 
15
15
  # Type definitions
16
16
  MonitorID = str
@@ -53,7 +53,7 @@ def setup_process_monitor_cli(subparsers):
53
53
  "--name", help="process name to monitor (can be a regular expression)"
54
54
  )
55
55
  process_group.add_argument(
56
- "--command", help="command pattern to match (can be a regular expression)"
56
+ "--command-pattern", dest="command_pattern", help="command pattern to match (can be a regular expression)"
57
57
  )
58
58
  process_group.add_argument(
59
59
  "--pid", type=int, help="specific process ID to monitor"
@@ -303,7 +303,7 @@ def handle_process_monitor(args):
303
303
  return
304
304
 
305
305
  # Start a new monitor
306
- if not (args.name or args.command or args.pid):
306
+ if not (args.name or args.command_pattern or args.pid):
307
307
  print("❌ You must specify at least one of --name, --command, or --pid.")
308
308
  return
309
309
 
@@ -324,7 +324,7 @@ def handle_process_monitor(args):
324
324
  monitor_id = monitor_process(
325
325
  name=args.monitor_name,
326
326
  process_name=args.name,
327
- command=args.command,
327
+ command=args.command_pattern,
328
328
  pid=args.pid,
329
329
  notify_on=notify_on,
330
330
  cpu_threshold=args.cpu_threshold,
@@ -4,7 +4,7 @@ import json
4
4
  from datetime import datetime
5
5
  from typing import Dict
6
6
 
7
- from telert.monitoring.fixed_logs import MonitorLogger, LogLevel
7
+ from telert.monitoring.activity_logs import MonitorLogger, LogLevel
8
8
 
9
9
 
10
10
  def format_log_entry(log_entry: Dict) -> str:
@@ -24,7 +24,7 @@ from telert.monitoring.base import (
24
24
  MonitorStatus,
25
25
  MonitorRegistry
26
26
  )
27
- from telert.monitoring.fixed_logs import LogLevel
27
+ from telert.monitoring.activity_logs import LogLevel
28
28
  from telert.monitoring.debug_logs import debug_log, debug_inspect
29
29
 
30
30
 
@@ -1,21 +1,34 @@
1
1
  """Process monitoring for telert."""
2
2
 
3
- import os
3
+ import json
4
4
  import re
5
5
  import subprocess
6
6
  import threading
7
7
  import time
8
- from typing import Any, Callable, Dict, List, Optional, Union, Set
8
+ import atexit
9
+ from typing import Any, Dict, List, Optional, Union # Callable, Set removed
9
10
 
11
+ # Local application imports
12
+ from telert.messaging import Provider
13
+ from telert.monitoring.base import (
14
+ Monitor,
15
+ MonitorID,
16
+ MonitorStatus,
17
+ MonitorType,
18
+ MonitorRegistry
19
+ )
20
+ from telert.monitoring.activity_logs import LogLevel # LogLevel import from correct module
21
+
22
+ # Helper function for psutil import error
10
23
  def _get_platform_help():
11
- import platform
24
+ import platform # Keep platform import local to this helper
12
25
  system = platform.system().lower()
13
26
  arch = platform.machine().lower()
14
-
27
+
15
28
  help_msg = []
16
29
  help_msg.append("\nInstallation instructions:")
17
30
  help_msg.append(f"- System: {system}, Architecture: {arch}")
18
-
31
+
19
32
  if system == 'darwin' and 'arm' in arch: # Apple Silicon
20
33
  help_msg.append("\nFor Apple Silicon (M-series) users, try:")
21
34
  help_msg.append(" arch -arm64 pip install --no-cache-dir psutil")
@@ -24,11 +37,12 @@ def _get_platform_help():
24
37
  elif system == 'windows':
25
38
  help_msg.append("\nOn Windows, you might need to install Visual C++ Build Tools:")
26
39
  help_msg.append(" https://visualstudio.microsoft.com/visual-cpp-build-tools/")
27
-
40
+
28
41
  help_msg.append("\nFor other platforms, try:")
29
42
  help_msg.append(" pip install --upgrade --force-reinstall psutil")
30
43
  return "\n".join(help_msg)
31
44
 
45
+ # psutil import with detailed error handling
32
46
  try:
33
47
  import psutil
34
48
  except (ImportError, OSError) as e:
@@ -39,16 +53,6 @@ except (ImportError, OSError) as e:
39
53
  )
40
54
  raise ImportError(error_msg) from e
41
55
 
42
- from telert.messaging import Provider
43
- from telert.monitoring.base import (
44
- Monitor,
45
- MonitorID,
46
- MonitorType,
47
- MonitorStatus,
48
- MonitorRegistry
49
- )
50
- from telert.monitoring.fixed_logs import LogLevel
51
-
52
56
  # Type aliases
53
57
  ResourceThreshold = Union[int, float, str]
54
58
  NotifyEvent = str
@@ -257,77 +261,89 @@ class ProcessMonitor(Monitor):
257
261
  """Check if process state changed and generate notification messages."""
258
262
  if self._first_check:
259
263
  self._first_check = False
260
- # Don't send notifications on first check
261
- self.log(LogLevel.INFO, "First process check completed, establishing baseline")
264
+ self.log(LogLevel.INFO, "First process check completed, establishing baseline.")
262
265
  return []
263
266
 
264
267
  notifications = []
265
268
 
266
- # Check for stopped processes
267
- for pid in old_status:
268
- if pid not in new_status or not new_status[pid]["running"]:
269
- if "stop" in self.notify_on:
270
- process_name = old_status[pid].get("name", f"PID {pid}")
271
- msg = f"Process stopped: {process_name}"
269
+ # Check for stopped or crashed processes
270
+ for pid, last_info in old_status.items():
271
+ if pid not in new_status or not new_status[pid].get("running"):
272
+ event_type = "stopped"
273
+
274
+ if event_type in self.notify_on or ("stop" in self.notify_on and event_type == "stopped") or ("crash" in self.notify_on and event_type == "crashed"):
275
+ process_name = last_info.get("name", f"PID {pid}")
276
+ msg = f"Process {event_type}: {process_name} (PID {pid})"
272
277
  notifications.append(msg)
273
- self.log(LogLevel.FAILURE, msg, {"pid": pid, "process_name": process_name})
274
-
275
- # Run action if configured
278
+ self.log(LogLevel.FAILURE, msg, {"pid": pid, "process_name": process_name, "event": event_type})
276
279
  if self.action:
277
- self.log(LogLevel.INFO, f"Running action command: {self.action}")
280
+ self.log(LogLevel.INFO, f"Running action for {event_type} event on {process_name}: {self.action}")
278
281
  self._run_action()
279
282
 
280
- # Check for new processes
281
- for pid in new_status:
282
- if pid not in old_status and "start" in self.notify_on:
283
- process_name = new_status[pid].get("name", f"PID {pid}")
284
- msg = f"Process started: {process_name}"
285
- notifications.append(msg)
286
- self.log(LogLevel.SUCCESS, msg, {"pid": pid, "process_name": process_name})
287
-
288
- # Check for resource thresholds
289
- for pid, status in new_status.items():
290
- if status["running"]:
291
- # Check CPU threshold
292
- if status["high_cpu"] and "high-cpu" in self.notify_on:
293
- process_name = status.get("name", f"PID {pid}")
294
- cpu = status["cpu_percent"]
295
- msg = f"High CPU usage: {process_name} is using {cpu:.1f}% CPU"
283
+ # Check for newly started processes
284
+ for pid, current_info in new_status.items():
285
+ if current_info.get("running") and pid not in old_status: # Process is running and wasn't in old_status
286
+ if "start" in self.notify_on:
287
+ process_name = current_info.get("name", f"PID {pid}")
288
+ msg = f"Process started: {process_name} (PID {pid})"
296
289
  notifications.append(msg)
297
- self.log(LogLevel.WARNING, msg, {"pid": pid, "process_name": process_name, "cpu_percent": cpu})
290
+ self.log(LogLevel.SUCCESS, msg, {"pid": pid, "process_name": process_name, "event": "start"})
291
+ if self.action:
292
+ self.log(LogLevel.INFO, f"Running action for start event on {process_name}: {self.action}")
293
+ self._run_action()
294
+
295
+ # Check for resource threshold violations on currently running processes
296
+ for pid, current_proc_status in new_status.items():
297
+ if current_proc_status.get("running"):
298
+ process_name = current_proc_status.get("name", f"PID {pid}")
299
+
300
+ # Check CPU threshold
301
+ if current_proc_status.get("high_cpu") and "high-cpu" in self.notify_on:
302
+ if not old_status.get(pid, {}).get("high_cpu"): # Notify only on transition into high CPU state
303
+ cpu_percent = current_proc_status.get("cpu_percent", 0.0)
304
+ msg = f"High CPU usage: {process_name} (PID {pid}) is at {cpu_percent:.1f}%"
305
+ notifications.append(msg)
306
+ self.log(LogLevel.WARNING, msg, {"pid": pid, "process_name": process_name, "cpu_percent": cpu_percent, "event": "high-cpu"})
307
+ if self.action:
308
+ self.log(LogLevel.INFO, f"Running action for high-cpu event on {process_name}: {self.action}")
309
+ self._run_action()
298
310
 
299
311
  # Check memory threshold
300
- if status["high_memory"] and "high-memory" in self.notify_on:
301
- process_name = status.get("name", f"PID {pid}")
302
- memory_mb = status["memory_bytes"] / (1024 * 1024)
303
- msg = f"High memory usage: {process_name} is using {memory_mb:.1f} MB"
304
- notifications.append(msg)
305
- self.log(LogLevel.WARNING, msg, {"pid": pid, "process_name": process_name, "memory_bytes": status["memory_bytes"]})
306
-
312
+ if current_proc_status.get("high_memory") and "high-memory" in self.notify_on:
313
+ if not old_status.get(pid, {}).get("high_memory"): # Notify only on transition into high memory state
314
+ memory_bytes = current_proc_status.get("memory_bytes", 0)
315
+ memory_mb = memory_bytes / (1024 * 1024)
316
+ msg = f"High memory usage: {process_name} (PID {pid}) is using {memory_mb:.1f}MB"
317
+ notifications.append(msg)
318
+ self.log(LogLevel.WARNING, msg, {"pid": pid, "process_name": process_name, "memory_bytes": memory_bytes, "event": "high-memory"})
319
+ if self.action:
320
+ self.log(LogLevel.INFO, f"Running action for high-memory event on {process_name}: {self.action}")
321
+ self._run_action()
307
322
  return notifications
308
-
323
+
309
324
  def _monitor_loop(self) -> None:
310
325
  """Main monitoring loop that runs in a separate thread."""
311
326
  while self._should_run:
312
327
  try:
313
- # Find matching processes
314
328
  processes = self._find_matching_processes()
315
329
 
316
- # Check each process and build status dictionary
330
+ # Build new status dictionary
317
331
  new_status = {}
318
332
  for proc in processes:
319
333
  try:
320
- # Get basic process info
334
+ # Get process information
321
335
  proc_info = {
322
336
  "pid": proc.pid,
323
337
  "name": proc.name(),
324
- "running": True,
338
+ "cmdline": proc.cmdline(),
339
+ "running": proc.is_running(),
325
340
  }
326
341
 
327
- # Add resource usage info
328
- resource_info = self._check_process_resources(proc)
329
- proc_info.update(resource_info)
342
+ # Add resource information
343
+ resources = self._check_process_resources(proc)
344
+ proc_info.update(resources)
330
345
 
346
+ # Store in new status
331
347
  new_status[proc.pid] = proc_info
332
348
  except (psutil.NoSuchProcess, psutil.AccessDenied):
333
349
  # Process disappeared or we don't have access
@@ -357,23 +373,20 @@ class ProcessMonitor(Monitor):
357
373
 
358
374
  # Clear last status to avoid sending repeated notifications
359
375
  self._last_status = {}
360
-
376
+
361
377
  except Exception as e:
362
378
  # Log the exception but keep the monitor running
363
- print(f"Error in process monitor: {e}")
379
+ self.log(LogLevel.ERROR, f"Error in process monitor: {e}", exc_info=True)
364
380
 
365
381
  # Sleep until next check
366
382
  time.sleep(self.check_interval)
367
-
383
+
368
384
  def start(self) -> None:
369
385
  """Start the process monitor."""
370
386
  if self._monitor_thread and self._monitor_thread.is_alive():
371
- # Already running
372
- self.log(LogLevel.INFO, "Process monitor already running")
387
+ self.log(LogLevel.INFO, f"Process monitor {self.monitor_id} already running.")
373
388
  return
374
389
 
375
- self.log(LogLevel.INFO, f"Starting process monitor {self.monitor_id}")
376
-
377
390
  self._should_run = True
378
391
  self._first_check = True
379
392
  self._last_status = {}
@@ -573,8 +586,6 @@ def stop_process_monitor(monitor_id: MonitorID) -> bool:
573
586
 
574
587
 
575
588
  # Make sure to initialize properly
576
- import atexit
577
- import json
578
589
 
579
590
  def _cleanup_monitors():
580
591
  """Stop all monitors on exit."""
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: telert
3
- Version: 0.2.1
3
+ Version: 0.2.2
4
4
  Summary: Ultimate command monitoring & notification system: Telegram, Slack, Discord, Teams, Pushover, Email, desktop & more. Monitor Python code and CLI tasks with context managers, decorators, and webhooks.
5
5
  Author-email: Mihir Khandekar <mihirkhandekar@gmail.com>
6
6
  License-Expression: MIT
@@ -54,7 +54,7 @@ Dynamic: license-file
54
54
  <img src="https://github.com/navig-me/telert/raw/main/telert.png" alt="telert logo" width="150">
55
55
  </p>
56
56
 
57
- **Version 0.2.1**
57
+ **Version 0.2.2**
58
58
 
59
59
  [![GitHub Stars](https://img.shields.io/github/stars/navig-me/telert?style=social)](https://github.com/navig-me/telert/stargazers)
60
60
  [![PyPI version](https://img.shields.io/pypi/v/telert)](https://pypi.org/project/telert/)
@@ -87,7 +87,7 @@ find . -name "*.log" | telert "Log files found!"
87
87
  telert monitor log --name "postgres" --file "/var/log/postgresql/postgresql-15-main.log" --pattern "ERROR|FATAL"
88
88
 
89
89
  # Monitor a process and notify on high memory usage
90
- telert monitor process --name "postgres" --command "ps aux | grep postgres" --memory-threshold 2G
90
+ telert monitor process --command-pattern "ps aux | grep postgres" --memory-threshold 2G
91
91
 
92
92
  # Monitor a network endpoint and notify on failure
93
93
  telert monitor network --name "myapp-health" --host "myapp.com" --port 80 --type http --interval 60 --timeout 5 --expected-status 200 --expected-content "healthy"
@@ -155,8 +155,9 @@ For more detailed information, please refer to the [docs](https://github.com/nav
155
155
 
156
156
  ## 🚀 Installation & Quick Start
157
157
 
158
+ Install and configure in seconds:
159
+
158
160
  ```bash
159
- # Install from PyPI (works on any OS with Python 3.8+)
160
161
  pip install telert
161
162
 
162
163
  # Interactive setup wizard - easiest way to get started
@@ -164,13 +165,45 @@ telert init
164
165
 
165
166
  # Or configure a notification provider manually
166
167
  telert config desktop --app-name "My App" --set-default
168
+ ```
169
+
170
+ Use in your shell directly or wrap any command:
167
171
 
168
- # Basic usage - pipe command output
172
+ ```bash
173
+ # Pipe command output for notification
169
174
  long_running_command | telert "Command finished!"
170
175
 
171
- # Or wrap a command to capture status and timing
176
+ # Wrap a command to capture status and timing
172
177
  telert run --label "Database Backup" pg_dump -U postgres mydb > backup.sql
173
178
 
179
+ # Get notified for any command taking longer than 30 seconds
180
+ eval "$(telert hook -l 30)"
181
+ ```
182
+
183
+ Or use in your Python code:
184
+
185
+ ```python
186
+ from telert import send, telert, notify
187
+
188
+ # Simple notification
189
+ send("Script completed successfully!")
190
+
191
+ # Using the context manager
192
+ def process():
193
+ with telert("Data processing", provider="telegram"):
194
+ # Your long-running code here
195
+ process_large_dataset()
196
+
197
+ # Using the function decorator
198
+ @notify("Database backup", provider="email")
199
+ def backup_database():
200
+ # Backup code here
201
+ return "Backup completed"
202
+ ```
203
+
204
+ Or monitor processes, log files, and network endpoints:
205
+
206
+ ```bash
174
207
  # Monitor a process
175
208
  telert monitor process --name "postgres" --command "ps aux | grep postgres" --memory-threshold 2G
176
209
 
@@ -388,7 +421,7 @@ telert monitor process --name "nginx" --notify-on stop,high-cpu --provider slack
388
421
  telert monitor process --name "postgres" --cpu-threshold 80 --memory-threshold 2G --provider telegram
389
422
 
390
423
  # Monitor with custom action on state change
391
- telert monitor process --command "python worker.py" --notify-on crash --action "systemctl restart worker"
424
+ telert monitor process --command-pattern "python worker.py" --notify-on crash --action "systemctl restart worker"
392
425
 
393
426
  # List all monitored processes
394
427
  telert monitor process --list
@@ -737,6 +770,21 @@ curl -X POST https://your-deployment-url.example.com/send \
737
770
 
738
771
  For more details on deployment options and configuration, see the [telert-notifier repository](https://github.com/navig-me/telert-notifier).
739
772
 
773
+ ---
774
+ ## 🌿 Environment Variables
775
+
776
+ Telert can be configured using environment variables, which is especially useful in CI/CD pipelines or containerized environments. Key variables include:
777
+
778
+ - `TELERT_DEFAULT_PROVIDER` - Set default provider(s) to use
779
+ - Provider-specific variables for Telegram, Teams, Slack, Discord, Pushover, etc.
780
+ - Runtime variables like `TELERT_SILENT=1` for output control
781
+
782
+ Environment variables take precedence over the configuration file, making them perfect for temporary overrides.
783
+
784
+ [**See all environment variables**](https://github.com/navig-me/telert/blob/main/docs/ENVIRONMENT_VARIABLES.md)
785
+
786
+ ---
787
+
740
788
  ## 🔧 Troubleshooting
741
789
 
742
790
  ### Desktop Notifications Issues
@@ -768,49 +816,55 @@ For more details on deployment options and configuration, see the [telert-notifi
768
816
  - Install required audio players (macOS: built-in, Linux: mpg123/paplay/aplay, Windows: winsound/playsound)
769
817
  - For MP3 support on Windows: `pip install telert[audio]`
770
818
 
819
+ ### Notification Delivery Failures
820
+ - Verify your internet connection
821
+ - Check provider configuration with `telert status`
822
+ - For cloud services, verify API keys and webhook URLs
823
+ - Check rate limits for your notification provider
824
+
825
+
826
+ ### Monitoring Installation Issues & Commands
827
+
828
+ Telert’s process monitoring depends on the `psutil` library. If you encounter errors related to psutil (such as ImportError, build failures, or missing wheels), follow these platform-specific tips:
829
+
830
+ **Apple Silicon (M1/M2):**
831
+ - Try installing psutil using the native ARM64 architecture:
832
+ ```bash
833
+ arch -arm64 pip install --no-cache-dir psutil
834
+ ```
835
+ - For Intel compatibility (Rosetta):
836
+ ```bash
837
+ arch -x86_64 pip install --no-cache-dir psutil
838
+ ```
839
+ - If you see compilation errors, ensure you have Xcode Command Line Tools installed:
840
+ ```bash
841
+ xcode-select --install
842
+ ```
843
+
844
+ **Linux:**
845
+ - Make sure you have Python development headers and a C compiler installed:
846
+ ```bash
847
+ sudo apt-get install python3-dev gcc
848
+ pip install --upgrade --force-reinstall psutil
849
+ ```
850
+
851
+ **Windows:**
852
+ - You may need to install Visual C++ Build Tools from:
853
+ https://visualstudio.microsoft.com/visual-cpp-build-tools/
854
+ - Then try:
855
+ ```bash
856
+ pip install --upgrade --force-reinstall psutil
857
+ ```
858
+
859
+ **General:**
860
+ - If you still have issues, try upgrading pip and setuptools:
861
+ ```bash
862
+ pip install --upgrade pip setuptools wheel
863
+ ```
864
+ - For more details, see the error message for platform-specific instructions.
865
+
866
+ > **Note:** psutil is required for all process monitoring features in Telert. If import fails, you’ll see a detailed error with platform-specific help.
771
867
 
772
- ---
773
- ## 🌿 Environment Variables
774
-
775
- Telert can be configured using environment variables, which is especially useful in CI/CD pipelines or containerized environments. Key variables include:
776
-
777
- - `TELERT_DEFAULT_PROVIDER` - Set default provider(s) to use
778
- - Provider-specific variables for Telegram, Teams, Slack, Discord, Pushover, etc.
779
- - Runtime variables like `TELERT_SILENT=1` for output control
780
-
781
- Environment variables take precedence over the configuration file, making them perfect for temporary overrides.
782
-
783
- [**See all environment variables**](https://github.com/navig-me/telert/blob/main/docs/ENVIRONMENT_VARIABLES.md)
784
-
785
- ---
786
-
787
- ## 🔍 Troubleshooting
788
-
789
- ### Common Issues and Solutions
790
-
791
- #### Notification Delivery Failures
792
- - **Symptom**: Notifications not being received
793
- - Verify your internet connection
794
- - Check provider configuration with `telert status`
795
- - For cloud services, verify API keys and webhook URLs
796
- - Check rate limits for your notification provider
797
-
798
- #### Audio Notifications Not Working
799
- - **Symptom**: No sound when using audio notifications
800
- - Ensure audio package dependencies are installed: `pip install 'telert[audio]'`
801
- - Check system volume and audio output device
802
- - On Linux, ensure `libasound2` and `libasound2-dev` are installed
803
-
804
- #### Apple Silicon (M1/M2) Installation
805
- - **Symptom**: Installation fails on Apple Silicon Macs
806
- - For Apple Silicon (M-series) users, try:
807
- ```bash
808
- # Native ARM64 installation (recommended)
809
- arch -arm64 pip install --no-cache-dir telert
810
-
811
- # Or for Intel compatibility
812
- arch -x86_64 pip install --no-cache-dir telert
813
- ```
814
868
 
815
869
  ---
816
870
  ## 📝 Message Formatting
@@ -10,13 +10,12 @@ telert.png
10
10
  ./telert/data/notification-icon.png
11
11
  ./telert/data/notification.mp3
12
12
  ./telert/monitoring/__init__.py
13
+ ./telert/monitoring/activity_logs.py
13
14
  ./telert/monitoring/base.py
14
15
  ./telert/monitoring/cli.py
15
16
  ./telert/monitoring/cli_logs.py
16
17
  ./telert/monitoring/debug_logs.py
17
- ./telert/monitoring/fixed_logs.py
18
18
  ./telert/monitoring/log.py
19
- ./telert/monitoring/logs.py
20
19
  ./telert/monitoring/network.py
21
20
  ./telert/monitoring/process.py
22
21
  telert/__init__.py
@@ -32,12 +31,11 @@ telert.egg-info/top_level.txt
32
31
  telert/data/notification-icon.png
33
32
  telert/data/notification.mp3
34
33
  telert/monitoring/__init__.py
34
+ telert/monitoring/activity_logs.py
35
35
  telert/monitoring/base.py
36
36
  telert/monitoring/cli.py
37
37
  telert/monitoring/cli_logs.py
38
38
  telert/monitoring/debug_logs.py
39
- telert/monitoring/fixed_logs.py
40
39
  telert/monitoring/log.py
41
- telert/monitoring/logs.py
42
40
  telert/monitoring/network.py
43
41
  telert/monitoring/process.py
@@ -1,267 +0,0 @@
1
- """Logging utilities for telert monitors."""
2
-
3
- import json
4
- import os
5
- import pathlib
6
- from datetime import datetime
7
- from enum import Enum
8
- from typing import Any, Dict, List, Optional, Union
9
-
10
- # Define the log directory
11
- LOG_DIR = pathlib.Path(os.path.expanduser("~/.config/telert/logs"))
12
- LOG_DIR.mkdir(parents=True, exist_ok=True)
13
-
14
- # Define debug logging to help troubleshoot log issues
15
- DEBUG_LOG_PATH = os.path.expanduser("~/telert_logs_debug.log")
16
- def _debug_log(message):
17
- """Write a debug message to help troubleshoot logging issues."""
18
- with open(DEBUG_LOG_PATH, "a") as f:
19
- timestamp = datetime.now().isoformat()
20
- f.write(f"{timestamp} - {message}\n")
21
-
22
- # Maximum number of log entries to keep per monitor type
23
- MAX_LOG_ENTRIES = 1000
24
-
25
-
26
- class LogLevel(Enum):
27
- """Log levels for monitor logs."""
28
- INFO = "info"
29
- WARNING = "warning"
30
- ERROR = "error"
31
- SUCCESS = "success"
32
- FAILURE = "failure"
33
-
34
- def __str__(self) -> str:
35
- return self.value
36
-
37
-
38
- class MonitorLogger:
39
- """Logger for telert monitors."""
40
-
41
- @staticmethod
42
- def log(
43
- monitor_id: str,
44
- monitor_type: str,
45
- level: LogLevel,
46
- message: str,
47
- details: Optional[Dict[str, Any]] = None,
48
- ) -> Dict[str, Any]:
49
- """
50
- Log a monitor event.
51
-
52
- Args:
53
- monitor_id: ID of the monitor
54
- monitor_type: Type of the monitor (process, log, network)
55
- level: Log level
56
- message: Log message
57
- details: Additional details to include in the log entry
58
-
59
- Returns:
60
- The log entry that was created
61
- """
62
- # Create log entry
63
- timestamp = datetime.now().isoformat()
64
- log_entry = {
65
- "timestamp": timestamp,
66
- "monitor_id": monitor_id,
67
- "monitor_type": monitor_type,
68
- "level": level.value,
69
- "message": message,
70
- "details": details or {},
71
- }
72
-
73
- # Load existing logs
74
- log_file = LOG_DIR / f"{monitor_type}_logs.json"
75
- _debug_log(f"Log file path: {log_file}")
76
- logs = []
77
-
78
- if log_file.exists():
79
- _debug_log(f"Log file exists: {log_file}")
80
- try:
81
- content = log_file.read_text()
82
- _debug_log(f"Read log file content length: {len(content)}")
83
- if content.strip():
84
- logs = json.loads(content)
85
- _debug_log(f"Loaded {len(logs)} log entries")
86
- else:
87
- _debug_log("Log file is empty, starting with empty logs")
88
- except (json.JSONDecodeError, OSError) as e:
89
- _debug_log(f"Error reading log file: {e}")
90
- # If file is corrupt or can't be read, start with empty logs
91
- logs = []
92
- else:
93
- _debug_log(f"Log file does not exist, creating new file: {log_file}")
94
- # Create an empty file
95
- try:
96
- log_file.write_text("[]")
97
- _debug_log(f"Created empty log file: {log_file}")
98
- except Exception as e:
99
- _debug_log(f"Error creating log file: {e}")
100
-
101
- # Add new log entry
102
- logs.append(log_entry)
103
-
104
- # Limit the number of logs
105
- if len(logs) > MAX_LOG_ENTRIES:
106
- logs = logs[-MAX_LOG_ENTRIES:]
107
-
108
- # Save logs
109
- try:
110
- log_content = json.dumps(logs, indent=2)
111
- _debug_log(f"Writing to log file: {log_file} - Content length: {len(log_content)}")
112
- log_file.write_text(log_content)
113
- _debug_log(f"Successfully wrote to log file: {log_file}")
114
- except Exception as e:
115
- _debug_log(f"Error writing to log file {log_file}: {e}")
116
-
117
- return log_entry
118
-
119
- @staticmethod
120
- def get_logs(
121
- monitor_type: Optional[str] = None,
122
- monitor_id: Optional[str] = None,
123
- level: Optional[Union[LogLevel, str]] = None,
124
- limit: int = 100,
125
- ) -> List[Dict[str, Any]]:
126
- """
127
- Retrieve monitor logs.
128
-
129
- Args:
130
- monitor_type: Filter by monitor type (process, log, network)
131
- monitor_id: Filter by monitor ID
132
- level: Filter by log level
133
- limit: Maximum number of logs to return
134
-
135
- Returns:
136
- List of log entries matching the filters
137
- """
138
- _debug_log(f"get_logs called with type={monitor_type}, id={monitor_id}, level={level}, limit={limit}")
139
-
140
- # Normalize level if it's a string
141
- if level is not None and isinstance(level, str):
142
- try:
143
- level = LogLevel(level)
144
- except ValueError:
145
- raise ValueError(f"Invalid log level: {level}")
146
-
147
- # Determine which log files to load
148
- if monitor_type:
149
- log_files = [LOG_DIR / f"{monitor_type}_logs.json"]
150
- else:
151
- # Load all monitor types
152
- log_files = [
153
- LOG_DIR / "process_logs.json",
154
- LOG_DIR / "log_logs.json",
155
- LOG_DIR / "network_logs.json",
156
- ]
157
-
158
- # Load and filter logs
159
- all_logs = []
160
- for log_file in log_files:
161
- _debug_log(f"Checking log file: {log_file}")
162
- if not log_file.exists():
163
- _debug_log(f"Log file does not exist: {log_file}")
164
- continue
165
-
166
- try:
167
- content = log_file.read_text()
168
- if not content.strip():
169
- _debug_log(f"Log file is empty: {log_file}")
170
- continue
171
-
172
- logs = json.loads(content)
173
- _debug_log(f"Loaded {len(logs)} entries from {log_file}")
174
- all_logs.extend(logs)
175
- except (json.JSONDecodeError, OSError) as e:
176
- # Skip files that can't be read
177
- _debug_log(f"Error reading log file {log_file}: {e}")
178
- continue
179
-
180
- # Apply filters
181
- filtered_logs = []
182
- for log in all_logs:
183
- # Filter by monitor ID if specified
184
- if monitor_id and log.get("monitor_id") != monitor_id:
185
- continue
186
-
187
- # Filter by level if specified
188
- if level and log.get("level") != level.value:
189
- continue
190
-
191
- filtered_logs.append(log)
192
-
193
- _debug_log(f"Filtered to {len(filtered_logs)} logs")
194
-
195
- # Sort by timestamp (newest first)
196
- filtered_logs.sort(key=lambda x: x.get("timestamp", ""), reverse=True)
197
-
198
- # Apply limit
199
- result = filtered_logs[:limit]
200
- _debug_log(f"Returning {len(result)} logs after limit")
201
- return result
202
-
203
- @staticmethod
204
- def clear_logs(monitor_type: Optional[str] = None, monitor_id: Optional[str] = None) -> int:
205
- """
206
- Clear monitor logs.
207
-
208
- Args:
209
- monitor_type: Clear logs for this monitor type only
210
- monitor_id: Clear logs for this monitor ID only
211
-
212
- Returns:
213
- Number of log entries cleared
214
- """
215
- _debug_log(f"clear_logs called with type={monitor_type}, id={monitor_id}")
216
-
217
- if monitor_id and not monitor_type:
218
- # Need to determine monitor type from ID prefix
219
- if monitor_id.startswith("pro"):
220
- monitor_type = "process"
221
- elif monitor_id.startswith("log"):
222
- monitor_type = "log"
223
- elif monitor_id.startswith("net"):
224
- monitor_type = "network"
225
-
226
- # Determine which log files to clear
227
- if monitor_type:
228
- log_files = [LOG_DIR / f"{monitor_type}_logs.json"]
229
- else:
230
- # Clear all monitor types
231
- log_files = [
232
- LOG_DIR / "process_logs.json",
233
- LOG_DIR / "log_logs.json",
234
- LOG_DIR / "network_logs.json",
235
- ]
236
-
237
- count = 0
238
-
239
- # Clear logs
240
- for log_file in log_files:
241
- _debug_log(f"Checking log file: {log_file}")
242
- if not log_file.exists():
243
- _debug_log(f"Log file does not exist: {log_file}")
244
- continue
245
-
246
- try:
247
- if monitor_id:
248
- # Only clear logs for specific monitor ID
249
- logs = json.loads(log_file.read_text())
250
- original_count = len(logs)
251
- logs = [log for log in logs if log.get("monitor_id") != monitor_id]
252
- count += original_count - len(logs)
253
- log_file.write_text(json.dumps(logs, indent=2))
254
- else:
255
- # Clear all logs for this monitor type
256
- try:
257
- logs = json.loads(log_file.read_text())
258
- count += len(logs)
259
- except (json.JSONDecodeError, OSError):
260
- pass
261
- log_file.write_text("[]")
262
- except (json.JSONDecodeError, OSError):
263
- # Skip files that can't be read
264
- continue
265
-
266
- _debug_log(f"Cleared {count} log entries")
267
- return count
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes