这是indexloc提供的服务,不要输入任何密码
Skip to content

Add a gRPC logger (Restored) #389

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions packages/talker_grpc_logger/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
# https://dart.dev/guides/libraries/private-files
# Created by `dart pub`
.dart_tool/

# Avoid committing pubspec.lock for library packages; see
# https://dart.dev/guides/libraries/private-files#pubspeclock.
pubspec.lock
3 changes: 3 additions & 0 deletions packages/talker_grpc_logger/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
## 1.0.0

- Initial version.
99 changes: 99 additions & 0 deletions packages/talker_grpc_logger/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
# talker_grpc_logger
Lightweight and customizable [grpc](https://pub.dev/packages/grpc) client logger on [talker](https://pub.dev/packages/talker) base.<br>
[Talker](https://github.com/Frezyx/talker) - Advanced exception handling and logging for dart/flutter applications 🚀

## Preview
This is how the logs of your grpc requests will look in the console
![](preview.jpg)


## Note

At the moment, only unary RPCs are supported. Streaming RPCs will probably
be added in the future. Contributions are welcome!


## Usage

Create an interceptor and instrument your RPC client:

```dart
import 'package:grpc/grpc.dart';
import 'package:grpc/grpc_or_grpcweb.dart';
import 'package:talker_flutter/talker_flutter.dart';
import 'package:talker_grpc_logger/talker_grpc_logger.dart';

void main() {
// Define port and host as you see fit
var host = 'localhost';
var port = 50051;

// transportSecure needs to be true when talking to a server through TLS.
// This can be disabled for local development.
// GrpcOrGrpcWebClientChannel is a channel type compatible with web and native. There
// are other channel types available for each platform.
late final channel = GrpcOrGrpcWebClientChannel.toSingleEndpoint(
host: host,
port: port,
transportSecure: host == 'localhost' ? false : true);


final List<ClientInterceptor> interceptors = [
TalkerGrpcLogger()
];

// Generate your RPC client as usual, and use the interceptor to log the requests and responses.
late final rpcClient = YourRPCClient(channel, interceptors: interceptors);
}
```


## Usage with Talker

Very similar to the section above, just pass a Talker instance to the interceptor:

```dart
import 'package:grpc/grpc.dart';
import 'package:grpc/grpc_or_grpcweb.dart';
import 'package:talker_flutter/talker_flutter.dart';
import 'package:talker_grpc_logger/talker_grpc_logger.dart';

void main() {
// Not mandatory, but useful to see the grpc logs in the Talker screen
final talker = TalkerFlutter.init();

// Define port and host as you see fit
var host = 'localhost';
var port = 50051;

// transportSecure needs to be true when talking to a server through TLS.
// This can be disabled for local development.
// GrpcOrGrpcWebClientChannel is a channel type compatible with web and native. There
// are other channel types available for each platform.
late final channel = GrpcOrGrpcWebClientChannel.toSingleEndpoint(
host: host,
port: port,
transportSecure: host == 'localhost' ? false : true);


final List<ClientInterceptor> interceptors = [
TalkerGrpcLogger(talker: talker)
];

// Generate your RPC client as usual, and use the interceptor to log the requests and responses.
late final rpcClient = YourRPCClient(channel, interceptors: interceptors);
}
```


## Token obfuscation

`TalkerGrpcLogger` will obfuscate bearer tokens by default. It'll look at the
metadata of the request and obfuscate the `authorization` header. It'll look
like `Bearer [obfuscated]` in the logs. It is highly recommended to keep this
option enabled. If you want to disable it, you can pass `obfuscateToken:
false`:

```dart
TalkerGrpcLogger(talker: talker, obfuscateToken: true)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

issue: Code snippet shows enabling obfuscation, not disabling as described.

Update the code snippet to use obfuscateToken: false to match the description above.

```
30 changes: 30 additions & 0 deletions packages/talker_grpc_logger/analysis_options.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
# This file configures the static analysis results for your project (errors,
# warnings, and lints).
#
# This enables the 'recommended' set of lints from `package:lints`.
# This set helps identify many issues that may lead to problems when running
# or consuming Dart code, and enforces writing Dart using a single, idiomatic
# style and format.
#
# If you want a smaller set of lints you can change this to specify
# 'package:lints/core.yaml'. These are just the most critical lints
# (the recommended set includes the core lints).
# The core lints are also what is used by pub.dev for scoring packages.

include: package:lints/recommended.yaml

# Uncomment the following section to specify additional rules.

# linter:
# rules:
# - camel_case_types

# analyzer:
# exclude:
# - path/to/excluded/files/**

# For more information about the core and recommended set of lints, see
# https://dart.dev/go/core-lints

# For additional information about configuring this file, see
# https://dart.dev/guides/language/analysis-options
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import 'package:grpc/grpc.dart';
import 'package:grpc/grpc_or_grpcweb.dart';
import 'package:talker_flutter/talker_flutter.dart';
import 'package:talker_grpc_logger/talker_grpc_logger.dart';

void main() {
// Not mandatory, but useful to see the grpc logs in the Talker screen
final talker = TalkerFlutter.init();

// Define port and host as you see fit
var host = 'localhost';
var port = 50051;

// transportSecure needs to be true when talking to a server through TLS.
// This can be disabled for local development.
// GrpcOrGrpcWebClientChannel is a channel type compatible with web and native. There
// are other channel types available for each platform.
late final channel = GrpcOrGrpcWebClientChannel.toSingleEndpoint(
host: host,
port: port,
transportSecure: host == 'localhost' ? false : true);


final List<ClientInterceptor> interceptors = [
TalkerGrpcLogger(talker: talker)
];

// Generate your RPC client as usual, and use the interceptor to log the requests and responses.
late final rpcClient = YourRPCClient(channel, interceptors: interceptors);
}
139 changes: 139 additions & 0 deletions packages/talker_grpc_logger/lib/src/grpc_logs.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,139 @@
import 'dart:convert';

import 'package:grpc/grpc.dart';
import 'package:talker/talker.dart';

const encoder = JsonEncoder.withIndent(' ');

class GrpcRequestLog<Q, R> extends TalkerLog {
GrpcRequestLog(
String title, {
required this.method,
required this.request,
required this.options,
this.obfuscateToken = true,
}) : super(title);

final ClientMethod<Q, R> method;
final Q request;
final CallOptions options;
final bool obfuscateToken;

@override
AnsiPen get pen => (AnsiPen()..xterm(219));

@override
String get title => 'grpc-request';

@override
String generateTextMessage() {
var time = TalkerDateTimeFormatter(DateTime.now()).timeAndSeconds;
var msg = '[$title] | $time | [${method.path}]';

msg += '\nRequest: ${request.toString().replaceAll("\n", " ")}';

// Add the headers to the log message, but obfuscate the token if
// necessary.
final Map<String, String> headers = {};
options.metadata.forEach((key, value) {
if (obfuscateToken && key.toLowerCase() == 'authorization') {
headers[key] = 'Bearer [obfuscated]';
} else {
headers[key] = value;
}
});
Comment on lines +38 to +44
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

issue (bug_risk): Assumes all metadata values are strings, which may not always be the case.

gRPC metadata values can be non-strings (e.g., List), so this code may fail or log incorrectly if such values are present. Please add type checks or handle non-string values appropriately.


try {
if (headers.isNotEmpty) {
final prettyHeaders = encoder.convert(headers);
msg += '\nHeaders: $prettyHeaders';
}
} catch (_) {
// TODO: add handling can`t convert
}
return msg;
Comment on lines +51 to +54
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion (bug_risk): Catching all exceptions without handling or logging may obscure errors.

Please log the exception or provide a fallback message in the catch block to aid debugging if header conversion fails.

Suggested change
} catch (_) {
// TODO: add handling can`t convert
}
return msg;
} catch (e, stackTrace) {
msg += '\nHeaders: <Failed to convert headers: $e>';
// Optionally, log the stack trace if a logger is available:
// logger.error('Failed to convert headers', e, stackTrace);
}
return msg;

}
}

