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

improve: add console logging (RMCCX-6876) #390

Merged
Show file tree
Hide file tree
Changes from all 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
4 changes: 4 additions & 0 deletions inappmessaging/USERGUIDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -496,6 +496,10 @@ All the events "launch the app event, login event, purchase successful event, cu
<details>
<summary style="cursor: pointer;";>(click to expand)</summary>

#### 7.7.0 (In-Progress)
* Improvements:
- RMCCX-6876: Improved console logging.

#### 7.6.0 (In-Progress)
* Improvements:
- SDKCF-6327: Updated compile and target SDK to API 34 (Android 14).
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,8 @@ internal object EventTrackerHelper {
com.rakuten.tech.mobile.analytics.RatTracker.event(eventName, serializableData).track()
return true
} catch (e: Exception) {
InAppLogger(TAG).warn("Could not send event: $e")
InAppLogger(TAG).warn("sendEvent - analytics.track() failed")
InAppLogger(TAG).debug("exception: $e")
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -57,20 +57,21 @@ internal class InApp(
override var onPushPrimer: (() -> Unit)? = null

override fun registerPreference(userInfoProvider: UserInfoProvider) {
InAppLogger(TAG).info("registerPreference - userInfoProvider: $userInfoProvider")
InAppLogger(TAG).info("registerPreference: $userInfoProvider")
accountRepo.userInfoProvider = userInfoProvider
}

@SuppressWarnings("TooGenericExceptionCaught")
override fun registerMessageDisplayActivity(activity: Activity) {
InAppLogger(TAG).info("registerMessageDisplayActivity - Activity: $activity")
InAppLogger(TAG).info("registerActivity: $activity")
try {
hostAppInfoRepo.registerActivity(activity)
// Making worker thread to display message.
if (configRepo.isConfigEnabled()) {
displayManager.displayMessage()
}
} catch (ex: Exception) {
InAppLogger(TAG).error("registerActivity - error: ${ex.message}")
errorCallback?.let {
it(InAppMessagingException("In-App Messaging register activity failed", ex))
}
Expand All @@ -79,13 +80,14 @@ internal class InApp(

@SuppressWarnings("FunctionMaxLength", "TooGenericExceptionCaught")
override fun unregisterMessageDisplayActivity() {
InAppLogger(TAG).info("unregisterMessageDisplayActivity")
InAppLogger(TAG).info("unregisterActivity")
try {
if (configRepo.isConfigEnabled()) {
displayManager.removeMessage(hostAppInfoRepo.getRegisteredActivity(), removeAll = true)
}
hostAppInfoRepo.registerActivity(null)
} catch (ex: Exception) {
InAppLogger(TAG).warn("unregisterActivity - error: ${ex.message}")
errorCallback?.let {
it(InAppMessagingException("In-App Messaging unregister activity failed", ex))
}
Expand All @@ -102,48 +104,50 @@ internal class InApp(
val isSameUser = !accountRepo.updateUserInfo()
val areCampaignsSynced = campaignRepo.lastSyncMillis != null && eventMatchingUtil.eventBuffer.isEmpty()

InAppLogger(TAG).debug(
"name: ${event.getEventName()}, attributes: ${event.getAttributeMap()}, " +
"isConfigEnabled: $isConfigEnabled, isSameUser: $isSameUser, synced: $areCampaignsSynced",
InAppLogger(TAG).info(
"logEvent: ${event.getEventName()} - isConfigEnabled: $isConfigEnabled," +
" isSameUser: $isSameUser, synced: $areCampaignsSynced",
)
InAppLogger(TAG).debug("attributes: ${event.getAttributeMap()}")

if (!isConfigEnabled || !isSameUser || !areCampaignsSynced) {
// To be processed later (flushed after sync)
InAppLogger(TAG).debug("Event added to buffer")
InAppLogger(TAG).debug("event added to buffer")
eventMatchingUtil.addToEventBuffer(event)
}

if (!isSameUser) {
// Sync campaigns, flush event buffer, then match events
InAppLogger(TAG).debug("There is a change in user, will perform onSessionUpdate")
InAppLogger(TAG).debug("there is a change in user, will perform onSessionUpdate")
sessionManager.onSessionUpdate()
return
}

if (areCampaignsSynced) {
// Match event right away
InAppLogger(TAG).debug("Event ${event.getEventName()} will be processed")
InAppLogger(TAG).debug("event ${event.getEventName()} will be processed")
eventsManager.onEventReceived(event)
}
} catch (ex: Exception) {
InAppLogger(TAG).error("logEvent - error: ${ex.message}")
errorCallback?.let {
it(InAppMessagingException("In-App Messaging log event failed", ex))
}
}
}

override fun closeMessage(clearQueuedCampaigns: Boolean) {
InAppLogger(TAG).info("closeMessage - clearQueuedCampaigns: $clearQueuedCampaigns")
InAppLogger(TAG).info("closeMessage: $clearQueuedCampaigns")
closeCampaign(clearQueuedCampaigns = clearQueuedCampaigns)
}

override fun closeTooltip(viewId: String) {
InAppLogger(TAG).info("closeTooltip - viewId: $viewId")
InAppLogger(TAG).info("closeTooltip: $viewId")
closeCampaign(viewId = viewId)
}

override fun trackPushPrimer(permissions: Array<String>, grantResults: IntArray) {
InAppLogger(TAG).info("trackPushPrimer - permissions: $permissions, grantResults: $grantResults")
InAppLogger(TAG).info("trackPushPrimer - perm: $permissions, res: $grantResults")
if (!BuildVersionChecker.isAndroidTAndAbove()) {
return
}
Expand Down Expand Up @@ -178,6 +182,7 @@ internal class InApp(
removeMessage(viewId)
}
} catch (ex: Exception) {
InAppLogger(TAG).warn("closeCampaign - error: ${ex.message}")
errorCallback?.let {
it(InAppMessagingException("In-App Messaging close message failed", ex))
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -133,10 +133,9 @@ abstract class InAppMessaging internal constructor() {
configUrl: String? = null,
enableTooltipFeature: Boolean? = false,
): Boolean {
InAppLogger(TAG).info("configure")
return try {
if (!shouldProcess(subscriptionKey)) {
InAppLogger(TAG).debug("Not processed since RMC is integrated")
InAppLogger(TAG).info("configure called but using RMC, skipping")
return false
}

Expand All @@ -158,6 +157,7 @@ abstract class InAppMessaging internal constructor() {
errorCallback?.let {
it(InAppMessagingException("In-App Messaging configuration failed", ex))
}
InAppLogger(TAG).error("configure - error: ${ex.message}")
false
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -165,7 +165,7 @@ internal class MessageActionsCoroutine(
try {
activityContext.startActivity(intent)
} catch (e: ActivityNotFoundException) {
InAppLogger(TAG).debug(e.message)
InAppLogger(TAG).info("handleDeeplinkRedirection - error: ${e.message}")
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ internal abstract class CampaignRepository {
}

override fun syncWith(messageList: List<Message>, timestampMillis: Long, ignoreTooltips: Boolean) {
InAppLogger(TAG).debug("START - message size: ${messageList.size}")
InAppLogger(TAG).info("syncWith start")
lastSyncMillis = timestampMillis
loadCachedData() // ensure we're using latest cache data for syncing below
val oldList = LinkedHashMap(messages) // copy
Expand All @@ -68,7 +68,7 @@ internal abstract class CampaignRepository {
messages[updatedCampaign.campaignId] = updatedCampaign
}
saveDataToCache()
InAppLogger(TAG).debug("END")
InAppLogger(TAG).info("syncWith end")
}

private fun List<Message>.filterMessages(ignoreTooltips: Boolean): List<Message> {
Expand Down Expand Up @@ -99,13 +99,10 @@ internal abstract class CampaignRepository {
}

override fun optOutCampaign(id: String): Message? {
InAppLogger(TAG).debug("Campaign: $id}")
InAppLogger(TAG).debug("campaign: $id}")
val localCampaign = messages[id]
if (localCampaign == null) {
InAppLogger(TAG).debug(
"Campaign ($id) could not be updated -" +
"not found in the repository",
)
InAppLogger(TAG).debug("campaign not found in repository")
return null
}
val updatedCampaign = localCampaign.apply { isOptedOut = true }
Expand All @@ -116,7 +113,7 @@ internal abstract class CampaignRepository {
}

override fun decrementImpressions(id: String): Message? {
InAppLogger(TAG).debug("Campaign: $id")
InAppLogger(TAG).debug("campaign: $id")
val campaign = messages[id] ?: return null
return updateImpressions(
campaign,
Expand All @@ -136,7 +133,7 @@ internal abstract class CampaignRepository {
@SuppressWarnings("TooGenericExceptionCaught")
private fun loadCachedData() {
if (InAppMessaging.instance().isLocalCachingEnabled()) {
InAppLogger(TAG).debug("START")
InAppLogger(TAG).debug("start")
messages.clear()
try {
val jsonObject = JSONObject(retrieveData())
Expand All @@ -146,9 +143,9 @@ internal abstract class CampaignRepository {
)
}
} catch (ex: Exception) {
InAppLogger(TAG).debug(ex.cause, "Invalid JSON format for $IAM_USER_CACHE data")
InAppLogger(TAG).debug(ex.cause, "invalid JSON format for $IAM_USER_CACHE data")
}
InAppLogger(TAG).debug("END")
InAppLogger(TAG).debug("end")
}
}

Expand All @@ -161,7 +158,8 @@ internal abstract class CampaignRepository {
key = IAM_USER_CACHE,
defValue = "",
)
InAppLogger(TAG).debug("Cache Read - file: $preferenceFile, data: $preferenceData")
InAppLogger(TAG).info("retrieveData - file: $preferenceFile")
InAppLogger(TAG).debug("retrieveData - data: $preferenceData")
preferenceData
}.orEmpty()
}
Expand All @@ -171,7 +169,8 @@ internal abstract class CampaignRepository {
HostAppInfoRepository.instance().getContext()?.let { ctx ->
val preferenceFile = InAppMessaging.getPreferencesFile()
val preferenceData = Gson().toJson(messages)
InAppLogger(TAG).debug("Cache Write - file: $preferenceFile, data: $preferenceData")
InAppLogger(TAG).info("saveData - file: $preferenceFile")
InAppLogger(TAG).debug("saveData - data: $preferenceData")
PreferencesUtil.putString(
context = ctx,
name = preferenceFile,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,8 @@ internal data class Message(
tooltip = null
}
} catch (je: JsonParseException) {
InAppLogger(TAG).warn("Invalid format for tooltip config.", je)
InAppLogger(TAG).warn("getTooltipConfig - invalid tooltip format")
InAppLogger(TAG).debug("parse exception: $je")
}
}
return tooltip
Expand All @@ -86,7 +87,8 @@ internal data class Message(
try {
customJsonData = Gson().fromJson(customJson, CustomJson::class.java)
} catch (je: JsonParseException) {
InAppLogger(TAG).warn("Invalid format/representation for CustomJson", je)
InAppLogger(TAG).warn("getCustomJsonData - invalid customJson format")
InAppLogger(TAG).debug("parse exception: $je")
}
}
return customJsonData
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,15 @@ package com.rakuten.tech.mobile.inappmessaging.runtime.extensions

import android.Manifest
import android.app.Activity
import android.content.ActivityNotFoundException
import android.content.Intent
import android.os.Build
import androidx.annotation.RequiresApi
import androidx.core.app.ActivityCompat
import com.rakuten.tech.mobile.inappmessaging.runtime.InAppMessaging
import com.rakuten.tech.mobile.inappmessaging.runtime.utils.InAppLogger

private const val TAG = "IAM_ActivityExt"

/**
* Prompts the push notification permission dialog if applicable.
Expand All @@ -24,5 +28,9 @@ internal fun Activity.openAppNotifPermissionSettings() {
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
intent.putExtra("android.provider.extra.APP_PACKAGE", this.packageName)

this.startActivity(intent)
try {
this.startActivity(intent)
} catch (e: ActivityNotFoundException) {
InAppLogger(TAG).info("openAppNotifPermissionSettings - error: ${e.message}")
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -165,7 +165,7 @@ internal interface DisplayManager {
parent.removeView(inAppMessageBaseView)
}

InAppLogger(TAG).debug("View removed")
InAppLogger(TAG).debug("view removed")
}

private fun removeTooltip(parent: ViewGroup, id: String?, activity: Activity) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -112,13 +112,13 @@ internal class MessageReadinessManager(
for (messageId in queuedMessagesCopy) {
val message = campaignRepo.messages[messageId]
if (message == null) {
InAppLogger(TAG).debug("Queued campaign $messageId does not exist in the repository anymore")
InAppLogger(TAG).debug("queued campaign $messageId does not exist in the repository anymore")
continue
}

// First, check if this message should be displayed.
if (!shouldDisplayMessage(message)) {
InAppLogger(TAG).debug("Skipping message: ${message.campaignId}")
InAppLogger(TAG).info("campaign won't be displayed: ${message.campaignId}")
// Skip to next message.
continue
}
Expand All @@ -136,11 +136,10 @@ internal class MessageReadinessManager(

@SuppressWarnings("LongMethod")
private fun shouldPing(message: Message, result: MutableList<Message>) = if (message.isTest) {
InAppLogger(TAG).debug("Skipping test message: ${message.campaignId}")
InAppLogger(TAG).debug("skipping test message: ${message.campaignId}")
result.add(message)
false
} else {
InAppLogger(TAG).debug("Check API START - campaignId: ${message.campaignId}")
// Check message display permission with server.
val displayPermissionResponse = getMessagePermission(message)
// If server wants SDK to ping for updated messages, do a new ping request and break this loop.
Expand Down Expand Up @@ -260,7 +259,7 @@ internal class MessageReadinessManager(
handleResponse(response, call.clone())
} catch (e: Exception) {
checkAndRetry(call.clone()) {
InAppLogger(DISP_TAG).error(e.message)
InAppLogger(DISP_TAG).error("executeDisplayRequest - error: ${e.message}")
InAppMessaging.errorCallback?.let {
it(InAppMessagingException("In-App Messaging display permission request failed", e))
}
Expand All @@ -272,7 +271,7 @@ internal class MessageReadinessManager(
response: Response<DisplayPermissionResponse>,
callClone: Call<DisplayPermissionResponse>,
): DisplayPermissionResponse? {
InAppLogger(DISP_TAG).debug("Check API END - code: ${response.code()}, body: ${response.body()}")
InAppLogger(DISP_TAG).info("check API - code: ${response.code()}")
return when {
response.isSuccessful -> response.body()
response.code() >= HttpURLConnection.HTTP_INTERNAL_ERROR -> checkAndRetry(callClone) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ internal abstract class EventMatchingUtil {
val totalMatchedEvents = campaignEvents.count() + persistentEvents.count()

if (!(totalMatchedEvents > 0 && totalMatchedEvents >= eventsToRemove.size)) {
InAppLogger(TAG).debug("Couldn't find set of events")
InAppLogger(TAG).debug("couldn't find set of events")
return false
}

Expand Down Expand Up @@ -121,7 +121,7 @@ internal abstract class EventMatchingUtil {
}
val index = campaignEvents.indexOf(eventToRemove)
if (index == -1) {
InAppLogger(TAG).debug("Couldn't find requested set of events")
InAppLogger(TAG).debug("couldn't find requested set of events")
return true
}
campaignEvents.removeAt(index)
Expand All @@ -136,15 +136,15 @@ internal abstract class EventMatchingUtil {
override fun addToEventBuffer(event: Event) {
synchronized(eventBuffer) {
eventBuffer.add(event)
InAppLogger(TAG).debug("Buffer: " + eventBuffer.map { it.getEventName() })
InAppLogger(TAG).debug("buffer: " + eventBuffer.map { it.getEventName() })
}
}

override fun flushEventBuffer() {
synchronized(eventBuffer) {
eventBuffer.forEach { ev -> matchAndStore(ev) }
eventBuffer.clear()
InAppLogger(TAG).debug("Buffer: []")
InAppLogger(TAG).debug("buffer: []")
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,12 @@ package com.rakuten.tech.mobile.inappmessaging.runtime.utils

import com.rakuten.tech.mobile.sdkutils.logger.Logger

/**
* Error, warn, and info logs are logged regardless of build configuration as per standard:
* https://source.android.com/docs/core/tests/debug/understanding-logging#log-level-guidelines
*
* Debug logs are logged only if host app enables it through manifest metadata.
*/
internal class InAppLogger(tag: String) : Logger(tag) {
init {
this.setDebug(isDebug)
Expand Down
Loading
Loading