Skip to content

Commit

Permalink
mobile: Pass the log level when setting a logger (envoyproxy#32131)
Browse files Browse the repository at this point in the history
mobile: Pass the log level when setting a logger

Signed-off-by: Fredy Wijaya <[email protected]>
  • Loading branch information
fredyw authored Feb 1, 2024
1 parent 6762bf3 commit 69f3d43
Show file tree
Hide file tree
Showing 29 changed files with 303 additions and 149 deletions.
3 changes: 2 additions & 1 deletion mobile/docs/root/api/starting_envoy.rst
Original file line number Diff line number Diff line change
Expand Up @@ -236,9 +236,10 @@ Specify a closure to be called when Envoy's engine emits a log message.

// Kotlin
// This interface is pending for Kotlin
builder.setLogger { level, message -> /* log it */ }

// Swift
builder.setLogger { msg in
builder.setLogger { level, msg in
NSLog("Envoy log: \(msg)")
}

Expand Down
2 changes: 1 addition & 1 deletion mobile/examples/kotlin/hello_world/MainActivity.kt
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ class MainActivity : Activity() {
Log.d("MainActivity", "Event emitted: ${entry.key}, ${entry.value}")
}
})
.setLogger { Log.d("MainActivity", it) }
.setLogger { _, message -> Log.d("MainActivity", message) }
.build()