class GrpcErrorLog<Q, R> extends TalkerLog {
GrpcErrorLog(
String title, {
required this.method,
required this.request,
required this.options,
required this.grpcError,
required this.durationMs,
this.obfuscateToken = true,
}) : super(title);

final ClientMethod<Q, R> method;
final Q request;
final CallOptions options;
final GrpcError grpcError;
final int durationMs;
final bool obfuscateToken;

@override
AnsiPen get pen => (AnsiPen()..red());

@override
String get title => 'grpc-error';

@override
String generateTextMessage() {
var time = TalkerDateTimeFormatter(DateTime.now()).timeAndSeconds;
var msg = '[$title] | $time | [${method.path}]';
msg += '\nDuration: $durationMs ms';
msg += '\nError code: ${grpcError.codeName}';
msg += '\nError message: ${grpcError.message}';
msg += '\nRequest: ${request.toString().replaceAll("\n", " ")}';

// Add the headers to the log message, but obfuscate the token if
// necessary.
final Map<String, String> headers = {};
options.metadata.forEach((key, value) {
if (obfuscateToken && key.toLowerCase() == 'authorization') {
headers[key] = 'Bearer [obfuscated]';
} else {
headers[key] = value;
}
});

try {
if (headers.isNotEmpty) {
final prettyHeaders = encoder.convert(headers);
msg += '\nHeaders: $prettyHeaders';
}
} catch (_) {
// TODO: add handling can`t convert
}
return msg;
}
}

