Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore: logging feature in react native package and ios native module #318

Merged
merged 7 commits into from
Sep 10, 2024
Merged
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion Apps/APN/src/services/CustomerIOService.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,9 @@ export const initializeCustomerIoSDK = (sdkConfig) => {
}
};
if (sdkConfig.debugMode) {
config.logLevel = CioLogLevel.debug;
config.logLevel = CioLogLevel.Debug;
}

CustomerIO.initialize(config)
};

Expand Down
8 changes: 6 additions & 2 deletions ios/wrappers/CioRctWrapper.swift
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,14 @@ import React
class CioRctWrapper: NSObject {

@objc var moduleRegistry: RCTModuleRegistry!
private var logger: CioLogger!

@objc
func initialize(_ configJson: AnyObject, logLevel: String) {
do {
logger = CioLoggerWrapper.getInstance(moduleRegistry: moduleRegistry, logLevel: CioLogLevel(rawValue: logLevel) ?? .none)

logger.debug("Initializing Customer.io SDK with config: \(configJson)")
let rtcConfig = try RCTCioConfig.from(configJson)
let cioInitConfig = cioInitializeConfig(from: rtcConfig, logLevel: logLevel)
CustomerIO.initialize(withConfig: cioInitConfig.cdp)
Expand All @@ -23,7 +27,7 @@ class CioRctWrapper: NSObject {
}
}
} catch {
// TODO: Add log when logger feature is implemented
logger.error("Initializing Customer.io SDK failed with error \(error)")
}
}

Expand All @@ -36,7 +40,7 @@ class CioRctWrapper: NSObject {
} else if codableTraits != nil {
CustomerIO.shared.identify(traits: codableTraits!)
} else {
// TODO: Add log when logger feature is implemented
logger.error("Provide id or traits to identify a user profile.")
}
}

Expand Down
4 changes: 4 additions & 0 deletions ios/wrappers/logging/CioLoggingEmitter.mm
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
#import <React/RCTEventEmitter.h>

@interface RCT_EXTERN_REMAP_MODULE(CioLoggingEmitter, CioLoggingEmitter, RCTEventEmitter)
@end
96 changes: 96 additions & 0 deletions ios/wrappers/logging/CioLoggingEmitter.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@

import React
import CioInternalCommon

typealias CioLogger = CioInternalCommon.Logger

@objc(CioLoggingEmitter)
class CioLoggingEmitter: RCTEventEmitter {

fileprivate static var eventName = "CioLogEvent"

fileprivate var hasObservers = false

// Requires adding requiresMainQueueSetup method
// since it overrides init
@objc static override func requiresMainQueueSetup() -> Bool {
return true // Return true if the module must be initialized on the main queue
}
override func startObserving() {
hasObservers = true
}

override func stopObserving() {
hasObservers = false
}

override func supportedEvents() -> [String] {
[Self.eventName]
}

override var methodQueue: dispatch_queue_t! {
DispatchQueue(label: Self.moduleName())
}
}


