升级你的Logger(注解+动态代理)

前言

基于Android的Log进行了一层简单的封装,以一个demo的形式呈现。

背景

我们在自定义Log的时候,应该考虑到的几点:

  1. 使用方便(我自己觉得只传递msg的Logger用起来是最舒服);
  2. 统一管理,包括日志类型、level、开关;
  3. 自定义方便,使用者只需添加一个注解就完成了一种类型的Logger;

实现

描述: 利用注解描述一个类型的日志,利用动态代理生成一种日志类型。
直接看demo,简单粗暴:

日志等级枚举:

enum class LogLevel(value: Int) {

    NONE(0), DEBUG(1), INFO(2), ERROR(3);

    private val level: Int = value

    fun isLessThan(levelEnum: LogLevel) = this.level < levelEnum.level

    fun isLessThanOrEqual(levelEnum: LogLevel) = this.level <= levelEnum.level
}

普通的日志类,可以实例化之后使用:

class DSLogger(
    var openLog: Boolean = true,
    var logLevel: LogLevel = LogLevel.DEBUG,
    val name: String = "ds"
) {

    init {
        if (logLevel.isLessThanOrEqual(LogLevel.NONE)) {
            openLog = false
        }
    }

    fun debug(msg: String) : DSLogger {
        if (openLog && logLevel.isLessThan(LogLevel.INFO)) {
            Log.d(name, msg)
        }
        return this
    }

    fun debug(tag: String, msg: String) : DSLogger {
        if (openLog && logLevel.isLessThan(LogLevel.INFO)) {
            Log.d("$name-$tag", msg)
        }
        return this
    }

    //我就不全部粘贴出来了,都是一样的

Config注解,描述一种类型的日志:开关、等级、名称(log前缀):

@Target(AnnotationTarget.FUNCTION)
@Retention(AnnotationRetention.RUNTIME)
annotation class Config(val openLog: Boolean = true,
                        val logLevel: LogLevel = LogLevel.DEBUG,
                        val name: String)

日志接口,利用Config注解添加一种日志类型

interface ILogger {

    @Config(openLog = true, logLevel = LogLevel.DEBUG, name = "def")
    fun default() : DSLogger

    @Config(openLog = true, logLevel = LogLevel.DEBUG, name = "net")
    fun net() : DSLogger

    @Config(openLog = true, logLevel = LogLevel.DEBUG, name = "map")
    fun map() : DSLogger
}

动态代理,Logger的代理类,可以生成和管理所有Logger:

class LoggerManager : InvocationHandler {

    private val loggers = mutableListOf()

    private val defaultLogger = DSLogger()

    private val methodOfLoggers = mutableMapOf()

    init {
        methodOfLoggers["DiverseShow-Logger"] = defaultLogger
        loggers.add(defaultLogger)
    }

    override fun invoke(proxy: Any?, method: Method, args: Array?): Any {
        if (method.returnType != DSLogger::class.java) {
            throw RuntimeException("find ${method.returnType.simpleName} on ${method.name}'s return type, but require BaseLogger.")
        }

        //找到注解,提取注解的value
        val fromMethodName = methodOfLoggers[method.name]
        if (fromMethodName != null) {
            return fromMethodName
        } else {
            var targetAnnotation: Config? = null
            method.annotations.forEach find@ {
                if (it is Config) {
                    targetAnnotation = it
                    return@find
                }
            }
            if (targetAnnotation == null) {
                Log.e("ds", "the ${method.name}() has no annotation which is Config::class ")
                return defaultLogger
            }
            //生成一个新的Logger
            val config = targetAnnotation!!
            val logger = DSLogger(config.openLog, config.logLevel, "ds-${config.name}")
            synchronized(this::class) {
                val checkLogger = methodOfLoggers[method.name]
                if (checkLogger != null) return checkLogger
                methodOfLoggers[method.name] = logger
                loggers.add(logger)
                return logger
            }
        }
    }
}

对上面的那些类封装一层,对外提供日志的能力,DSLog:

object DSLog : ILogger {

    private val loggerManager = LoggerManager()

    private val logger: ILogger = (Proxy.newProxyInstance(DSLogger::class.java.classLoader,
        arrayOf(ILogger::class.java), loggerManager)) as ILogger

    override fun default(): DSLogger = logger.default()

    override fun net(): DSLogger  = logger.net()

    override fun map(): DSLogger = logger.map()

    fun getLoggerManager() = loggerManager
}

使用

//默认日志
DSLog.defalut().debug("hello world!")
DSLog.defalut().debug("myTag","hello world!")
//网络日志
DSLog.net().debug("http failed.")

//关闭所有日志
DSLog.getLoggerManager().closeAllLogger()

demo日志器就做好了,在上面扩展功能也是非常容易的~
欢迎拿去食用~

你可能感兴趣的:(升级你的Logger(注解+动态代理))