8.3 KiB
📊 Monitoring & Alerts System - Implementation Report
Date: 2025-11-30
Status: ✅ Skeleton Implemented
Completion: 30% (Structure ready, integrations pending)
🎯 Overview
اسکلت سیستم Monitoring & Alerts برای پروژه CMS پیادهسازی شد. این سیستم به دو بخش اصلی تقسیم میشود:
- Alert System: برای ارسال اعلانهای مدیریتی (Critical Errors, Warnings, Success)
- User Notification System: برای ارسال پیام به کاربران (کمیسیون، پرداخت، فعالسازی باشگاه)
📦 Files Created/Modified
✨ New Files:
-
IAlertService.cs(Interface)SendCriticalAlertAsync()- برای خطاهای CriticalSendWarningAlertAsync()- برای Warning هاSendSuccessNotificationAsync()- برای موفقیتها
-
IUserNotificationService.cs(Interface)SendCommissionReceivedNotificationAsync()- اعلان دریافت کمیسیونSendClubActivationNotificationAsync()- اعلان فعالسازی باشگاهSendPayoutErrorNotificationAsync()- اعلان خطا در پرداخت
-
AlertService.cs(Implementation - Skeleton)- ✅ Logging به Console
- ⏳ TODO: Sentry Integration
- ⏳ TODO: Slack Integration
- ⏳ TODO: Email Integration
-
UserNotificationService.cs(Implementation - Skeleton)- ✅ Logging به Console
- ⏳ TODO: SMS Gateway Integration
- ⏳ TODO: Email Service Integration
- ⏳ TODO: Push Notification Integration
-
MonitoringSettings.cs(Configuration Model)- تنظیمات Sentry, Slack, Email, SMS
- قابل تنظیم از طریق
appsettings.json
✏️ Modified Files:
-
ConfigureServices.csservices.AddScoped<IAlertService, AlertService>(); services.AddScoped<IUserNotificationService, UserNotificationService>(); -
WeeklyNetworkCommissionWorker.cs- ✅ Integration با
IAlertService - ✅ ارسال Critical Alert در صورت خطا
- ✅ ارسال Success Notification پس از اتمام موفق
- ✅ Integration با
-
appsettings.json- اضافه شدن بخش
Monitoringبا تنظیمات پیشفرض
- اضافه شدن بخش
🔧 Current Implementation
Alert System Usage:
// در Worker یا هر Handler دیگر:
try
{
// عملیات خطرناک
}
catch (Exception ex)
{
await _alertService.SendCriticalAlertAsync(
"Operation Failed",
"Description of what went wrong",
ex);
}
Current Output:
🚨 CRITICAL ALERT: Weekly Commission Worker Failed - Worker execution abc-123 failed for week 2025-W48
⏳ Pending Integrations (TODO)
1. Sentry Integration
// در AlertService.SendCriticalAlertAsync():
if (_settings.SentryEnabled)
{
SentrySdk.CaptureException(exception);
}
Steps:
- Install NuGet:
Sentry.AspNetCore - Configure DSN in
appsettings.json - Add to
Program.cs:builder.WebHost.UseSentry()
2. Slack Integration
// در AlertService:
if (_settings.SlackEnabled)
{
var payload = new
{
text = $"🚨 {title}",
attachments = new[]
{
new { text = message, color = "danger" }
}
};
await _httpClient.PostAsJsonAsync(_settings.SlackWebhookUrl, payload);
}
Steps:
- Create Slack Incoming Webhook
- Add URL to
appsettings.json - Install NuGet:
System.Net.Http.Json
3. Email Alerts (برای Admin)
// در AlertService:
if (_settings.EmailAlertsEnabled)
{
foreach (var email in _settings.AdminEmails)
{
await _emailService.SendAsync(
to: email,
subject: $"[ALERT] {title}",
body: message);
}
}
Steps:
- Configure SMTP settings
- Install NuGet:
MailKitor use existing email service - Add admin emails to config
4. SMS Notifications (برای کاربران)
// در UserNotificationService.SendCommissionReceivedNotificationAsync():
var user = await _context.Users.FindAsync(userId);
if (user.SmsNotifications && _settings.SmsNotificationsEnabled)
{
var message = $"کمیسیون شما: {amount:N0} ریال برای هفته {weekNumber} واریز شد.";
await _smsGateway.SendAsync(user.Mobile, message);
}
Steps:
- Choose SMS provider (Kavenegar, Ghasedak, etc.)
- Get API Key
- Implement
ISmsGatewayService
5. Retry Logic با Exponential Backoff
// در Worker:
private async Task<T> RetryWithExponentialBackoff<T>(
Func<Task<T>> operation,
int maxRetries = 3)
{
for (int i = 0; i < maxRetries; i++)
{
try
{
return await operation();
}
catch (Exception ex) when (i < maxRetries - 1)
{
var delay = TimeSpan.FromSeconds(Math.Pow(2, i)); // 2^i seconds
_logger.LogWarning("Retry {Attempt}/{Max} after {Delay}s",
i + 1, maxRetries, delay.TotalSeconds);
await Task.Delay(delay);
}
}
}
📋 Configuration Example
در appsettings.Production.json:
{
"Monitoring": {
"SentryEnabled": true,
"SentryDsn": "https://xxxxx@sentry.io/12345",
"SlackEnabled": true,
"SlackWebhookUrl": "https://hooks.slack.com/services/T00000000/B00000000/XXXXXXXXXXXXXXXXXXXX",
"EmailAlertsEnabled": true,
"AdminEmails": [
"admin@foursat.ir",
"devops@foursat.ir"
],
"SmsNotificationsEnabled": true,
"SmsApiKey": "your-kavenegar-api-key",
"SmsGatewayUrl": "https://api.kavenegar.com/v1/{apikey}/sms/send.json"
}
}
🧪 Testing
Test 1: Alert Service
var alertService = serviceProvider.GetRequiredService<IAlertService>();
await alertService.SendCriticalAlertAsync(
"Test Alert",
"This is a test critical alert");
Expected: Log در Console + (در Production) Sentry + Slack
Test 2: User Notification
var notificationService = serviceProvider.GetRequiredService<IUserNotificationService>();
await notificationService.SendCommissionReceivedNotificationAsync(
userId: 123,
amount: 500_000,
weekNumber: 48);
Expected: Log در Console + (در Production) SMS + Email
📊 Integration Priority
| Priority | Integration | Effort | Impact |
|---|---|---|---|
| 🔴 High | Sentry | 1 hour | Critical error tracking |
| 🟡 Medium | Slack | 2 hours | Real-time admin alerts |
| 🟡 Medium | SMS (Kavenegar) | 3 hours | User notifications |
| 🟢 Low | Email Alerts | 2 hours | Backup notification channel |
| 🟢 Low | Retry Logic | 1 hour | Reliability improvement |
✅ Current Status Summary
Completed (30%):
- ✅ Interface definitions
- ✅ Skeleton implementations with Logging
- ✅ DI registration
- ✅ Worker integration
- ✅ Configuration model
- ✅ appsettings structure
Pending (70%):
- ⏳ Sentry integration (5%)
- ⏳ Slack webhook (10%)
- ⏳ Email service (10%)
- ⏳ SMS gateway (15%)
- ⏳ Push notifications (10%)
- ⏳ Retry logic (5%)
- ⏳ Testing (10%)
- ⏳ Documentation (5%)
🚀 Next Steps
-
Immediate (در صورت نیاز):
- Enable Sentry for error tracking
- Setup Slack webhook for critical alerts
-
Short-term (هفته آینده):
- Integrate SMS gateway (Kavenegar)
- Test User notifications
-
Long-term (ماه آینده):
- Add Email service
- Implement Retry logic
- Push notification service
📝 Notes
- تمام TODO ها در کد با comment مشخص شدهاند
- فعلاً فقط Logging فعال است
- برای Production باید حتماً یکی از Integration ها (Sentry/Slack) فعال شود
- SMS Gateway باید بر اساس پروژه انتخاب شود (Kavenegar, Ghasedak, etc.)
🔗 Related Files
- Interfaces:
CMSMicroservice.Application/Common/Interfaces/IAlertService.cs - Implementations:
CMSMicroservice.Infrastructure/Services/Monitoring/ - Worker:
CMSMicroservice.Infrastructure/BackgroundJobs/WeeklyNetworkCommissionWorker.cs - Config:
CMSMicroservice.WebApi/appsettings.json
Report generated: 2025-11-30
Build Status: ✅ Success
Ready for: Development continuation / Integration implementation