- Notifications
You must be signed in to change notification settings - Fork0
🍯 Awesome log aggregator powered by Kotlin Multiplatform
License
cookpad/puree-kmp
Folders and files
| Name | Name | Last commit message | Last commit date | |
|---|---|---|---|---|
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.
- 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 |
|---|---|
| Android | ✅ Supported |
| iOS | ✅ Supported |
| JVM | 🔲 Planing |
| Desktop | 🔲 Planing |
| Web | ❌ Not Supported |
dependencies { implementation("com.cookpad.puree:puree-kmp:$latestVersion")}Distributed throughSwift Package Manager.You can install directly from Xcode by specifying the URL for this repository.
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.
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
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}}
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()}}
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.
// 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.
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 with
logger.suspend()andlogger.resume()
Please do read theLicense before using and contributing.
About
🍯 Awesome log aggregator powered by Kotlin Multiplatform
Resources
License
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Packages0
Uh oh!
There was an error while loading.Please reload this page.
Contributors2
Uh oh!
There was an error while loading.Please reload this page.

