패키지, 저장소 및 앱 카테고리 검색

패키지 상세v1.0.5

pretty_http_logger

프리티 HTTP 로거는 네트워크 호출을 예쁘고 읽기 쉬운 형식으로 로깅하고 네트워크 호출을 가로챌 수 있는 Dart HTTP 라이브러리용 미들웨어 로거 라이브러리입니다.

AndroidiOSWebmacOSWindowsLinux
30일 다운로드
4.7천
좋아요
20
Pub 점수
150

패키지 설치

flutter pub add pretty_http_logger

패키지 개요

공개 정보를 바탕으로 생성한 선택 가이드입니다.

Pretty Http Logger는 HTTP 네트워크 요청과 응답에 대해 깔끔하고 가독성 높은 형식으로 로깅을 제공하는 Dart 패키지입니다. Dart의 HTTP 클라이언트와 원활하게 통합되어 개발자가 API 상호작용을 쉽게 모니터링하고 디버그할 수 있도록 합니다. 네트워크 호출을 가로채는 기능을 지원하여 개발 중 요청과 응답을 보다 세밀하게 검사하고 수정할 수 있습니다. Android, iOS, Web, macOS, Windows, Linux 등 모든 주요 플랫폼에서 지원되므로 크로스플랫폼 앱에서 투명한 네트워크 로깅이 필요한 경우에 이상적입니다.

사용 사례

  • API 문제 디버깅
  • 네트워크 성능 모니터링
  • 요청/응답 데이터 검사
  • API 통합 테스트
  • 개발 워크플로우 향상
  • 생산 환경에서 로그인하기

주요 기능

  • 포맷팅된 HTTP 로그
  • 요청/응답 가로채기
  • 크로스 플랫폼 호환성
  • http 패키지와의 간편한 통합
  • 사용자 정의 로그 형식
  • 동기 및 비동기 호출을 모두 지원합니다

적합한 대상

  • 크로스 플랫폼 앱을 개발하는 개발자
  • 세부 네트워크 디버깅이 필요한 팀
  • API를 사용하는 프론트엔드 엔지니어
  • 테스터가 API 동작을 검증하고 있습니다
  • 투명한 네트워크 모니터링이 필요한 응용 프로그램

고려 사항

  • 민감한 데이터를 필터링하지 않고 프로덕션 환경에서 사용하지 마십시오
  • 과도한 데이터를 로깅할 경우 성능에 영향을 미칠 수 있습니다
  • 혼잡한 로그를 방지하기 위해 적절한 구성이 필요합니다
  • 고주파 로깅 시나리오에 적합하지 않습니다
  • 보안을 위해 릴리스 빌드에서는 비활성화되어야 합니다

원본 README

연결된 소스 저장소의 README 원문 스냅샷입니다. 최신 내용은 저장소에서 확인하세요.

pretty_http_logger

A middleware logger library for Dart http library.

Getting Started

pretty_http_logger is a module that lets you log request and response for Dart's http package.

Installing

Include this library in your package.

pretty_http_logger: any
Importing
import 'package:pretty_http_logger/pretty_http_logger.dart';
Using pretty_http_logger

Create an object of HttpWithMiddleware by using the build factory constructor.

The build constructor takes in a list of middlewares that are built already by pretty_http_logger.

(You can also build your own middleware for pretty_http_logger. Check out Build your own middleware)
HttpWithMiddleware http = HttpWithMiddleware.build(middlewares: [
    HttpLogger(logLevel: LogLevel.BODY),
]);

That is it! Now go ahead and use this http object as you would normally do.

//Simple POST request
var response = await http.post('https://jsonplaceholder.typicode.com/posts/',
    body: {"testing", "1234"});

//Simple GET request
var response = await http.get('https://jsonplaceholder.typicode.com/posts/');

/// Simple Multipart Request
final request = MultipartRequest('POST', Uri.parse('YOUR_URL'));
request.fields['category_id'] = '1';
request.headers.addAll({'Authorization': 'YOUR_AUTH_TOKEN'});
final file = await MultipartFile.fromPath(
"images[0]",
"image_picker_632B42C0-11AF-4075-90F8-A7FCD48A7FC0-27133-0000014E3B2E5959.png",
contentType: MediaType("image", "jpg"),
);
request.files.add(file);
final response = await http.multipart(request);
Request Timeout

With pretty_http_logger you can also specify the timeout of requests. So if you want a request to be timeout in 30 seconds:

HttpWithMiddleware http = HttpWithMiddleware.build(
  requestTimeout: Duration(seconds: 30),
  middlewares: [
    HttpLogger(logLevel: LogLevel.BODY),
]);

HttpWithMiddleware supports all the functions that http provides.

http.get(...);
http.post(...);
http.put(...);
http.delete(...);
http.head(...);
http.patch(...);
http.read(...);
http.readBytes(...);
Using a Client

If you want to use a http.Client in order to keep the connection alive with the server, use HttpClientWithMiddleware.

HttpClientWithMiddleware httpClient = HttpClientWithMiddleware.build(middlewares: [
    HttpLogger(logLevel: LogLevel.BODY),
]);

var response = await httpClient.post('https://jsonplaceholder.typicode.com/posts/',
    body: {"testing", "1234"});

var response = await httpClient.get('https://jsonplaceholder.typicode.com/posts/');

//Don't forget to close the client once done.
httpClient.close();
Building your own middleware

Building your own middleware with pretty_http_logger is very easy, whether you want to create a package for pretty_http_logger or you want to build a middleware solely for your own project.

Once you have the necessary imports, all you have to do is extend the MiddlewareContract class which will give you access to 3 functions.

interceptRequest(RequestData) is the method called before any request is made. interceptResponse(ResponseData) is the method called after the response from request is received. interceptError(error) is the method called when an exception occurs.

You can then @override all the required functions you need to add middleware to.

Example (A simple logger that logs data in all requests):

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");
  }
}

You can also modify the RequestData before the request is made and every ResponseData after every response is received. For Example, if you want to wrap your data in a particular structure before sending, or you want every request header to have Content-Type set to application/json.

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");
  }
}
Package pretty_http_logger is inspired by
  • pretty_http_logger(https://github.com/mithunadhikari40/pretty_http_logger) : Easy request and response logging.
  • pretty_http_logger is inspired by http_logger(https://github.com/gurleensethi/http_logger)
  • pretty_http_logger is inspired by http_middleware(https://github.com/TEDConsulting/http_middleware)
  • pretty_http_logger is inspired by pretty_dio_logger(https://github.com/Milad-Akarie/pretty_dio_logger)
  • pretty_http_logger is a combination of packages mentioned above and uses the code provided by these libraries and keeps everything up to date

If you find any issues or suggestions pretty_http_logger, open an issue or raise a PR, I will be happy to see.

카테고리

의존성

의존성 목록 1 개

소스 저장소

이 패키지를 사용하는 프로젝트