Detailed explanation of custom log printing component of flutter

Time:2021-6-30

In flutter, if we need to print logs, if we don’t customize them, we can only use our ownprint()perhapsdebugPrint()Method to print, but the log is the default for both types of printingInfoHierarchical logs are very unfriendly, so if we need to print logs with distinct levels, we need to customize a log printing component. Here’s how to customize the log printing component.

How to make the output log hierarchical?

In another way, if we can call the log component in the original Android in the flutter code, won’t we be able to solve the problem of log printing?

How to associate

In flutter, you can useMethodChannelTo make flutter call the relevant API of specific platform (such as Android and IOS), forMethodChannelPlease refer to the official document: Click to view.

Here is a brief explanation. The API of flutter for a specific platform mainly depends on its flexible message passing mode, rather than a complete set of code generation. What do you mean?

  • Flutter can send messages to its hosts (Android and IOS) through platform channel;
  • Its host monitors the channel of platform and receives the message sent;
  • The host platform executes the host specific API through the received message, and then returns the response result to the client (that is, the flutter part) to update the status.

The following is a brief code Description:

Step1: create a flutter platform client

import 'package:flutter/services.dart';

///A log printing tool class
class LogUtils {
 LogUtils._();

 //Step 1: set the platform and name it
 static const _platform = const MethodChannel('com.yancy.flutter.plugins/log');

 //The second step is to set the method to be passed
 //The first required parameter of the parameter received by the invokemethod method is the name of the method; The following parameters are optional and need to be passed
 static void i(String tag, String msg) {
 _platform.invokeMethod('logI', {'tag': tag, 'msg': msg});
 }

 static void d(String tag, String msg) {
 _platform.invokeMethod('logD', {'tag': tag, 'msg': msg});
 }

 static void v(String tag, String msg) {
 _platform.invokeMethod('logV', {'tag': tag, 'msg': msg});
 }

 static void w(String tag, String msg) {
 _platform.invokeMethod('logW', {'tag': tag, 'msg': msg});
 }

 static void e(String tag, String msg) {
 _platform.invokeMethod('logE', {'tag': tag, 'msg': msg});
 }

}

Step2: the host side establishes the corresponding channel and the receiver side

package com.yancy.flutter.host;

import android.content.Context;
import android.util.Log;
import android.widget.Toast;

import io.flutter.plugin.common.BinaryMessenger;
import io.flutter.plugin.common.MethodChannel;

/**
 *Note:
 *
 * @author Yancy
 * @date 2019/3/15
 */
public class CustomFlutterPlugins {
 
 //It must be corresponding to the name of the flutter platform, otherwise the message cannot be received
 private static final String LOG_CHANNEL_NAME = "com.yancy.flutter.plugins/log";

 public static void registerLogger(BinaryMessenger messenger) {
  new MethodChannel(messenger, LOG_CHANNEL_NAME).setMethodCallHandler((methodCall, result) -> {
   String tag = methodCall.argument("tag");
   String msg = methodCall.argument("msg");
   switch (methodCall.method) {
    case "logV":
     Log.v(tag, msg);
     break;
    case "logD":
     Log.d(tag, msg);
     break;
    case "logI":
     Log.i(tag, msg);
     break;
    case "logW":
     Log.w(tag, msg);
     break;
    case "logE":
     Log.e(tag, msg);
     break;
    default:
     Log.d(tag, msg);
     break;
   }
  });
 }
}

aboveswitchThe inner part is for the flitterinvokeMethodMethod.

Step3: and then we’re in the host’s MainActivityThe channel can be established by calling and registering in.


public class MainActivity extends FlutterActivity {
 @Override
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 GeneratedPluginRegistrant.registerWith(this);

 CustomFlutterPlugins.registerLogger(getFlutterView());
 }
}

Step4Flutter calls LogUtils related method to print logs.


class MyApp extends StatelessWidget {

 @override
 Widget build(BuildContext context) {
 print('print------');
 debugPrint('debugPrint-----');
 LogUtils.v('yancy', 'v-------');
 LogUtils.d('yancy', 'd-------');
 LogUtils.i('yancy', 'i-------');
 LogUtils.w('yancy', 'w-------');
 LogUtils.e('yancy', 'e-------');

 return MaterialApp(
  title: 'Flutter Demo',
  theme: ThemeData(
  primarySwatch: Colors.blue,
  ),

  home: MyHomePage(title: 'Flutter Demo Home Page'),
 );
 }
}

The printing results of the console output are as follows:

At this point, a simple log printing set-up has been developed. I hope it will be helpful to your study and support developer.

Recommended Today

Install mongodb using yum

Mongodb series: Install mongodb using yum Command operation of mongodb Programming operation of mongodb Install mongodb using Yum in CentOS 7. The installation package may not be the latest, but it must be the most stable. The advantages of Yum installation are simple, time-saving, labor-saving and efficient. If you want to install the latest version […]