Skip to content

Commit

Permalink
Logs alignment (#217)
Browse files Browse the repository at this point in the history
* Refactoring logs. Replacing property from `zenoh.logger` to `zenoh.rust_log`.

* Refactoring logs. Loading log config from enviornment variable like in other bindings: RUST_LOG=debug gradle ZPub (for instance).

* Addressing comments:

- Renaming tryInitLogFromEnvOr to initLogFromEnvOr
- Adding Zenoh.initLogFromEnvOr("error") to all the examples

* Using filters for logging
  • Loading branch information
DariusIMP authored Sep 13, 2024
1 parent 8aa102f commit c97136e
Show file tree
Hide file tree
Showing 18 changed files with 71 additions and 32 deletions.
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -295,12 +295,12 @@ tests executed locally as Unit tests.

## Logging

Rust logs are propagated when setting the property `zenoh.logger=debug` (using RUST_LOG=debug will result in nothing)
Rust logs are propagated when setting the `RUST_LOG` environment variable.

For instance running the ZPub test as follows:

```bash
gradle -Pzenoh.logger=debug ZPub
RUST_LOG=debug gradle ZPub
```

causes the logs to appear in standard output.
Expand Down
4 changes: 2 additions & 2 deletions examples/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -54,10 +54,10 @@ There is the possibility to provide a Zenoh config file as follows

In that case, any other provided configuration parameters through the command line interface will not be taken into consideration.

One last comment regarding Zenoh logging for the examples, remember it can be enabled through the `zenoh.logger` property as follows:
One last comment regarding Zenoh logging for the examples, remember it can be enabled through the environment variable `RUST_LOG` as follows:

```bash
gradle ZPub -Pzenoh.logger=<level>
RUST_LOG=<level> gradle ZPub
```

where `<level>` can be either `info`, `trace`, `debug`, `warn` or `error`.
Expand Down
7 changes: 1 addition & 6 deletions examples/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -51,12 +51,7 @@ tasks {
classpath(sourceSets["main"].runtimeClasspath)
val zenohPaths = "../zenoh-jni/target/release"
val defaultJvmArgs = arrayListOf("-Djava.library.path=$zenohPaths")
val loggerLvl = project.findProperty("zenoh.logger")?.toString()
if (loggerLvl != null) {
jvmArgs(defaultJvmArgs + "-Dzenoh.logger=$loggerLvl")
} else {
jvmArgs(defaultJvmArgs)
}
jvmArgs(defaultJvmArgs)
}
}
}
Expand Down
2 changes: 2 additions & 0 deletions examples/src/main/kotlin/io.zenoh/ZDelete.kt
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@ class ZDelete(private val emptyArgs: Boolean) : CliktCommand(
override fun run() {
val config = loadConfig(emptyArgs, configFile, connect, listen, noMulticastScouting, mode)

Zenoh.initLogFromEnvOr("error")

println("Opening session...")
Zenoh.open(config).onSuccess { session ->
session.use {
Expand Down
2 changes: 2 additions & 0 deletions examples/src/main/kotlin/io.zenoh/ZGet.kt
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,8 @@ class ZGet(private val emptyArgs: Boolean) : CliktCommand(
override fun run() {
val config = loadConfig(emptyArgs, configFile, connect, listen, noMulticastScouting, mode)

Zenoh.initLogFromEnvOr("error")

Zenoh.open(config).onSuccess { session ->
session.use {
selector.intoSelector().onSuccess { selector ->
Expand Down
2 changes: 2 additions & 0 deletions examples/src/main/kotlin/io.zenoh/ZPub.kt
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@ class ZPub(private val emptyArgs: Boolean) : CliktCommand(
override fun run() {
val config = loadConfig(emptyArgs, configFile, connect, listen, noMulticastScouting, mode)

Zenoh.initLogFromEnvOr("error")

println("Opening session...")
Zenoh.open(config).onSuccess { session ->
session.use {
Expand Down
2 changes: 2 additions & 0 deletions examples/src/main/kotlin/io.zenoh/ZPubThr.kt
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,8 @@ class ZPubThr(private val emptyArgs: Boolean) : CliktCommand(
) {

override fun run() {
Zenoh.initLogFromEnvOr("error")

val data = ByteArray(payloadSize)
for (i in 0..<payloadSize) {
data[i] = (i % 10).toByte()
Expand Down
2 changes: 2 additions & 0 deletions examples/src/main/kotlin/io.zenoh/ZPut.kt
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@ class ZPut(private val emptyArgs: Boolean) : CliktCommand(
override fun run() {
val config = loadConfig(emptyArgs, configFile, connect, listen, noMulticastScouting, mode)

Zenoh.initLogFromEnvOr("error")

println("Opening Session...")
Zenoh.open(config).onSuccess { session ->
session.use {
Expand Down
2 changes: 2 additions & 0 deletions examples/src/main/kotlin/io.zenoh/ZQueryable.kt
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,8 @@ class ZQueryable(private val emptyArgs: Boolean) : CliktCommand(
override fun run() {
val config = loadConfig(emptyArgs, configFile, connect, listen, noMulticastScouting, mode)

Zenoh.initLogFromEnvOr("error")

Zenoh.open(config).onSuccess { session ->
session.use {
key.intoKeyExpr().onSuccess { keyExpr ->
Expand Down
2 changes: 2 additions & 0 deletions examples/src/main/kotlin/io.zenoh/ZScout.kt
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@ class ZScout : CliktCommand(
) {
override fun run() {

Zenoh.initLogFromEnvOr("error")

println("Scouting...")

val scout = Zenoh.scout(channel = Channel(), whatAmI = setOf(WhatAmI.Peer, WhatAmI.Router)).getOrThrow()
Expand Down
2 changes: 2 additions & 0 deletions examples/src/main/kotlin/io.zenoh/ZSub.kt
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@ class ZSub(private val emptyArgs: Boolean) : CliktCommand(
override fun run() {
val config = loadConfig(emptyArgs, configFile, connect, listen, noMulticastScouting, mode)

Zenoh.initLogFromEnvOr("error")

println("Opening session...")
Zenoh.open(config).onSuccess { session ->
session.use {
Expand Down
3 changes: 2 additions & 1 deletion examples/src/main/kotlin/io.zenoh/ZSubThr.kt
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@ import com.github.ajalt.clikt.core.CliktCommand
import com.github.ajalt.clikt.parameters.options.*
import com.github.ajalt.clikt.parameters.types.ulong
import io.zenoh.keyexpr.intoKeyExpr
import io.zenoh.subscriber.Reliability
import io.zenoh.subscriber.Subscriber
import kotlin.system.exitProcess

Expand Down Expand Up @@ -73,6 +72,8 @@ class ZSubThr(private val emptyArgs: Boolean) : CliktCommand(
override fun run() {
val config = loadConfig(emptyArgs, configFile, connect, listen, noMulticastScouting, mode)

Zenoh.initLogFromEnvOr("error")

"test/thr".intoKeyExpr().onSuccess { keyExpr ->
keyExpr.use {
println("Opening Session")
Expand Down
2 changes: 1 addition & 1 deletion zenoh-jni/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ json5 = "0.4.1"
serde_yaml = "0.9.19"
zenoh = { version = "1.0.0-dev", git = "https://github.com/eclipse-zenoh/zenoh.git", branch = "main", default-features = false }
zenoh-ext = { version = "1.0.0-dev", git = "https://github.com/eclipse-zenoh/zenoh.git", branch = "main", default-features = false }
tracing = "0.1"
tracing = { version = "0.1" , features = ["log"] }
[lib]
name = "zenoh_jni"
crate_type = ["staticlib", "dylib"]
Expand Down
17 changes: 9 additions & 8 deletions zenoh-jni/src/logger.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,27 +21,28 @@ use crate::{errors::Result, jni_error, throw_exception};

/// Redirects the Rust logs either to logcat for Android systems or to the standard output (for non-Android systems).
///
/// This function is meant to be called from Java/Kotlin code through JNI. It takes a `log_level`
/// indicating the desired log level, which must be one of the following: "info", "debug", "warn",
/// "trace", or "error".
/// This function is meant to be called from Java/Kotlin code through JNI. It takes a `filter`
/// indicating the desired log level.
///
/// See https://docs.rs/env_logger/latest/env_logger/index.html for accepted filter format.
///
/// # Parameters:
/// - `env`: The JNI environment.
/// - `_class`: The JNI class.
/// - `log_level`: The log level java string indicating the desired log level.
/// - `filter`: The logs filter.
///
/// # Errors:
/// - If there is an error parsing the log level string, a `JNIException` is thrown on the JVM.
///
#[no_mangle]
#[allow(non_snake_case)]
pub extern "C" fn Java_io_zenoh_Logger_00024Companion_start(
pub extern "C" fn Java_io_zenoh_Logger_00024Companion_startLogsViaJNI(
mut env: JNIEnv,
_class: JClass,
log_level: JString,
filter: JString,
) {
|| -> Result<()> {
let log_level = parse_log_level(&mut env, log_level)?;
let log_level = parse_filter(&mut env, filter)?;
android_logd_logger::builder()
.parse_filters(log_level.as_str())
.tag_target_strip()
Expand All @@ -52,7 +53,7 @@ pub extern "C" fn Java_io_zenoh_Logger_00024Companion_start(
.unwrap_or_else(|err| throw_exception!(env, err))
}

fn parse_log_level(env: &mut JNIEnv, log_level: JString) -> Result<String> {
fn parse_filter(env: &mut JNIEnv, log_level: JString) -> Result<String> {
let log_level = env.get_string(&log_level).map_err(|err| jni_error!(err))?;
log_level
.to_str()
Expand Down
1 change: 0 additions & 1 deletion zenoh-kotlin/src/androidMain/kotlin/io.zenoh/Zenoh.kt
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,5 @@ internal actual object ZenohLoad {

init {
System.loadLibrary(ZENOH_LIB_NAME)
Zenoh.tryInitLogFromEnv()
}
}
18 changes: 14 additions & 4 deletions zenoh-kotlin/src/commonMain/kotlin/io/zenoh/Logger.kt
Original file line number Diff line number Diff line change
Expand Up @@ -15,13 +15,23 @@
package io.zenoh

/** Logger class to redirect the Rust logs from Zenoh to the kotlin environment. */
class Logger {
internal class Logger {

companion object {

internal const val LOG_ENV: String = "RUST_LOG"

fun start(filter: String) = runCatching {
startLogsViaJNI(filter)
}

/**
* Redirects the rust logs either to logcat for Android systems or to the standard output (for non-android
* systems). @param logLevel must be either "info", "debug", "warn", "trace" or "error".
* systems).
*
* See https://docs.rs/env_logger/latest/env_logger/index.html for accepted filter format.
*/
external fun start(logLevel: String)
@Throws(Exception::class)
private external fun startLogsViaJNI(filter: String)
}
}
}
29 changes: 24 additions & 5 deletions zenoh-kotlin/src/commonMain/kotlin/io/zenoh/Zenoh.kt
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@

package io.zenoh

import io.zenoh.Logger.Companion.LOG_ENV
import io.zenoh.handlers.Callback
import io.zenoh.handlers.ChannelHandler
import io.zenoh.handlers.Handler
Expand Down Expand Up @@ -108,15 +109,33 @@ object Zenoh {
}

/**
* Try starting the logs with the level specified under the property 'zenoh.logger'.
* Initializes the zenoh runtime logger, using rust environment settings.
* E.g.: `RUST_LOG=info` will enable logging at info level. Similarly, you can set the variable to `error` or `debug`.
*
* Note that if the environment variable is not set, then logging will not be enabled.
* See https://docs.rs/env_logger/latest/env_logger/index.html for accepted filter format.
*
* @see Logger
*/
fun tryInitLogFromEnv() {
val logLevel = System.getProperty("zenoh.logger")
if (logLevel != null) {
Logger.start(logLevel)
}
ZenohLoad
Logger.start(System.getenv(LOG_ENV) ?: "")
}

/**
* Initializes the zenoh runtime logger, using rust environment settings or the provided fallback level.
* E.g.: `RUST_LOG=info` will enable logging at info level. Similarly, you can set the variable to `error` or `debug`.
*
* Note that if the environment variable is not set, then [fallbackFilter] will be used instead.
* See https://docs.rs/env_logger/latest/env_logger/index.html for accepted filter format.
*
* @param fallbackFilter: The fallback filter if the `RUST_LOG` environment variable is not set.
* @see Logger
*/
fun initLogFromEnvOr(fallbackFilter: String): Result<Unit> = runCatching {
ZenohLoad
val logLevelProp = System.getenv(LOG_ENV)
logLevelProp?.let { Logger.start(it) } ?: Logger.start(fallbackFilter)
}
}

Expand Down
2 changes: 0 additions & 2 deletions zenoh-kotlin/src/jvmMain/kotlin/io/zenoh/Zenoh.kt
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,6 @@ internal actual object ZenohLoad {
val target = determineTarget().getOrThrow()
tryLoadingLibraryFromJarPackage(target).getOrThrow()
}

Zenoh.tryInitLogFromEnv()
}

/**
Expand Down

0 comments on commit c97136e

Please sign in to comment.