照着 Hugo 实现一个监控方法耗时的插件

1,742 阅读3分钟

背景

Hugo 是 Jake Wharton 大神写的一个监控方法耗时的插件。

1. 接入

在根目录的 build.gradle 中添加

buildscript {
    repositories {
        mavenCentral()
    }

    dependencies {
        classpath 'com.jakewharton.hugo:hugo-plugin:1.2.1'
    }
}

在 app 的 build.gradle 中添加

plugins {
    id 'com.android.application'
    id 'com.jakewharton.hugo'
}

2. 使用

@DebugLog
public String getName(String first, String last) {
  SystemClock.sleep(15); // Don't ever really do this!
  return first + " " + last;
}

在方法上添加 @DebugLog 的注解,就可以在输出窗口看到相关 Log(方法参数,方法耗时及方法返回值)。

V/Example: ⇢ getName(first="Jake", last="Wharton")
V/Example: ⇠ getName [16ms] = "Jake Wharton"

3. 问题

这个插件已经 7 年没有更新了,gradle 里的一些 api 已经不能使用,因此按照上述方法接入,会编译不过。即在 app 的 build.gradle 中添加 plugin 就会 sync 失败,具体错误如下:

image.png 查看 Hugo 的源码发现代码量特别少,因此我们完全可以照着源码自己写一个插件。

创建项目

1. 创建一个 Android 的 project,并 clone 下 Hugo 的源码。

2. 从 Hugo 项目中 copy hugo-annotations 到新项目中,修改 module 中的 build.gradle 文件如下

apply plugin: 'java'

targetCompatibility = JavaVersion.VERSION_1_8
sourceCompatibility = JavaVersion.VERSION_1_8

这样第一个 library 就可以编译成功了。

3. 从 Hugo 项目中 copy hugo-runtime 到新项目中,修改 build.gradle 如下:

在 apply plugin 前加入如下代码,不然 import 导包找不到文件

buildscript {
  repositories {
    mavenCentral()
  }
  dependencies {
    classpath 'org.aspectj:aspectjtools:1.9.6'
    classpath 'org.aspectj:aspectjweaver:1.9.6'
  }
}

去掉以下插件引用,因为我们并不使用这个插件上传仓库

apply plugin: 'com.github.dcendents.android-maven'

整个 build.gradle 文件如下

import org.aspectj.bridge.IMessage
import org.aspectj.bridge.MessageHandler
import org.aspectj.tools.ajc.Main

buildscript {
  repositories {
    mavenCentral()
  }
  dependencies {
    classpath 'org.aspectj:aspectjtools:1.9.6'
    classpath 'org.aspectj:aspectjweaver:1.9.6'
  }
}

apply plugin: 'com.android.library'

dependencies {
  implementation 'org.aspectj:aspectjweaver:1.9.6'
  implementation project(':hugo-annotations')

  testImplementation 'junit:junit:4.13.2'
}

android {
  compileSdkVersion 32

  compileOptions {
    sourceCompatibility JavaVersion.VERSION_1_8
    targetCompatibility JavaVersion.VERSION_1_8
  }
}

android.libraryVariants.all { variant ->
  JavaCompile javaCompile = variant.javaCompile
  javaCompile.doLast {
    String[] args = [
        "-showWeaveInfo",
        "-1.5",
        "-inpath", javaCompile.destinationDir.toString(),
        "-aspectpath", javaCompile.classpath.asPath,
        "-d", javaCompile.destinationDir.toString(),
        "-classpath", javaCompile.classpath.asPath,
        "-bootclasspath", android.bootClasspath.join(File.pathSeparator)
    ]

    MessageHandler handler = new MessageHandler(true);
    new Main().run(args, handler)

    def log = project.logger
    for (IMessage message : handler.getMessages(null, true)) {
      switch (message.getKind()) {
        case IMessage.ABORT:
        case IMessage.ERROR:
        case IMessage.FAIL:
          log.error message.message, message.thrown
          break;
        case IMessage.WARNING:
        case IMessage.INFO:
          log.info message.message, message.thrown
          break;
        case IMessage.DEBUG:
          log.debug message.message, message.thrown
          break;
      }
    }
  }
}