class CioLoggerWrapper: CioLogger {
private(set) var logLevel: CioLogLevel
private var moduleRegistry: RCTModuleRegistry
ami-aman marked this conversation as resolved.
Show resolved Hide resolved

static func getInstance (moduleRegistry: RCTModuleRegistry, logLevel: CioLogLevel) -> CioLogger {
if let wrapper = DIGraphShared.shared.logger as? Self {
wrapper.logLevel = logLevel
wrapper.moduleRegistry = moduleRegistry
return wrapper
}

let wrapper = CioLoggerWrapper(moduleRegistry: moduleRegistry, logLevel: logLevel)
DIGraphShared.shared.override(value: wrapper, forType: CioLogger.self)
return wrapper
}

private init(moduleRegistry: RCTModuleRegistry, logLevel: CioLogLevel?) {
self.logLevel = logLevel ?? .none
self.moduleRegistry = moduleRegistry
}

func setLogLevel(_ level: CioLogLevel) {
logLevel = level
}

func debug(_ message: String) {
emit(message, level: .debug)
}

func info(_ message: String) {
emit(message, level: .info)
}

func error(_ message: String) {
emit(message, level: .error)
}

private func emit(_ message: String, level: CioLogLevel) {
if shouldEmit(level: level), let emitter, emitter.hasObservers {
emitter.sendEvent(withName: CioLoggingEmitter.eventName, body: ["logLevel": level.rawValue, "message": message])
}
}

private func shouldEmit(level: CioLogLevel) -> Bool {
switch self.logLevel {
case .none: return false
case .error:
return level == .error
case .info:
return level == .error || level == .info
case .debug:
return true
}
}

private var emitter: CioLoggingEmitter? {
moduleRegistry.module(forName: "CioLoggingEmitter") as? CioLoggingEmitter
}

}
11 changes: 5 additions & 6 deletions src/customerio-cdp.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import { NativeModules, Platform } from 'react-native';
import { CioLogLevel, type CioConfig } from './cio-config';
import {type IdentifyParams } from './cio-params';
// TODO: Import the CustomerIOInAppMessaging, NativeLoggerListener and CustomerIOPushMessaging classes from their respective files
// TODO: Import the CustomerIOInAppMessaging and CustomerIOPushMessaging classes from their respective files
// when they are implemented.
// import { CustomerIOInAppMessaging } from './customerio-inapp';
// import { CustomerIOPushMessaging } from './customerio-push';
// import { NativeLoggerListener } from './native-logger-listener';
import { NativeLoggerListener } from './native-logger-listener';

const LINKING_ERROR =
`The package 'customerio-reactnative' doesn't seem to be linked. Make sure: ` +
Expand All @@ -28,10 +28,9 @@ export class CustomerIO {
private static initialized = false;

static readonly initialize = async (config: CioConfig) => {
// TODO: Initialize logger when it is implemented.
// if (config.logLevel && config.logLevel !== CioLogLevel.None) {
// NativeLoggerListener.initialize();
// }
if (config.logLevel && config.logLevel !== CioLogLevel.None) {
NativeLoggerListener.initialize();
}
let logLevel = config.logLevel?.valueOf() ?? CioLogLevel.Error.valueOf();
NativeCustomerIO.initialize(config, logLevel);
CustomerIO.initialized = true;
Expand Down
51 changes: 51 additions & 0 deletions src/native-logger-listener.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import { NativeEventEmitter, NativeModules, Platform } from 'react-native';
import { CioLogLevel } from './cio-config';

const LINKING_ERROR =
`The package 'customerio-reactnative' doesn't seem to be linked. Make sure: ` +
Platform.select({ ios: "- You have run 'pod install'\n", default: '' }) +
'- You rebuilt the app after installing the package\n' +
'- You are not using Expo Go\n';

const CioLoggingEmitter = NativeModules.CioLoggingEmitter
? NativeModules.CioLoggingEmitter
: new Proxy(
{},
{
get() {
throw new Error(LINKING_ERROR);
},
}
);

export class NativeLoggerListener {
static initialize() {
const bridge = new NativeEventEmitter(CioLoggingEmitter);
bridge.addListener(
'CioLogEvent',
(event: { logLevel: CioLogLevel; message: string }) => {
// Using console.log will log to the JavaScript side but prevent
// React Native’s default behavior of redirecting logs to the native side.
// By doing it asynchronously, we ensure the logs are captured on both
// the JavaScript and native ends.
async function log() {
switch (event.logLevel) {
case CioLogLevel.Debug:
console.debug("[CIO] " + event.message);
ami-aman marked this conversation as resolved.
Show resolved Hide resolved
break;
case CioLogLevel.Info:
console.info("[CIO] " + event.message);
break;
case CioLogLevel.Error:
console.error("[CIO] " + event.message);
break;
default:
console.log("[CIO] " + event);
break;
}
}
log();
}
);
}
}
Loading