class GrpcResponseLog<Q, R> extends TalkerLog {
GrpcResponseLog(
String title, {
required this.method,
required this.response,
required this.durationMs,
}) : super(title);

final ClientMethod<Q, R> method;
final R response;
final int durationMs;

@override
AnsiPen get pen => (AnsiPen()..xterm(46));

@override
String get title => 'grpc-response';

@override
String generateTextMessage() {
var time = TalkerDateTimeFormatter(DateTime.now()).timeAndSeconds;
var msg = '[$title] | $time | [${method.path}]';
msg += '\nDuration: $durationMs ms';
return msg;
}
}
57 changes: 57 additions & 0 deletions packages/talker_grpc_logger/lib/src/talker_grpc_logger_base.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
/// Implements a gRPC interceptor that logs requests and responses to Talker.
/// https://pub.dev/documentation/grpc/latest/grpc/ClientInterceptor-class.html
import 'package:talker/talker.dart';
import 'package:grpc/grpc.dart';

import 'grpc_logs.dart';


class TalkerGrpcLogger extends ClientInterceptor {
TalkerGrpcLogger({Talker? talker, this.obfuscateToken = true}) {
_talker = talker ?? Talker();
}

late Talker _talker;
final bool obfuscateToken;

@override
ResponseFuture<R> interceptUnary<Q, R>(ClientMethod<Q, R> method, Q request,
CallOptions options, ClientUnaryInvoker<Q, R> invoker) {
_talker.logTyped(GrpcRequestLog(method.path,
method: method,
request: request,
options: options,
obfuscateToken: obfuscateToken));

DateTime startTime = DateTime.now();
final response = invoker(method, request, options);

response.then((r) {
Duration elapsedTime = DateTime.now().difference(startTime);
_talker.logTyped(GrpcResponseLog(method.path,
method: method, response: r, durationMs: elapsedTime.inMilliseconds));
}).catchError((e) {
Comment on lines +29 to +33
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

issue (bug_risk): Error handling assumes all errors are GrpcError instances.

If 'e' is not a GrpcError, passing it directly to GrpcErrorLog may cause a runtime error. Please add a type check and handle unexpected error types accordingly.

Duration elapsedTime = DateTime.now().difference(startTime);
_talker.logTyped(GrpcErrorLog(method.path,
method: method,
request: request,
options: options,
grpcError: e,
durationMs: elapsedTime.inMilliseconds,
obfuscateToken: obfuscateToken));
});
return response;
}

@override
ResponseStream<R> interceptStreaming<Q, R>(
ClientMethod<Q, R> method,
Stream<Q> requests,
CallOptions options,
ClientStreamingInvoker<Q, R> invoker) {
print('interceptStreaming');
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nitpick: Debug print statement left in production code.

Please remove the print statement or replace it with appropriate logging if necessary.


return invoker(method, requests, options);
}
}

3 changes: 3 additions & 0 deletions packages/talker_grpc_logger/lib/talker_grpc_logger.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
library talker_grpc_logger;

export 'src/talker_grpc_logger_base.dart';
Binary file added packages/talker_grpc_logger/preview.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
17 changes: 17 additions & 0 deletions packages/talker_grpc_logger/pubspec.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
name: talker_grpc_logger
description: A starting point for Dart libraries or applications.
version: 1.0.0
# repository: https://github.com/my_org/my_repo

environment:
sdk: ^3.2.6

# Add regular dependencies here.
dependencies:
grpc: ^3.2.4
talker: ^4.0.3
# path: ^1.8.0

dev_dependencies:
lints: ^2.1.0
test: ^1.24.0
Loading