MAUI Monitoring & Alerting
.NET MAUI C# Cross-platform Monitoring Crash Reporting Performance Sentry Firebase Application Insights Alert Mobile Android iOS
| Tool | Feature | Platform | Price |
|---|---|---|---|
| Sentry | Crash + Performance + Breadcrumbs | Android iOS Windows macOS | Free 5K events/mo |
| Firebase Crashlytics | Crash Reporting Real-time | Android iOS | Free |
| Application Insights | APM Logging Metrics Traces | All (.NET native) | Azure Pay-as-you-go |
| New Relic | Mobile APM Full Stack | Android iOS | Free 100GB/mo |
| Datadog RUM | Real User Monitoring | Android iOS | $1.50/1K sessions |
Sentry Integration
# === Sentry for .NET MAUI ===
# Install NuGet:
# dotnet add package Sentry.Maui
# MauiProgram.cs:
# public static MauiApp CreateMauiApp()
# {
# var builder = MauiApp.CreateBuilder();
# builder
# .UseMauiApp()
# .UseSentry(options =>
# {
# options.Dsn = "https://examplePublicKey@o0.ingest.sentry.io/0";
# options.Debug = true; // Dev only
# options.TracesSampleRate = 1.0; // 100% transactions
# options.ProfilesSampleRate = 1.0;
# options.AttachScreenshot = true;
# options.SetBeforeSend((sentryEvent, hint) =>
# {
# // Filter or modify events
# sentryEvent.SetTag("app_version", "1.2.3");
# sentryEvent.User = new SentryUser
# {
# Id = CurrentUser.Id,
# Email = CurrentUser.Email
# };
# return sentryEvent;
# });
# });
# return builder.Build();
# }
from dataclasses import dataclass
@dataclass
class MonitorConfig:
component: str
tool: str
config: str
alert_rule: str
configs = [
MonitorConfig("Crash Reporting",
"Sentry",
"UseSentry(dsn) + AttachScreenshot + User Context",
"New Crash > 5 users → P1 Alert Slack"),
MonitorConfig("Performance",
"Sentry Transactions",
"TracesSampleRate = 0.2 (20% sampling)",
"App Launch > 3s → Warning Alert"),
MonitorConfig("Custom Events",
"Sentry Breadcrumbs",
"SentrySdk.AddBreadcrumb(message, category)",
"Error Rate > 5% → P2 Alert"),
MonitorConfig("Network Monitoring",
"Sentry HTTP Integration",
"Auto-capture HTTP calls duration status",
"API Error Rate > 10% → P1 Alert"),
MonitorConfig("Release Health",
"Sentry Release",
"options.Release = '1.2.3' Crash Free Rate",
"Crash Free < 99% → P1 Alert Rollback"),
]
print("=== Monitoring Configuration ===")
for c in configs:
print(f" [{c.component}] Tool: {c.tool}")
print(f" Config: {c.config}")
print(f" Alert: {c.alert_rule}")
Performance Monitoring
# === MAUI Performance Metrics ===
# Custom Performance Tracking:
# using var transaction = SentrySdk.StartTransaction("MainPage", "navigation");
# var span = transaction.StartChild("api-call", "Load user data");
# try {
# var data = await _apiService.GetUserDataAsync();
# span.Finish(SpanStatus.Ok);
# } catch (Exception ex) {
# span.Finish(ex);
# throw;
# }
# transaction.Finish();
@dataclass
class PerfMetric:
metric: str
target: str
measure_method: str
optimization: str
perf_metrics = [
PerfMetric("App Launch (Cold Start)",
"< 2 seconds",
"Sentry Transaction app.launch + Stopwatch",
"AOT Compilation Lazy Load Reduce Startup DI"),
PerfMetric("App Launch (Warm Start)",
"< 500ms",
"Sentry Transaction app.resume",
"Cache State Minimize OnResume Work"),
PerfMetric("Page Navigation",
"< 300ms",
"Sentry Span page.navigation.{PageName}",
"Compiled Bindings Reduce Visual Tree"),
PerfMetric("API Response Time",
"< 1 second",
"Sentry HTTP Integration Auto-capture",
"Caching Retry Polly Connection Pooling"),
PerfMetric("Memory Usage",
"< 150MB",
"DeviceInfo + GC.GetTotalMemory()",
"WeakReference Dispose Image Caching"),
PerfMetric("Crash Free Rate",
"> 99.5%",
"Sentry Release Health Dashboard",
"Error Handling Null Checks Unit Tests"),
PerfMetric("Frame Rate",
"> 55 FPS (Target 60)",
"Platform Profiler (Android Studio Instruments)",
"Reduce Layout Complexity Async UI Updates"),
]
print("=== Performance Metrics ===")
for m in perf_metrics:
print(f" [{m.metric}] Target: {m.target}")
print(f" Measure: {m.measure_method}")
print(f" Optimize: {m.optimization}")
Alert & Incident
# === Alert Configuration ===
@dataclass
class AlertRule:
alert: str
condition: str
severity: str
channel: str
action: str
alerts = [
AlertRule("New Crash Spike",
"Crash count > 50 in 1 hour OR affects > 5% users",
"P1 Critical",
"Slack #mobile-alerts + PagerDuty",
"Investigate immediately Hotfix if needed"),
AlertRule("Crash Free Rate Drop",
"Crash Free Rate < 99% for latest release",
"P1 Critical",
"Slack + PagerDuty + Email CTO",
"Consider rollback Review crash logs"),
AlertRule("App Launch Slow",
"Cold start P95 > 3 seconds",
"P2 High",
"Slack #mobile-perf",
"Profile startup Optimize lazy load"),
AlertRule("API Error Rate",
"HTTP 5xx > 10% of requests in 5 min",
"P1 Critical",
"Slack + PagerDuty",
"Check backend Health endpoint"),
AlertRule("Memory Warning",
"App memory > 200MB on any device",
"P3 Medium",
"Slack #mobile-perf",
"Profile memory leaks Review image cache"),
]
print("=== Alert Rules ===")
for a in alerts:
print(f" [{a.alert}] Severity: {a.severity}")
print(f" Condition: {a.condition}")
print(f" Channel: {a.channel}")
print(f" Action: {a.action}")
เคล็ดลับ
- Sentry: ใช้ Sentry.Maui NuGet ตั้งค่าง่าย ครบทุก Platform
- Screenshot: เปิด AttachScreenshot ดู Context ตอน Crash
- Sampling: Production ใช้ TracesSampleRate 0.1-0.2 ลด Cost
- Release: ตั้ง Release Version ดู Crash Free Rate ต่อ Version
- AOT: เปิด AOT Compilation ลด App Launch Time 30-50%
การดูแลระบบในสภาพแวดล้อม Production
การบริหารจัดการระบบ Production ที่ดีต้องมี Monitoring ครอบคลุม ใช้เครื่องมืออย่าง Prometheus + Grafana สำหรับ Metrics Collection และ Dashboard หรือ ELK Stack สำหรับ Log Management ตั้ง Alert ให้แจ้งเตือนเมื่อ CPU เกิน 80% RAM ใกล้เต็ม หรือ Disk Usage สูง
Backup Strategy ต้องวางแผนให้ดี ใช้หลัก 3-2-1 คือ มี Backup อย่างน้อย 3 ชุด เก็บใน Storage 2 ประเภทต่างกัน และ 1 ชุดต้องอยู่ Off-site ทดสอบ Restore Backup เป็นประจำ อย่างน้อยเดือนละครั้ง เพราะ Backup ที่ Restore ไม่ได้ก็เหมือนไม่มี Backup
เรื่อง Security Hardening ต้องทำตั้งแต่เริ่มต้น ปิด Port ที่ไม่จำเป็น ใช้ SSH Key แทน Password ตั้ง Fail2ban ป้องกัน Brute Force อัพเดท Security Patch สม่ำเสมอ และทำ Vulnerability Scanning อย่างน้อยเดือนละครั้ง ใช้หลัก Principle of Least Privilege ให้สิทธิ์น้อยที่สุดที่จำเป็น
.NET MAUI คืออะไร
Microsoft Cross-platform C# XAML Android iOS macOS Windows .NET 8+ MVVM Hot Reload Native Performance Single Project Xamarin
App Monitoring ทำอย่างไร
Sentry Firebase Crashlytics Application Insights New Relic Datadog Crash Performance Network Device Custom Events Breadcrumbs
Crash Reporting ตั้งอย่างไร
Sentry.Maui NuGet UseSentry DSN Screenshot User Context Firebase Crashlytics Application Insights Global Exception Handler
Performance Optimize อย่างไร
AOT Compiled Bindings CollectionView Virtualize WeakReference Dispose Cache HttpClient Singleton Polly Launch < 2s Memory < 150MB 99.5%
สรุป
.NET MAUI C# Monitoring Sentry Crash Performance Alert Release Health AOT Compiled Bindings Memory Network Mobile Production
