Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

🍯 Awesome log aggregator powered by Kotlin Multiplatform

License

NotificationsYou must be signed in to change notification settings

cookpad/puree-kmp

 
 

Repository files navigation

Puree-KMP is a structured logging library for Kotlin Multiplatform (KMP) applications, supporting both Android and iOSplatforms. It provides a flexible and extensible framework for capturing, processing, and routing logs to variousdestinations.

Features

  • Cross-Platform: Works seamlessly on both Android and iOS
  • Filtering: Log entries can be processed before being sent. You can add common parameters, do random sampling, ...
  • Buffering: Log entries are stored in a buffer until it's time to send them.
  • Batching: Multiple log entries are grouped and sent in one request.
  • Retrying: Automatically retry to send after some backoff time if a transmission error occurred.

Platform Support

PlatformSupport
Android✅ Supported
iOS✅ Supported
JVM🔲 Planing
Desktop🔲 Planing
Web❌ Not Supported

Installation

Android

dependencies {    implementation("com.cookpad.puree:puree-kmp:$latestVersion")}

iOS

Distributed throughSwift Package Manager.You can install directly from Xcode by specifying the URL for this repository.

Usage

Note: If you want to know how to use the library in more detail, please take a look at the demo app. There are separateversions for Android and iOS.

1. Define Log Classes

Create data classes that implementPureeLog:

// Kotlin@Serializabledata classClickLog(    @SerialName("button_name")valbuttonName:String,) : PureeLog
// SwiftclassClickLog:PureeLog,Encodable{letbuttonName:Stringinit(buttonName:String){self.buttonName= buttonName}}

When creating log classes in swift, you need to useclass instead ofstruct. This is due to Kotlin Native's specification thatstruct cannot conform to protocols written in KMP.

FYI:JetBrains/kotlin-native#2975

2. Define filter / output

Filter

Implement thePureeFilter interface to create custom filters:

// KotlinclassAddTimeFilter :PureeFilter {overridefunapplyFilter(log:JsonObject):JsonObject {        buildJsonObject {            put("time",System.currentTimeMillis())            put("device_id",UUID.randomUUID().toString())        }.also {returnJsonObject(log+ it)        }    }}
// SwiftclassAddTimeFilter:PureeFilter{func applyFilter(log:String)->String?{guardvar json=parseJSON(log)else{return log}json["time"]=ISO8601DateFormatter().string(from:Date())returnstringifyJSON(json)?? log}}

Output

Implement thePureeOutput interface to output logs:

// KotlinclassLogcatOutput :PureeOutput {overridefunemit(log:JsonObject) {Log.d("Puree", log.toString())    }}
// SwiftclassOSLogOutput:PureeOutput{func emit(log:String){os_log("Puree: %s", log: osLogger, type:.debug, log)}}

ExtendPureeBufferedOutput for batch processing:

// KotlinclassLogcatBufferedOutput(uniqueId:String) : PureeBufferedOutput(uniqueId) {init {        flushInterval=5.seconds    }overridefunemit(logs:List<JsonObject>,onSuccess: ()->Unit,onFailed: (Throwable)->Unit) {// Process logs in batchLog.d("Puree","Logs:$logs")        onSuccess()    }}
// SwiftclassOSLogBufferedOutput:PureeBufferedOutput{overrideinit(uniqueId:String){        super.init(uniqueId: uniqueId)setFlushInterval(flushIntervalMillis:5000)}overridefunc emit(logs:[String], onSuccess:@escaping()->Void, onFailed:@escaping(KotlinThrowable)->Void){os_log("Puree Buffered Logs: %s", log: osLogger, type:.debug, log)onSuccess()}}

3. Configure Puree

Initialize Puree with filters and outputs:

// Kotlinval logger=Puree(    logStore=DefaultPureeLogStore("log.db"),)    .output(LogcatBufferedOutput("buffered"),ClickLog::class,MenuLog::class)    .defaultOutput(LogcatOutput())    .defaultFilter(AddTimeFilter())    .build()
// SwiftprivateclassDefaultPureeLogSerializer:PureeLogSerializer{func serialize(log:anyPureeLog, platformClass:PlatformClass<anyPureeLog>)->String{return(logas?PureeLog&Encodable)?.encode()??""}}privateletpureeLogger:PureeLogger={letlogStore=PlatformDefaultPureeLogStore(dbName:"puree.db")letlogSerializer=DefaultPureeLogSerializer()returnPuree(logStore: logStore, logSerializer: logSerializer).output(output:OSLogBufferedOutput(uniqueId:"buffered"), logTypes:[ClickLog.self,MenuLog.self]).defaultOutput(outputs:[OSLogOutput()].toKotlinArray()).defaultFilter(filters:[AddTimeFilter()].toKotlinArray()).build()}()

Kotlin by default useskotlinx.serialization to perform JSON serialization, so there is no need to prepare a special serializer. Of course, if you wish to use other serialization libraries (Gson,Jackson, etc.), you can prepare a custom serializer and register it with Puree.

Swift does not provide a default serializer, so you will need to provide your own serializer to encode PureeLog. In the above example, we use a class that conforms to theEncodable protocol to perform JSON serialization.

4. Send Logs

// Kotlininlinefun <reifiedT :PureeLog>send(log:T) {    logger?.send(log)}
// Swiftfunc send<T:PureeLog&Encodable>(_ log:T){    pureeLogger.postLog(log: log, platformClass:PlatformClass(clazz:T.self))}

It is important to note that log type information must be passed to Puree, which determines the Filter and Output to use based on the log type.Therefore, be sure to use inline generics, etc. to pass log type information to Puree while retaining it.

5. Lifecycle Management

Puree automatically integrates with the application lifecycle (for Android only):

  • Logs are buffered when the app is in the background
  • Buffered logs are processed when the app returns to the foreground
  • You can manually control this behavior withlogger.suspend() andlogger.resume()

License

Please do read theLicense before using and contributing.

About

🍯 Awesome log aggregator powered by Kotlin Multiplatform

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Contributors2

  •  
  •  

Languages


[8]ページ先頭

©2009-2025 Movatter.jp