FlutterXLogPlugin.ets 2.3 KB
import {
  FlutterPlugin,
  FlutterPluginBinding,
  MethodCall,
  MethodCallHandler,
  MethodChannel,
  MethodResult,
} from '@ohos/flutter_ohos';

import common from '@ohos.app.ability.common';
import { AppednerMode, CompressLevel, CompressMode, XLog } from '../xlog/XLog';
import { Log } from '../xlog/Log';

/** MMKVPlugin **/
export default class FlutterXLogPlugin implements FlutterPlugin, MethodCallHandler {
  private channel: MethodChannel | null = null;
  private context: common.Context | null = null;
  private xlog: XLog = new XLog();

  constructor(context?: common.Context) {
    // hilog.info(0x0000, 'start', 'MMKVPlugin constructor: %{public}s', context);
    if (context) {
      this.context = context;
    }
  }

  getUniqueClassName(): string {
    return "FlutterXLogPlugin"
  }

  onAttachedToEngine(binding: FlutterPluginBinding): void {
    this.channel = new MethodChannel(binding.getBinaryMessenger(), "flutter_xlog");
    this.channel.setMethodCallHandler(this)

    this.context = binding.getApplicationContext();
    // hilog.info(0x0000, 'start', 'MMKVPlugin onAttachedToEngine: %{public}s', this.context);
  }

  onDetachedFromEngine(binding: FlutterPluginBinding): void {
    if (this.channel != null) {
      this.channel.setMethodCallHandler(null)
    }
  }

  onMethodCall(call: MethodCall, result: MethodResult): void {
    if (call.method == "open") {
      let level = call.argument("level") as number;
      let cacheDir = call.argument("cacheDir") as string;
      let logDir = call.argument("logDir") as string;
      let namePrefix = call.argument("namePrefix") as string;
      let cacheDays = call.argument("cacheDays") as number;
      let pubKey = call.argument("pubKey") as string;
      let consoleLogOpen = call.argument("consoleLogOpen") as boolean;
      Log.setLogImp(this.xlog);
      Log.setLevel(level);
      Log.setConsoleLogOpen(consoleLogOpen);
      XLog.appenderOpen(level, AppednerMode.AppednerModeAsync, cacheDir, logDir, namePrefix, cacheDays, pubKey,
        CompressMode.ZLIB_MODE, CompressLevel.COMPRESS_LEVEL0);
      result.success(null);
    } else if (call.method == "flush") {
      Log.appenderFlush(true);
      result.success(null);
    } else if (call.method == "close") {
      Log.appenderClose()
      result.success(null);
    } else {
      result.notImplemented()
    }
  }
}