GithubHelp home page GithubHelp logo

saschpe / log4k Goto Github PK

View Code? Open in Web Editor NEW
16.0 5.0 2.0 615 KB

Lightweight logging library for Kotlin/Multiplatform. Supports Android, iOS, JavaScript and plain JVM environments.

Kotlin 91.54% Shell 8.46%
kotlin kotlin-multiplatform kotlin-android logging kotlin-js kotlin-jvm kotlin-ios gradle ios ios-library

log4k's Introduction

Log4K

Build Status Maven Central Kotlin Version GitHub license

badge-android badge-ios badge-js badge-jvm

Lightweight logging library for Kotlin/Multiplatform. Supports Android, iOS, JavaScript and plain JVM environments.

  • log4k: Base library, provides infrastructure and console logging
  • log4k-slf4j: Integration with SLF4J

Download

Artifacts are published to Maven Central:

repositories {
    mavenCentral()
}

dependencies {
    implementation("de.peilicke.sascha:log4k:1.3.4")
}

Usage

Logging messages is straightforward, the Log object provides the usual functions you'd expect:

// Log to your heart's content
Log.verbose("FYI")
Log.debug("Debugging ${foo.bar}")
Log.info("Nice to know", tag = "SomeClass")
Log.warn("Warning about $stuff ...")
Log.error("Oops!")
Log.assert("Something went wrong!", throwable)

Or, if you prefer:

Log.verbose { "FYI" }
Log.debug { "Debugging ${foo.bar}" }
Log.info(tag = "SomeClass") { "Nice to know" }
Log.warn { "Warning about $stuff ..." }
Log.error { "Oops!" }
Log.assert(throwable = Exception("Ouch!")) { "Something went wrong!" }

The log output includes the function name and line and pretty-prints exceptions on all supported platforms:

I/Application.onCreate: Log4K rocks!

Logging objects

In case you want to log Any Kotlin class instance or object:

val map = mapOf("Hello" to "World")
map.logged()

The above example logs {Hello=World} with the tag SingletonMap with the log level Debug.

Logging expensive results

Sometimes, the log output involves a heavy computation that is not always necessary. For example, if the global log level is set to Info or above, the following text would not appear in any log output:

Log.debug("Some ${veryHeavyStuff()}")

However, the function veryHeavyStuff() will be executed regardless. To avoid this, use:

Log.debug { "Some ${veryHeavyStuff()}" }

Configuration (Android example)

To only output messages with log-level info and above, you can configure the console logger in your Application class:

class MyApplication : Application() {
    override fun onCreate() {
        super.onCreate()
        Log.loggers.forEach {
            if (!BuildConfig.DEBUG) {
                it.minimumLogLevel = Log.Level.Info
            }
        }
    }
}

Logging to a file

By default, the library only logs to the current platform's console. Additionally or instead, add one or multiple file loggers:

// Log with daily rotation and keep five log files at max:
Log.loggers += FileLogger(rotate = Rotate.Daily, limit = Limit.Files(max = 5))

// Log to a custom path and rotate every 1000 lines written:
Log.loggers += FileLogger(rotate = Rotate.After(lines = 1000), logPath = "myLogPath")

// Log with sensible defaults (daily, keep 10 files)
Log.loggers += FileLogger()

// On huge eternal log file:
Log.loggers += FileLogger(rotate = Rotate.Never, limit = Limit.Not)

Custom logger (Android Crashlytics example)

The library provides a cross-platform ConsoleLogger by default. Custom loggers can easily be added. For instance, to send only ERROR and ASSERT messages to Crashlytics in production builds, you could do the following:

class MyApplication : Application() {
    override fun onCreate() {
        super.onCreate()
        Log.loggers.clear() // Remove default loggers
        Log.loggers += when {
            BuildConfig.DEBUG -> ConsoleLogger()
            else -> CrashlyticsLogger()
        }
    }

    private class CrashlyticsLogger : Logger() {
        override fun print(level: Log.Level, tag: String, message: String?, throwable: Throwable?) {
            val priority = when (level) {
                Log.Level.Verbose -> VERBOSE
                Log.Level.Debug -> DEBUG
                Log.Level.Info -> INFO
                Log.Level.Warning -> WARN
                Log.Level.Error -> ERROR
                Log.Level.Assert -> ASSERT
            }
            if (priority >= ERROR) {
                FirebaseCrashlytics.getInstance().log("$priority $tag $message")
                throwable?.let { FirebaseCrashlytics.getInstance().recordException(it) }
            }
        }
    }
}

Ktor integration

Ktor supports providing a custom logger:

import io.ktor.client.*
import io.ktor.client.engine.cio.*
import io.ktor.client.plugins.logging.*
import saschpe.log4k.Log

val httpClient = HttpClient(CIO) {
    install(Logging) {
        level = LogLevel.ALL
        logger = object : Logger {
            override fun log(message: String) = Log.info { message }
        }
    }
}

Users

License

Copyright 2019 Sascha Peilicke

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

log4k's People

Contributors

saschpe avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

log4k's Issues

Lower minSdk version

When you moved to using gradle catalogs in commit 656bb65, the minSdk was updated to 24 versus the previous 17. Is there any reason for this upgrade?

Many applications and libraries have a lower minimum version than 24, so although this library still works, it has to be worked around. 21 is usually a good minimum since the Jetpack libraries have a minimum of that nowadays.

Any plans to support lazy evaluation of log messages?

Sometimes log messages use string interpolation that call "expensive" functions to compose the final string. Commonly, log frameworks offer an API that takes the message as a lambda in that case (like Log.info { "Did ${compute()} things." }), so string interpolation only happens if the respective log level is active. Is something like that also planned for Log4k?

Create FileLogger

Requirements

  • Should avoid dependencies on ktor-io or kotlinx-datetime
  • Available for JVM, Android and iOS at least
    • Not sure what file could mean in a browser context
  • Should allow to rotate logs
    • Daily
    • Every X lines logged

Usage Draft

Log.loggers += FileLogger(logDir = "my/logs", rotation = Rotate.After(lines = 4096))

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.