flutter_log_handler 1.0.2
flutter_log_handler: ^1.0.2 copied to clipboard
Enterprise-grade Flutter logging with console/file logs, crash capture, API interception, and built-in log viewer UI.
flutter_log_handler #
Enterprise-Grade Logging, Crash Tracking & API Monitoring Framework for Flutter
A production-ready logging infrastructure built specifically for modern Flutter applications.
Designed for enterprise apps, production builds, QA testing, white-label solutions, and scalable client deployments.
🚀 Why Use flutter_log_handler? #
print() is not production logging.
Modern Flutter apps require:
- ✅ Structured logs (info / warning / error)
- ✅ Persistent local storage with retention policy
- ✅ Crash capture & reporting
- ✅ API request/response tracking with performance monitoring
- ✅ Sensitive data masking (passwords, tokens, API keys)
- ✅ Enterprise-grade log viewer (search, filter, export)
- ✅ Shareable diagnostics for QA and supportExportable logs (TXT / JSON / PDF / GZIP)
flutter_log_handler delivers a complete observability layer inside your Flutter application.
Lightweight. Configurable. Enterprise-ready.
🎯 Ideal Use Cases #
- Enterprise Flutter apps
- Production & QA builds
- API performance tracking & crash diagnostics
- White-label client deployments
- Large-scale apps requiring structured logs
🔥 Core Features #
| Feature | Description | Badge |
|---|---|---|
| Structured Logging | Log levels, timestamps, stack trace, route & API tracking, custom tags | 📝 |
| Crash Capture | Flutter errors, unhandled exceptions, async & zone errors, device metadata | 💥 |
| Hive Persistence | Local log storage with retention days & auto-cleanup | 🗂 |
| API Monitoring | Dio interceptor, slow API detection, masked request/response logging | 🌐 |
| Sensitive Data Masking | Auto-mask keys like password, token, apiKey | 🔐 |
| Log Viewer UI | Animated filter chips, real-time search, expandable stack traces, Pull-to-refresh, Pull-to-refresh, Copy log button, Share logs, Clean production-ready card UI |
🖥 |
| Export Logs | TXT / JSON / PDF / GZIP, only today logs, grouped by date, customizable formats | 📤 |
| Session & Env Tags | Automatic session ID & environment (flavor, version, platform) tagging | 🛡 |
| Auto Upload System (NEW) | Config-driven multipart upload with dynamic body fields | ☁️ |
📦 Installation #
dependencies:
flutter_log_handler: ^1.0.2
Then run:
flutter pub get
⚙️ Quick Setup #
Initialize Logger in main() #
void main() async {
WidgetsFlutterBinding.ensureInitialized();
// Start session
SessionManager.startSession();
// Set environment tags
LogContext.setEnvironment(
flavor: "development",
appVersion: "0.0.6",
platform: "android",
);
// Initialize Hive log service
await LogServiceHive.init(
LogConfig(
retentionDays: 5,
enableConsoleLog: true,
sensitiveKeys: ["password", "token", "apiKey"],
clearLogsOnLogout: true
ignoreInfoLogs: true
),
);
runApp(const MyApp());
}
NEW: Log Upload System (v1.0.2) #
Supports:
- Multipart upload
- Static + dynamic body parameters
- Auto upload at intervals
- Manual upload trigger
- Strongly typed HTTP methods
- Cancelable upload with progress tracking
🔹 Upload Configuration Example #
await LogServiceHive.init(
LogConfig(
uploadLevels: [LogLevelHive.error], // Upload ONLY ERROR logs
keepUploadHistory: true, // Keep Upload History
uploadUrl: "https://api.yourserver.com/upload-logs",
enableAutoUpload: true,
uploadMethod: LogUploadMethod.post,
uploadHeaders: {
"Authorization": "Bearer YOUR_TOKEN",
},
// Static body fields
uploadFields: {
"appVersion": "1.0.0",
"platform": "android",
},
// Dynamic runtime fields
extraFieldsBuilder: () async {
return {
"sessionId": SessionManager.currentSessionId,
"timestamp": DateTime.now().toIso8601String(),
};
},
fileFieldName: "log_file", // if backend expects different key
uploadInterval: const Duration(minutes: 30),
compressBeforeUpload: true,
),
);
The final multipart request will look like: #
POST /logs/upload Content-Type: multipart/form-data { appVersion: "1.0.0" platform: "android" sessionId: "abc123" userId: "42" timestamp: "2026-02-25T12:00:00Z" log_file: logs_123456.gz }
# 🔹 Manual Upload
await LogServiceHive.to.uploadLogs();
---
# 🔹 Cancel Upload
LogServiceHive.to.cancelUpload();
---
# 📝 Logging Examples
## Simple Log
```dart
LogServiceHive.to.logEvent(
message: "User logged in",
level: LogLevel.info,
);
Log with Stack Trace #
LogServiceHive.to.logEvent(
message: error.toString(),
stackTrace: stack.toString(),
level: LogLevelHive.error,
);
Log with API Endpoint #
LogServiceHive.to.logEvent(
message: "API Failed",
level: LogLevel.error,
stackTrace: stack.toString(),
apiEndpoint: "/api/login",
);
Fetch Logs #
// Fetch all logs stored in Hive (latest first)
final logs = await LogServiceHive.to.getLogs();
// Example:
for (var log in logs) {
print("[${log.level.name.toUpperCase()}] ${log.timestamp}: ${log.message}");
}
💥 Crash Capture Setup #
await CrashWrapper.initialize(
logService: LogServiceHive.to,
);
Automatically captures:
- Flutter framework errors
- Unhandled async errors & Zone errors
- Device, platform, Session ID and environment tags
🧭 Route Tracking Setup #
MaterialApp(
navigatorObservers: [
RouteTracker(),
],
home: const HomeScreen(),
);
Automatically captures:
- Route push events, pop events, and replace events
- Current active screen name
- Navigation stack changes
🌐 API Monitoring with Dio #
final dio = Dio();
dio.interceptors.add(
ApiInterceptor(LogServiceHive.to),
);
Logs:
- Request method & endpoint
- Request/response bodies (masked)
- Status & duration
- Slow API warnings
- API errors with stack traces
🖥 Open Log Viewer Screen #
Navigator.push(
context,
MaterialPageRoute(
builder: (_) => LogViewerScreen(
title: "App Logs",
// Action buttons
enableShareButton: true,
enableRefreshButton: true,
enableClearButton: true,
// Search & filter
enableCollapsibleSearch: true,
showLevelChips: true,
enablePullToRefresh: true,
// Export system
enableCustomExportMenu: true,
allowedExportFormats: [
LogExportFormat.txt,
LogExportFormat.json,
LogExportFormat.pdf,
],
exportGroupByDate: true,
exportFormat: LogExportFormat.pdf,
// Upload logs to server
enableManualUpload: true,
showLogUploadHistoryButton: true,
),
),
);
#Features:
- Filter by log level
- Expand stack traces
- Refresh logs
- Share logs
- Enterprise UI design
- Supports 500k+ logs safely
- Lazy loading via streams
📊 Configuration Options #
LogConfig(
retentionDays: 5,
enableConsoleLog: true,
sensitiveKeys: ["password", "secretKey"],
);
| Parameter | Description |
|---|---|
| retentionDays | Auto-delete logs older than X days |
| enableConsoleLog | Print logs in debug console |
| sensitiveKeys | Keys automatically masked |
| uploadUrl | Server endpoint for log upload |
| enableAutoUpload | Enables background upload |
| uploadFields | Static multipart body fields |
| extraFieldsBuilder | Dynamic runtime body fields |
| uploadMethod | POST / PUT / PATCH |
| fileFieldName | Custom file field key |
| uploadInterval | Auto upload interval |
| compressBeforeUpload | GZIP compression before upload |
📁 Log Storage Location #
- Hive stores logs in your app's internal storage:
ApplicationDocumentsDirectory / hive / app_logs
🛡 Architecture Highlights #
- Automatic route tracking
- Automatic crash tagging
- Session & environment tagging (SessionManager + LogContext)
- Enterprise filtering engine
- No dependency injection required
- Works with GetX or without it
- Easily extendable to cloud upload
- Modular production-ready architecture
- Safe for release builds
📈 SEO Keywords #
Flutter logger
Flutter crash logger
Flutter file logger
Flutter API interceptor
Flutter production monitoring
Flutter enterprise logging
Flutter monitoring framework
Flutter error tracking
Flutter debugging tool
Flutter performance monitoring
🏆 Designed for Production #
flutter_log_handler flutter_log_handler provides structured, production-safe logging for enterprise-grade Flutter apps.
📄 License #
MIT License