Flutter网络日志记录插件pretty_http_logger的使用
Flutter网络日志记录插件pretty_http_logger的使用
pretty_http_logger
是一个用于Dart http
库的日志中间件库,它可以帮助开发者轻松地记录HTTP请求和响应信息。以下将详细介绍如何在Flutter项目中使用这个插件。
Getting Started
安装
首先,在你的pubspec.yaml
文件中添加依赖:
dependencies:
pretty_http_logger: any
然后执行flutter pub get
来安装包。
导入
在需要使用的Dart文件中导入该库:
import 'package:pretty_http_logger/pretty_http_logger.dart';
使用pretty_http_logger
创建一个HttpWithMiddleware
对象,并通过build
构造函数传入预构建的中间件列表。这里我们使用HttpLogger
作为中间件,它可以记录请求和响应的内容。
HttpWithMiddleware http = HttpWithMiddleware.build(middlewares: [
HttpLogger(logLevel: LogLevel.BODY),
]);
此时你就可以像平常一样使用这个http
对象发起网络请求了:
// Simple POST request
var response = await http.post(
Uri.parse('https://jsonplaceholder.typicode.com/posts/'),
body: {"testing": "1234"},
);
// Simple GET request
var response = await http.get(
Uri.parse('https://jsonplaceholder.typicode.com/posts/'),
);
请求超时设置
你可以为请求指定超时时间,例如设置请求在30秒内完成:
HttpWithMiddleware http = HttpWithMiddleware.build(
requestTimeout: Duration(seconds: 30),
middlewares: [
HttpLogger(logLevel: LogLevel.BODY),
],
);
对于可能出现的超时异常,你需要捕获并处理:
try {
var response = await http.get(
Uri.parse('https://jsonplaceholder.typicode.com/posts/'),
);
} catch (e) {
if (e is TimeoutException) {
// Timed out
}
}
使用HttpClientWithMiddleware
如果你希望保持与服务器的连接,则可以使用HttpClientWithMiddleware
:
HttpClientWithMiddleware httpClient = HttpClientWithMiddleware.build(
middlewares: [
HttpLogger(logLevel: LogLevel.BODY),
],
);
var response = await httpClient.post(
Uri.parse('https://jsonplaceholder.typicode.com/posts/'),
body: {"testing": "1234"},
);
var response = await httpClient.get(
Uri.parse('https://jsonplaceholder.typicode.com/posts/'),
);
// Don't forget to close the client once done.
httpClient.close();
自定义中间件
你可以通过继承MiddlewareContract
类来自定义中间件逻辑。下面是一个简单的日志记录器示例:
class Logger extends MiddlewareContract {
@override
void interceptRequest(RequestData data) {
print("Method: ${data.method}");
print("Url: ${data.url}");
print("Body: ${data.body}");
}
@override
void interceptResponse(ResponseData data) {
print("Status Code: ${data.statusCode}");
print("Method: ${data.method}");
print("Url: ${data.url}");
print("Body: ${data.body}");
print("Headers: ${data.headers}");
}
@override
void interceptError(err) {
print("Error: $err");
}
}
你还可以修改请求数据或响应数据,例如为每个请求添加特定的头部信息:
class Logger extends MiddlewareContract {
@override
void interceptRequest(RequestData data) {
// Adding content type to every request
data.headers["Content-Type"] = "application/json";
data.body = jsonEncode({
"uniqueId": "some unique id",
"data": data.body,
});
}
@override
void interceptResponse(ResponseData data) {
// Unwrapping response from a structure
data.body = jsonDecode(data.body)["data"];
}
@override
void interceptError(err) {
print("Error: $err");
}
}
示例代码
为了更好地理解如何在实际项目中应用pretty_http_logger
,这里提供了一个完整的示例程序:
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:pretty_http_logger/pretty_http_logger.dart';
void main() async {
final res = await baseRequest.get(Uri.parse('https://jsonplaceholder.typicode.com/todos/1'));
print(jsonDecode(res.body));
/// Observe the request and response log in the console
}
class _BaseRequest {
static final HttpWithMiddleware _httpClient = HttpWithMiddleware.build(
middlewares: [
HttpLogger(logLevel: LogLevel.BODY),
],
);
static final HttpClientWithMiddleware _streamedHttpClient =
HttpClientWithMiddleware.build(
middlewares: [
HttpLogger(logLevel: LogLevel.BODY),
],
);
Future<StreamedResponse> send(http.BaseRequest request) async {
final response = await _streamedHttpClient.send(request);
return response;
}
Future<http.Response> patch(Uri url,
{Map<String, String>? headers, Object? body, Encoding? encoding}) async {
final response = await _httpClient.patch(url, headers: headers);
return response;
}
Future<http.Response> get(Uri url, {Map<String, String>? headers}) async {
final response = await _httpClient.get(url, headers: headers);
return response;
}
Future<http.Response> put(Uri url,
{Map<String, String>? headers, Object? body, Encoding? encoding}) async {
final response = await _httpClient.put(url, headers: headers);
return response;
}
Future<http.Response> post(Uri url,
{Map<String, String>? headers, Object? body, Encoding? encoding}) async {
final response = await _httpClient.post(url, headers: headers, body: body);
return response;
}
Future<http.Response> delete(Uri url,
{Map<String, String>? headers, Object? body, Encoding? encoding}) async {
final response = await _httpClient.delete(url, headers: headers, body: body);
return response;
}
}
final baseRequest = _BaseRequest();
以上就是pretty_http_logger
的基本用法和一些高级特性。通过这些功能,你可以更方便地调试和监控你的网络请求。如果你有任何问题或者建议,欢迎访问GitHub仓库提交issue或pull request。
更多关于Flutter网络日志记录插件pretty_http_logger的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter网络日志记录插件pretty_http_logger的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
当然,以下是如何在Flutter项目中使用pretty_http_logger
插件来进行网络日志记录的代码示例。这个插件能够帮助你优雅地记录HTTP请求和响应的详细信息,非常适合调试和开发阶段使用。
步骤 1: 添加依赖
首先,在你的pubspec.yaml
文件中添加pretty_http_logger
依赖:
dependencies:
flutter:
sdk: flutter
pretty_http_logger: ^0.1.3 # 请注意版本号,根据实际情况使用最新版本
然后运行flutter pub get
来获取依赖。
步骤 2: 配置HTTP客户端
在你的Flutter应用中,配置HTTP客户端以使用pretty_http_logger
。这里以dio
库为例,因为pretty_http_logger
通常与dio
一起使用,但你也可以根据需要使用其他HTTP客户端库。
首先,添加dio
依赖到你的pubspec.yaml
文件中(如果尚未添加):
dependencies:
dio: ^4.0.0 # 请注意版本号,根据实际情况使用最新版本
然后,在你的项目中配置dio
客户端和pretty_http_logger
:
import 'package:dio/dio.dart';
import 'package:pretty_http_logger/pretty_http_logger.dart';
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: HomePage(),
);
}
}
class HomePage extends StatefulWidget {
@override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
late Dio _dio;
@override
void initState() {
super.initState();
// 配置Dio客户端
BaseOptions options = BaseOptions(
baseUrl: 'https://jsonplaceholder.typicode.com/',
headers: {
'Content-Type': 'application/json',
},
);
// 创建PrettyHttpLogger实例
var logger = PrettyHttpLogger(
requestBodyLogger: (requestBody) => print('Request Body: $requestBody'),
responseBodyLogger: (responseBody, responseBodyBytes) =>
print('Response Body: $responseBody'),
);
// 使用拦截器添加日志记录功能
_dio = Dio(options)
..interceptors.add(
InterceptorsWrapper(
onRequest: (RequestOptions options, RequestInterceptorHandler handler) async {
logger.logRequest(options);
return handler.next(options);
},
onResponse: (Response response, ResponseInterceptorHandler handler) async {
logger.logResponse(response);
return handler.next(response);
},
onError: (DioError err, ErrorInterceptorHandler handler) async {
logger.logError(err);
return handler.next(err);
},
),
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Pretty HTTP Logger Demo'),
),
body: Center(
child: ElevatedButton(
onPressed: () async {
try {
Response response = await _dio.get('/posts/1');
print('Response Data: ${response.data}');
} catch (e) {
print('Error: $e');
}
},
child: Text('Fetch Data'),
),
),
);
}
}
说明
- 添加依赖:在
pubspec.yaml
文件中添加pretty_http_logger
和dio
依赖。 - 配置
dio
客户端:创建dio
实例,并通过拦截器添加PrettyHttpLogger
,以便在请求、响应和错误时记录日志。 - 日志记录:
PrettyHttpLogger
提供了logRequest
、logResponse
和logError
方法来分别记录请求、响应和错误信息。 - 按钮触发请求:在UI中添加一个按钮,点击按钮时触发HTTP请求,并打印响应数据。
这样,你就可以在控制台中看到详细的HTTP请求和响应日志,方便调试和开发。