How do you get the output written to logcat back into the Flutter app that caused it? Or simpler asked: How to read logcat in Flutter?
The problem is this:
The app uses a stack of Android plugins to communicate with some custom hardware through Bluetooth. Those Android plugins write extensively to logcat. Now, for debugging, it would be very helpful to be able to read all the messages the App (including native plugins) has written to logcat. Question is, is this somehow possible?
How would you tackle that?
CodePudding user response:
Check out the plugin called logcat on pub.dev.
Sadly, it seems to be no longer maintained and isn't updated for null safety. But you can check out the source code here and see how the plugin gets access to the android logcat.
Because the logcat is a native thing, you'll have to use a MethodChannel to call a Java/Kotlin function:
// define MethodChannel
final platform = const MethodChannel('app.channel.logcat');
// call native method
logs = await platform.invokeMethod('execLogcat');
And the native part:
public class LogcatPlugin implements MethodCallHandler {
public static void registerWith(Registrar registrar) {
final MethodChannel channel = new MethodChannel(registrar.messenger(), "app.channel.logcat");
channel.setMethodCallHandler(new LogcatPlugin());
}
@Override
public void onMethodCall(MethodCall call, Result result) {
if (call.method.equals("execLogcat")) {
String logs = getLogs();
if (logs != null) {
result.success(logs);
} else {
result.error("UNAVAILABLE", "logs not available.", null);
}
} else {
result.notImplemented();
}
}
String getLogs() {
try {
Process process = Runtime.getRuntime().exec("logcat -d");
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
StringBuilder log = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
log.append(line);
}
return log.toString();
} catch (IOException e) {
return "EXCEPTION" e.toString();
}
}
}
The code samples are from github.com/pharshdev/logcat. Maybe you can just fork the git repo and migrate it to null safety if needed.
CodePudding user response:
Add Dependency :
dependencies:
logger: ^1.1.0
Example:
import 'package:logger/logger.dart';
var logger = Logger(
printer: PrettyPrinter(),
);
var loggerNoStack = Logger(
printer: PrettyPrinter(methodCount: 0),
);
void main() {
print(
'Run with either `dart example/main.dart` or `dart --enable-asserts example/main.dart`.');
demo();
}
void demo() {
logger.d('Log message with 2 methods');
loggerNoStack.i('Info message');
loggerNoStack.w('Just a warning!');
logger.e('Error! Something bad happened', 'Test Error');
loggerNoStack.v({'key': 5, 'value': 'something'});
Logger(printer: SimplePrinter(colors: true)).v('boom');
}