这样插桩的 Library 也编译成功了。接下来最后一步就是生成 gradle 插件了。

4. 从 Hugo 项目中 copy hugo-plugin 到新项目中,修改 build.gradle 如下:

apply plugin: 'groovy'

targetCompatibility = JavaVersion.VERSION_1_8
sourceCompatibility = JavaVersion.VERSION_1_8

dependencies {
  implementation gradleApi()
  implementation localGroovy()
  implementation 'com.android.tools.build:gradle:7.2.2' // gradle 相关 api
  implementation 'org.aspectj:aspectjtools:1.9.6'
  implementation 'org.aspectj:aspectjrt:1.9.6'
}

如果 gradle 文件找不到,看下自己的 gradle 版本,我当前的是

distributionUrl=https://services.gradle.org/distributions/gradle-7.3.3-bin.zip

5. 修改 HugoPlugin 文件

Hugo项目编译不过就是因为在 HugoPlugin 文件中使用了废弃的 debugCompile

project.dependencies {
  debugCompile 'com.jakewharton.hugo:hugo-runtime:1.2.2-SNAPSHOT'
  // TODO this should come transitively
  debugCompile 'org.aspectj:aspectjrt:1.8.6'
  compile 'com.jakewharton.hugo:hugo-annotations:1.2.2-SNAPSHOT'
}

因此把这部分代码改成如下

project.dependencies {
  debugImplementation 'com.jakewharton.hugo:hugo-runtime:1.2.1'
  // TODO this should come transitively
  debugImplementation 'org.aspectj:aspectjrt:1.8.6'
  implementation 'com.jakewharton.hugo:hugo-annotations:1.2.1'
}

6. 生成本地插件

在 hugo-plugin 的 build.gradle 中添加 Java Gradle Plugin 插件及 publish 插件

apply plugin: 'java-gradle-plugin' // Java Gradle Plugin
apply plugin: 'maven-publish'
gradlePlugin {
  plugins {
    Plugin {
      id = 'com.example.plugin'  // apply 的时候使用的
      implementationClass = 'hugo.weaving.plugin.HugoPlugin' // 具体的实现类
    }
  }
}

group = 'com.example.plugin'
version = '0.0.1'

publishing {
  repositories {
//        本地路径
        maven {
            url = uri('../localMavenRepository/snapshot')
        }
  }
}

然后点击右侧的 gradle,点击 publish

image.png 会在左侧生成 localMavenRepository/snapshot 文件夹

image.png 绿框就是我们要使用的插件。

使用

在项目的 setting.gradle 中添加

pluginManagement {
    repositories {
        gradlePluginPortal()
        google()
        mavenCentral()
        // 本地仓库名
        maven {
            url "$rootDir/localMavenRepository/snapshot"
        }
    }

}

在项目的 build.gradle 中添加

buildscript {
    dependencies {
        classpath 'com.example.plugin:hugo-plugin:0.0.1'
    }
}

在 app 的 build.gradle 中添加

plugins {
    id 'com.example.plugin'
}

最后在代码中验证

@DebugLog
private void sleep() {
  try {
    Thread.sleep(200);
  } catch (InterruptedException e) {
    e.printStackTrace();
  }
}

log 如下

V/MainActivity: ⇢ sleep()
V/MainActivity: ⇠ sleep [200ms]

总结

到目前为止就实现了一个本地的 gradle 插件。目前存在的问题是,HugoPlugin 文件中引用的都是远程的代码,即

project.dependencies {
  debugImplementation 'com.jakewharton.hugo:hugo-runtime:1.2.1'
  // TODO this should come transitively
  debugImplementation 'org.aspectj:aspectjrt:1.8.6'
  implementation 'com.jakewharton.hugo:hugo-annotations:1.2.1'
}

因此我们改动这两个 module 并没有什么用。解决办法是上传这两个 module,然后在 HugoPlugin 中引用我们上传的 module。完成这一步也就可以完成 gradle 插件上传远端了。