recyclerView = findViewById(R.id.recycler_view) as RecyclerView
Expand Down
2 changes: 1 addition & 1 deletion mobile/library/common/BUILD
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ envoy_cc_library(
deps = [
":engine_common_lib",
"//library/common/bridge:utility_lib",
"//library/common/common:lambda_logger_delegate_lib",
"//library/common/common:logger_delegate_lib",
"//library/common/data:utility_lib",
"//library/common/event:provisional_dispatcher_lib",
"//library/common/http:client_lib",
Expand Down
6 changes: 3 additions & 3 deletions mobile/library/common/common/BUILD
Original file line number Diff line number Diff line change
Expand Up @@ -63,9 +63,9 @@ envoy_cc_library(
)

envoy_cc_library(
name = "lambda_logger_delegate_lib",
srcs = ["lambda_logger_delegate.cc"],
hdrs = ["lambda_logger_delegate.h"],
name = "logger_delegate_lib",
srcs = ["logger_delegate.cc"],
hdrs = ["logger_delegate.h"],
repository = "@envoy",
deps = [
"//library/common/api:external_api_lib",
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
#include "library/common/common/lambda_logger_delegate.h"
#include "library/common/common/logger_delegate.h"

#include <iostream>

Expand All @@ -8,6 +8,31 @@
namespace Envoy {
namespace Logger {

namespace {

envoy_log_level toEnvoyLogLevel(spdlog::level::level_enum spd_log_level) {
switch (spd_log_level) {
case spdlog::level::trace:
return envoy_log_level::ENVOY_LOG_LEVEL_TRACE;
case spdlog::level::debug:
return envoy_log_level::ENVOY_LOG_LEVEL_DEBUG;
case spdlog::level::info:
return envoy_log_level::ENVOY_LOG_LEVEL_INFO;
case spdlog::level::warn:
return envoy_log_level::ENVOY_LOG_LEVEL_WARN;
case spdlog::level::err:
return envoy_log_level::ENVOY_LOG_LEVEL_ERROR;
case spdlog::level::critical:
return envoy_log_level::ENVOY_LOG_LEVEL_CRITICAL;
case spdlog::level::off:
return envoy_log_level::ENVOY_LOG_LEVEL_OFF;
default:
PANIC("not implemented");
}
}

} // namespace

void EventTrackingDelegate::logWithStableName(absl::string_view stable_name, absl::string_view,
absl::string_view, absl::string_view msg) {
if (event_tracker_.track == nullptr) {
Expand All @@ -30,8 +55,9 @@ LambdaDelegate::~LambdaDelegate() {
logger_.release(logger_.context);
}

void LambdaDelegate::log(absl::string_view msg, const spdlog::details::log_msg&) {
logger_.log(Data::Utility::copyToBridgeData(msg), logger_.context);
void LambdaDelegate::log(absl::string_view msg, const spdlog::details::log_msg& log_msg) {
logger_.log(toEnvoyLogLevel(log_msg.level), Data::Utility::copyToBridgeData(msg),
logger_.context);
}

DefaultDelegate::DefaultDelegate(absl::Mutex& mutex, DelegatingLogSinkSharedPtr log_sink)
Expand All @@ -41,5 +67,16 @@ DefaultDelegate::DefaultDelegate(absl::Mutex& mutex, DelegatingLogSinkSharedPtr

DefaultDelegate::~DefaultDelegate() { restoreDelegate(); }

// SinkDelegate
void DefaultDelegate::log(absl::string_view msg, const spdlog::details::log_msg&) {
absl::MutexLock l(&mutex_);
std::cerr << msg;
}

void DefaultDelegate::flush() {
absl::MutexLock l(&mutex_);
std::cerr << std::flush;
}

} // namespace Logger
} // namespace Envoy
Original file line number Diff line number Diff line change
Expand Up @@ -50,14 +50,9 @@ class DefaultDelegate : public EventTrackingDelegate {
~DefaultDelegate() override;

// SinkDelegate
void log(absl::string_view msg, const spdlog::details::log_msg&) override {
absl::MutexLock l(&mutex_);
std::cerr << msg;
}
void flush() override {
absl::MutexLock l(&mutex_);
std::cerr << std::flush;
};
void log(absl::string_view msg, const spdlog::details::log_msg&) override;

void flush() override;

private:
absl::Mutex& mutex_;
Expand Down
2 changes: 1 addition & 1 deletion mobile/library/common/engine.h
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@

#include "absl/base/call_once.h"
#include "extension_registry.h"
#include "library/common/common/lambda_logger_delegate.h"
#include "library/common/common/logger_delegate.h"
#include "library/common/engine_common.h"
#include "library/common/http/client.h"
#include "library/common/network/connectivity_manager.h"
Expand Down
6 changes: 3 additions & 3 deletions mobile/library/common/jni/jni_impl.cc
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ static void jvm_on_engine_running(void* context) {
jni_helper.getEnv()->DeleteGlobalRef(j_context);
}

static void jvm_on_log(envoy_data data, const void* context) {
static void jvm_on_log(envoy_log_level log_level, envoy_data data, const void* context) {
if (context == nullptr) {
return;
}
Expand All @@ -65,8 +65,8 @@ static void jvm_on_log(envoy_data data, const void* context) {
Envoy::JNI::LocalRefUniquePtr<jclass> jcls_JvmLoggerContext =
jni_helper.getObjectClass(j_context);
jmethodID jmid_onLog =
jni_helper.getMethodId(jcls_JvmLoggerContext.get(), "log", "(Ljava/lang/String;)V");
jni_helper.callVoidMethod(j_context, jmid_onLog, str.get());
jni_helper.getMethodId(jcls_JvmLoggerContext.get(), "log", "(ILjava/lang/String;)V");
jni_helper.callVoidMethod(j_context, jmid_onLog, log_level, str.get());

release_envoy_data(data);
}
Expand Down
14 changes: 13 additions & 1 deletion mobile/library/common/types/c_types.h
Original file line number Diff line number Diff line change
Expand Up @@ -222,6 +222,17 @@ typedef struct {
int64_t upstream_protocol;
} envoy_final_stream_intel;

/** The log level for the Envoy logger. The values should match with `Logger::Levels`. */
typedef enum {
ENVOY_LOG_LEVEL_TRACE = 0,
ENVOY_LOG_LEVEL_DEBUG = 1,
ENVOY_LOG_LEVEL_INFO = 2,
ENVOY_LOG_LEVEL_WARN = 3,
ENVOY_LOG_LEVEL_ERROR = 4,
ENVOY_LOG_LEVEL_CRITICAL = 5,
ENVOY_LOG_LEVEL_OFF = 6,
} envoy_log_level;

#ifdef __cplusplus
extern "C" { // utility functions
#endif
Expand Down Expand Up @@ -418,11 +429,12 @@ typedef void (*envoy_on_engine_running_f)(void* context);
/**
* Called when envoy's logger logs data.
*
* @param level the log level
* @param data, the logged data.
* @param context, contains the necessary state to carry out platform-specific dispatch and
* execution.
*/
typedef void (*envoy_logger_log_f)(envoy_data data, const void* context);
typedef void (*envoy_logger_log_f)(envoy_log_level level, envoy_data data, const void* context);

/**
* Called when Envoy is done with the logger.
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,17 @@
package io.envoyproxy.envoymobile.engine.types;

public interface EnvoyLogger {
void log(String str);
/** The log level for this logger. */
interface Level {
int TRACE = 0;
int DEBUG = 1;
int INFO = 2;
int WARN = 3;
int ERROR = 4;
int CRITICAL = 5;
int OFF = 6;
}

/** Logs the given string with the specified log level. */
void log(int logLevel, String str);
}
3 changes: 2 additions & 1 deletion mobile/library/java/org/chromium/net/impl/CronvoyLogger.java
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

import io.envoyproxy.envoymobile.engine.types.EnvoyLogger;

/*
Expand Down Expand Up @@ -42,7 +43,7 @@ public void stopLogging() {
}

@Override
public void log(String str) {
public void log(int logLevel, String str) {
if (mWriter != null) {
try {
Path path = Paths.get(mFileName);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,13 @@ constructor(context: Context, baseConfiguration: BaseConfiguration = Standard())
EngineBuilder(baseConfiguration) {
init {
addEngineType {
AndroidEngineImpl(context, onEngineRunning, logger, eventTracker, enableProxying)
AndroidEngineImpl(
context,
onEngineRunning,
{ level, msg -> logger?.let { it(LogLevel.from(level), msg) } },
eventTracker,
enableProxying
)
}
}
}
10 changes: 7 additions & 3 deletions mobile/library/kotlin/io/envoyproxy/envoymobile/EngineBuilder.kt
Original file line number Diff line number Diff line change
Expand Up @@ -130,12 +130,16 @@ open class XdsBuilder(internal val xdsServerAddress: String, internal val xdsSer
/** Builder used for creating and running a new `Engine` instance. */
open class EngineBuilder(private val configuration: BaseConfiguration = Standard()) {
protected var onEngineRunning: (() -> Unit) = {}
protected var logger: ((String) -> Unit)? = null
protected var logger: ((LogLevel, String) -> Unit)? = null
protected var eventTracker: ((Map<String, String>) -> Unit)? = null
protected var enableProxying = false
private var runtimeGuards = mutableMapOf<String, Boolean>()
private var engineType: () -> EnvoyEngine = {
EnvoyEngineImpl(onEngineRunning, logger, eventTracker)
EnvoyEngineImpl(
onEngineRunning,
{ level, msg -> logger?.let { it(LogLevel.from(level), msg) } },
eventTracker
)
}
private var logLevel = LogLevel.INFO
private var connectTimeoutSeconds = 30
Expand Down Expand Up @@ -474,7 +478,7 @@ open class EngineBuilder(private val configuration: BaseConfiguration = Standard
* @param closure: The closure to be called.
* @return This builder.
*/
fun setLogger(closure: (String) -> Unit): EngineBuilder {
fun setLogger(closure: (LogLevel, String) -> Unit): EngineBuilder {
this.logger = closure
return this
}
Expand Down
17 changes: 16 additions & 1 deletion mobile/library/kotlin/io/envoyproxy/envoymobile/LogLevel.kt
Original file line number Diff line number Diff line change
Expand Up @@ -13,5 +13,20 @@ enum class LogLevel(internal val level: String, val levelInt: Int) {
WARN("warn", 3),
ERROR("error", 4),
CRITICAL("critical", 5),
OFF("off", -1)
OFF("off", 6);

companion object {
/** Converts from numeric int to `LogLevel`. */
fun from(level: Int): LogLevel {
return when (level) {
0 -> TRACE
1 -> DEBUG
2 -> INFO
3 -> WARN
4 -> ERROR
5 -> CRITICAL
else -> OFF
}
}
}
}
2 changes: 1 addition & 1 deletion mobile/library/objective-c/EnvoyEngine.h
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ NS_ASSUME_NONNULL_BEGIN
@param networkMonitoringMode Configure how the engines observe network reachability.
*/
- (instancetype)initWithRunningCallback:(nullable void (^)())onEngineRunning
logger:(nullable void (^)(NSString *))logger
logger:(nullable void (^)(NSInteger, NSString *))logger
eventTracker:(nullable void (^)(EnvoyEvent *))eventTracker
networkMonitoringMode:(int)networkMonitoringMode;
/**
Expand Down
6 changes: 3 additions & 3 deletions mobile/library/objective-c/EnvoyEngineImpl.mm
Original file line number Diff line number Diff line change
Expand Up @@ -37,12 +37,12 @@ static void ios_on_exit(void *context) {
}
}

static void ios_on_log(envoy_data data, const void *context) {
static void ios_on_log(envoy_log_level log_level, envoy_data data, const void *context) {
// This code block runs inside the Envoy event loop. Therefore, an explicit autoreleasepool block
// is necessary to act as a breaker for any Objective-C allocation that happens.
@autoreleasepool {
EnvoyLogger *logger = (__bridge EnvoyLogger *)context;
logger.log(to_ios_string(data));
logger.log(log_level, to_ios_string(data));
}
}

Expand Down Expand Up @@ -403,7 +403,7 @@ @implementation EnvoyEngineImpl {
}

- (instancetype)initWithRunningCallback:(nullable void (^)())onEngineRunning
logger:(nullable void (^)(NSString *))logger
logger:(nullable void (^)(NSInteger, NSString *))logger
eventTracker:(nullable void (^)(EnvoyEvent *))eventTracker
networkMonitoringMode:(int)networkMonitoringMode {
self = [super init];
Expand Down
4 changes: 2 additions & 2 deletions mobile/library/objective-c/EnvoyLogger.h
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,12 @@ NS_ASSUME_NONNULL_BEGIN
// Logging interface.
@interface EnvoyLogger : NSObject

@property (nonatomic, copy) void (^log)(NSString *);
@property (nonatomic, copy) void (^log)(NSInteger, NSString *);

/**
Create a new instance of the logger.
*/
- (instancetype)initWithLogClosure:(void (^)(NSString *))log;
- (instancetype)initWithLogClosure:(void (^)(NSInteger, NSString *))log;

@end

Expand Down
2 changes: 1 addition & 1 deletion mobile/library/objective-c/EnvoyLogger.m
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

@implementation EnvoyLogger

- (instancetype)initWithLogClosure:(void (^)(NSString *))log {
- (instancetype)initWithLogClosure:(void (^)(NSInteger, NSString *))log {
self = [super init];
if (!self) {
return nil;
Expand Down
13 changes: 10 additions & 3 deletions mobile/library/swift/EngineBuilder.swift
Original file line number Diff line number Diff line change
Expand Up @@ -166,7 +166,7 @@ open class EngineBuilder: NSObject {
private var appVersion: String = "unspecified"
private var appId: String = "unspecified"
private var onEngineRunning: (() -> Void)?
private var logger: ((String) -> Void)?
private var logger: ((LogLevel, String) -> Void)?
private var eventTracker: (([String: String]) -> Void)?
private(set) var monitoringMode: NetworkMonitoringMode = .pathMonitor
private var nativeFilterChain: [EnvoyNativeFilterConfig] = []
Expand Down Expand Up @@ -573,7 +573,7 @@ open class EngineBuilder: NSObject {
///
/// - returns: This builder.
@discardableResult
public func setLogger(closure: @escaping (String) -> Void) -> Self {
public func setLogger(closure: @escaping (LogLevel, String) -> Void) -> Self {
self.logger = closure
return self
}
Expand Down Expand Up @@ -688,7 +688,14 @@ open class EngineBuilder: NSObject {
///
/// - returns: The built `Engine`.
public func build() -> Engine {
let engine = self.engineType.init(runningCallback: self.onEngineRunning, logger: self.logger,
let engine = self.engineType.init(runningCallback: self.onEngineRunning,
logger: { level, message in
if let log = self.logger {
if let lvl = LogLevel(rawValue: level) {
log(lvl, message)
}
}
},
eventTracker: self.eventTracker,
networkMonitoringMode: Int32(self.monitoringMode.rawValue))
let config = self.makeConfig()
Expand Down
3 changes: 2 additions & 1 deletion mobile/library/swift/mocks/MockEnvoyEngine.swift
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@ import Foundation

/// Mock implementation of `EnvoyEngine`. Used internally for testing the bridging layer & mocking.
final class MockEnvoyEngine: NSObject {
init(runningCallback onEngineRunning: (() -> Void)? = nil, logger: ((String) -> Void)? = nil,
init(runningCallback onEngineRunning: (() -> Void)? = nil,
logger: ((Int, String) -> Void)? = nil,
eventTracker: (([String: String]) -> Void)? = nil, networkMonitoringMode: Int32 = 0) {}

/// Closure called when `run(withConfig:)` is called.
Expand Down
Loading

0 comments on commit 69f3d43

Please sign in to comment.