Flutter日志记录插件snug_logger的使用
Flutter日志记录插件snug_logger的使用
Snug Logger 🛋️
Spice up your logs with Snug Logger! 🎉🛋️
Click here to try it out! 🚀✨
Welcome to Snug Logger! 🚀
Wave goodbye to mundane, dull logs and embrace the colorful, emoji-filled world of Snug Logger! 🎉💻✨ With us, debugging is no longer a chore but a lively, fun-filled experience.
Why Choose Snug Logger?
- 🛋️ Cozy to Use: Vibrant and clear log messages that are as comforting as your favorite hoodie.
- 🎨 Color-Coded Clarity: Instantly spot log levels with our dynamic colors and emojis.
- 📊 Professional Structure: Playful yet organized, ensuring your logs are both engaging and easy to navigate.
Features:
1. Colorful Logging
- Brighten up your log readability with dynamic colors for different log levels.
- Emojis bring your logs to life: 🐞 for debug, ℹ️ for info, 🚨 for error, and more!
2. Versatile Log Levels
- Log various levels:
debug
,info
,error
, andproduction
. Each has its own role, keeping your logs purposeful and organized.
3. SnugDioLogger for Network Requests
- Enhance your network request logs with SnugDioLogger for detailed insights into every request and response.
- Tailor what you log—headers, request data, and response content—with fine-tuned control.
4. Structured Log Formatting
- Logs follow a clear, structured template, blending fun with functionality.
- Consistent formatting across all levels for a polished, professional look.
Installation:
Getting started with Snug Logger is a breeze! Add it to your pubspec.yaml
file:
dependencies:
snug_logger: ^1.0.10
Then, fetch the package:
flutter pub get
Quick Start:
Import the Package:
import 'package:snug_logger/snug_logger.dart';
Basic Usage:
Bring some flair to your logs with just a few lines of code!
Example: Info Log
snugLog(
"This is an info message, filled with dad-joke-level wisdom and charm! 👨👧👦🤣",
logType: LogType.info
);
Example: Debug Log
snugLog(
"Debugging with precision! No clowns involved, just pure detective work. 🤡🔍",
logType: LogType.debug
);
Example: Error Log
snugLog(
"Oops! Something went wrong, but don't worry, I've got the toolkit ready! 🦸♂️🔧",
logType: LogType.error,
stackTrace: StackTrace.current
);
Example: Production Log
snugLog(
"Production-ready logs: polished, professional, and prepared for the spotlight! 🎭😄",
logType: LogType.production
);
Network Logging with SnugDioLogger:
Integrate SnugDioLogger for detailed network request logs:
_dio.interceptors.add(
SnugDioLogger(
requestHeaders: true,
requestData: true,
responseHeaders: true,
responseData: true,
logPrint: (object) => debugPrint(object.toString()),
),
);
You control exactly what gets logged—headers, request data, or full responses. 🕵️♂️
Join the Snug Squad!
Got ideas or feedback? We’re all ears! Here’s how to get involved:
Let’s make logging a delightful part of coding! 🚀✨
Why did the programmer go broke? Because they used up all their cache! 💸😄
示例代码
example/lib/main.dart
import 'package:flutter/material.dart';
import 'dart:developer';
import 'package:dio/dio.dart';
import 'package:snug_logger/snug_logger.dart';
import 'package:flutter/foundation.dart';
void main() {
runApp(const MyApp());
}
// Main application widget
class MyApp extends StatelessWidget {
const MyApp({super.key});
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Snug Logger Use Case Demo',
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
useMaterial3: true,
),
home: const MyHomePage(),
);
}
}
// Home page widget with state
class MyHomePage extends StatefulWidget {
const MyHomePage({Key? key}) : super(key: key);
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
final Dio _dio = Dio();
@override
void initState() {
super.initState();
// Add SnugDioLogger to Dio instance in debug mode
if (kDebugMode) {
_dio.interceptors.add(
SnugDioLogger(
requestData: false, // Fetch request data
requestHeaders: false, // Fetch request headers
responseMessage: false, // Fetch response message
responseData: true, // Fetch response data
responseHeaders: false, // Fetch response headers
logPrint: (object) {
// Use debugPrint to print logs so it won't be printed in release mode
debugPrint(object.toString());
},
),
);
}
}
// Method to handle division by zero error
_handleError(int i, int divisor) {
try {
if (divisor == 0) {
throw Exception(
'Cannot divide by zero. Mathematical paradox detected! 🧮');
}
return i / divisor;
} catch (error, stackTrace) {
snugLog('$error', logType: LogType.error, stackTrace: stackTrace);
}
}
// Method to perform a sample Dio GET request
Future<void> _performSampleRequest() async {
try {
final response =
await _dio.get('https://jsonplaceholder.typicode.com/posts/1');
snugLog('Dio Request Successful! Response: ${response.data} 🎉',
logType: LogType.info);
log("${response.data}");
} catch (error, stackTrace) {
snugLog('$error', logType: LogType.error, stackTrace: stackTrace);
}
}
// Method to perform a Dio GET request with an intentional error
Future<void> _performErrorRequest() async {
try {
final response =
await _dio.get('https://jsonplaceholder.typicode.com/posts/invalid');
snugLog('Dio Error Request Successful! Response: ${response.data} 🚨',
logType: LogType.debug);
} catch (error, stackTrace) {
snugLog('$error', logType: LogType.error, stackTrace: stackTrace);
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('SnugLogger Package Demo'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
ElevatedButton(
onPressed: () => snugLog('Having fun with Demo Data! 🚀'),
child: const Text('Demo Data Print'),
),
const SizedBox(height: 16),
ElevatedButton(
onPressed: () =>
snugLog('Enjoying a Info message! 🌟', logType: LogType.info),
child: const Text('Info message'),
),
const SizedBox(height: 16),
ElevatedButton(
onPressed: () =>
snugLog('Just having a good time with Debug! 🔍'),
child: const Text('Debug message'),
),
const SizedBox(height: 16),
ElevatedButton(
onPressed: () =>
snugLog('Heavy Debugging in Production! 🛠️ ',
logType: LogType.production),
child: const Text('Production message'),
),
const SizedBox(height: 16),
ElevatedButton(
onPressed: () => _handleError(10, 0),
child: const Text('Throw Custom Error'),
),
const SizedBox(height: 16),
ElevatedButton(
onPressed: _performSampleRequest,
child: const Text('Perform Dio Request'),
),
const SizedBox(height: 16),
ElevatedButton(
onPressed: _performErrorRequest,
child: const Text('Perform Dio Request With Error'),
),
const SizedBox(height: 16),
],
),
),
);
}
}
以上是一个完整的示例,展示了如何在Flutter应用中使用snug_logger
插件进行日志记录。希望这对你有所帮助!如果有任何问题或需要进一步的帮助,请随时提问。🚀✨
更多关于Flutter日志记录插件snug_logger的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter日志记录插件snug_logger的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
当然,以下是一个关于如何在Flutter项目中使用snug_logger
插件进行日志记录的示例代码。snug_logger
是一个功能强大的日志记录库,它允许你在Flutter应用中轻松地记录和管理日志。
首先,确保你已经在你的pubspec.yaml
文件中添加了snug_logger
依赖:
dependencies:
flutter:
sdk: flutter
snug_logger: ^最新版本号 # 请替换为实际可用的最新版本号
然后,运行flutter pub get
来安装依赖。
接下来,你可以在你的Flutter项目中设置和使用snug_logger
。以下是一个简单的示例,展示了如何配置和使用该插件进行日志记录:
- 初始化Logger
在你的应用的主入口文件(通常是main.dart
)中,初始化snug_logger
:
import 'package:flutter/material.dart';
import 'package:snug_logger/snug_logger.dart';
void main() {
// 初始化Logger
final logger = SnugLogger.init(
levels: [LogLevel.verbose, LogLevel.debug, LogLevel.info, LogLevel.warn, LogLevel.error],
printers: [
// 你可以添加多个Printer,比如将日志输出到控制台
ConsolePrinter(),
// 你也可以将日志输出到文件(需要额外配置)
// FilePrinter(directory: getApplicationDocumentsDirectory().path),
],
);
// 设置全局Logger
SnugLogger.global = logger;
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: HomeScreen(),
);
}
}
- 使用Logger记录日志
在你的应用的其他部分,你可以使用SnugLogger.global
来记录日志:
import 'package:flutter/material.dart';
import 'package:snug_logger/snug_logger.dart';
class HomeScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Snug Logger Example'),
),
body: Center(
child: ElevatedButton(
onPressed: () {
// 记录不同级别的日志
SnugLogger.global.v('这是一条Verbose日志');
SnugLogger.global.d('这是一条Debug日志');
SnugLogger.global.i('这是一条Info日志');
SnugLogger.global.w('这是一条Warning日志');
SnugLogger.global.e('这是一条Error日志');
},
child: Text('记录日志'),
),
),
);
}
}
- 运行应用
现在,当你运行你的Flutter应用并点击“记录日志”按钮时,你应该能在控制台中看到相应的日志输出。
这个示例展示了如何使用snug_logger
进行基本的日志记录。你可以根据需要进一步配置snug_logger
,比如添加更多的Printer(如将日志发送到远程服务器),或者根据不同的环境(如开发环境和生产环境)启用或禁用不同的日志级别。
希望这个示例能帮助你在Flutter项目中有效地使用snug_logger
进行日志记录!