refactor: simplify PlatformLog actuals and convert remaining interpolated log calls to lambdas

- Extract private log() helper in JVM and iOS PlatformLog to reduce
  copy-paste branching
- Fix JVM formatter to be private and non-nullable
- Convert 60+ interpolated Log.w/e/i calls to lambda overloads,
  including hot-path Filter.kt toJson() and LocalCache event processing

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
davotoula
2026-03-28 16:38:07 +01:00
parent 3b81731771
commit 6d89de9444
42 changed files with 107 additions and 130 deletions
@@ -254,7 +254,7 @@ object LocalPreferences {
val prefsDir = File(prefsDirPath) val prefsDir = File(prefsDirPath)
prefsDir.list()?.forEach { prefsDir.list()?.forEach {
if (it.contains(npub) && !File(prefsDir, it).delete()) { if (it.contains(npub) && !File(prefsDir, it).delete()) {
Log.w("LocalPreferences", "Failed to delete preference file: $it") Log.w("LocalPreferences") { "Failed to delete preference file: $it" }
} }
} }
} }
@@ -87,7 +87,7 @@ class AntiSpamFilter {
val link1 = njumpLink(NAddress.create(existingAddress.kind, existingAddress.pubKeyHex, existingAddress.dTag, relay)) val link1 = njumpLink(NAddress.create(existingAddress.kind, existingAddress.pubKeyHex, existingAddress.dTag, relay))
val link2 = njumpLink(NAddress.create(event.kind, event.pubKey, event.dTag(), relay)) val link2 = njumpLink(NAddress.create(event.kind, event.pubKey, event.dTag(), relay))
Log.w("Duplicated/SPAM", "${relay?.url} $link1 $link2") Log.w("Duplicated/SPAM") { "${relay?.url} $link1 $link2" }
// Log down offenders // Log down offenders
val spammer = logOffender(hash, event) val spammer = logOffender(hash, event)
@@ -114,7 +114,7 @@ class AntiSpamFilter {
val link1 = njumpLink(NEvent.create(existingEvent, null, null, relay)) val link1 = njumpLink(NEvent.create(existingEvent, null, null, relay))
val link2 = njumpLink(NEvent.create(event.id, null, null, relay)) val link2 = njumpLink(NEvent.create(event.id, null, null, relay))
Log.w("Duplicated/SPAM", "${relay?.url} $link1 $link2") Log.w("Duplicated/SPAM") { "${relay?.url} $link1 $link2" }
// Log down offenders // Log down offenders
val spammer = logOffender(hash, event) val spammer = logOffender(hash, event)
@@ -1931,7 +1931,7 @@ object LocalCache : ILocalCache, ICacheProvider {
if (new) { if (new) {
val channel = checkGetOrCreatePublicChatChannel(channelId) val channel = checkGetOrCreatePublicChatChannel(channelId)
if (channel == null) { if (channel == null) {
Log.w("LocalCache", "Unable to create public chat channel for event ${event.toJson()}") Log.w("LocalCache") { "Unable to create public chat channel for event ${event.toJson()}" }
return false return false
} }
@@ -2019,7 +2019,7 @@ object LocalCache : ILocalCache, ICacheProvider {
val zapRequest = event.zapRequest?.id?.let { getNoteIfExists(it) } val zapRequest = event.zapRequest?.id?.let { getNoteIfExists(it) }
if (zapRequest == null || zapRequest.event !is LnZapRequestEvent) { if (zapRequest == null || zapRequest.event !is LnZapRequestEvent) {
Log.e("ZP", "Zap Request not found. Unable to process Zap {${event.toJson()}}") Log.e("ZP") { "Zap Request not found. Unable to process Zap {${event.toJson()}}" }
return false return false
} }
@@ -2924,7 +2924,7 @@ object LocalCache : ILocalCache, ICacheProvider {
event.checkSignature() event.checkSignature()
} catch (e: Exception) { } catch (e: Exception) {
if (e is CancellationException) throw e if (e is CancellationException) throw e
Log.w("Event Verification Failed", "Kind: ${event.kind} from ${dateFormatter(event.createdAt, "", "")} with message ${e.message}") Log.w("Event Verification Failed") { "Kind: ${event.kind} from ${dateFormatter(event.createdAt, "", "")} with message ${e.message}" }
} }
false false
} else { } else {
@@ -3247,7 +3247,7 @@ object LocalCache : ILocalCache, ICacheProvider {
is WebBookmarkEvent -> consume(event, relay, wasVerified) is WebBookmarkEvent -> consume(event, relay, wasVerified)
is WikiNoteEvent -> consume(event, relay, wasVerified) is WikiNoteEvent -> consume(event, relay, wasVerified)
is PaymentTargetsEvent -> consume(event, relay, wasVerified) is PaymentTargetsEvent -> consume(event, relay, wasVerified)
else -> Log.w("Event Not Supported", "From ${relay?.url}: ${event.toJson()}").let { false } else -> Log.w("Event Not Supported") { "From ${relay?.url}: ${event.toJson()}" }.let { false }
} }
} catch (e: Exception) { } catch (e: Exception) {
if (e is CancellationException) throw e if (e is CancellationException) throw e
@@ -46,7 +46,7 @@ fun loadRelayInfo(
value = it value = it
}, },
onError = { url, errorCode, exceptionMessage -> onError = { url, errorCode, exceptionMessage ->
Log.e("RelayInfo", "Error loading relay info for ${relay.url}: $errorCode - $exceptionMessage") Log.e("RelayInfo") { "Error loading relay info for ${relay.url}: $errorCode - $exceptionMessage" }
}, },
) )
} }
@@ -128,7 +128,7 @@ class NamecoinSharedPreferences(
} }
} catch (e: Exception) { } catch (e: Exception) {
if (e is CancellationException) throw e if (e is CancellationException) throw e
Log.e("NamecoinPrefs", "Error writing pinned certs: ${e.message}") Log.e("NamecoinPrefs") { "Error writing pinned certs: ${e.message}" }
} }
} }
@@ -159,7 +159,7 @@ class NamecoinSharedPreferences(
} }
} catch (e: Exception) { } catch (e: Exception) {
if (e is CancellationException) throw e if (e is CancellationException) throw e
Log.e("NamecoinPrefs", "Error writing DataStore: ${e.message}") Log.e("NamecoinPrefs") { "Error writing DataStore: ${e.message}" }
} }
} }
@@ -181,7 +181,7 @@ class NamecoinSharedPreferences(
NamecoinSettings(enabled = enabled, customServers = servers) NamecoinSettings(enabled = enabled, customServers = servers)
} catch (e: Exception) { } catch (e: Exception) {
if (e is CancellationException) throw e if (e is CancellationException) throw e
Log.e("NamecoinPrefs", "Error reading DataStore: ${e.message}") Log.e("NamecoinPrefs") { "Error reading DataStore: ${e.message}" }
null null
} }
} }
@@ -86,7 +86,7 @@ class OtsSharedPreferences(
} }
} catch (e: Exception) { } catch (e: Exception) {
if (e is CancellationException) throw e if (e is CancellationException) throw e
Log.e("OtsPrefs", "Error writing DataStore: ${e.message}") Log.e("OtsPrefs") { "Error writing DataStore: ${e.message}" }
} }
} }
@@ -97,7 +97,7 @@ class OtsSharedPreferences(
OtsSettings(customExplorerUrl = url) OtsSettings(customExplorerUrl = url)
} catch (e: Exception) { } catch (e: Exception) {
if (e is CancellationException) throw e if (e is CancellationException) throw e
Log.e("OtsPrefs", "Error reading DataStore: ${e.message}") Log.e("OtsPrefs") { "Error reading DataStore: ${e.message}" }
null null
} }
} }
@@ -106,7 +106,7 @@ class TorSharedPreferences(
} catch (e: Exception) { } catch (e: Exception) {
if (e is CancellationException) throw e if (e is CancellationException) throw e
// Log any errors that occur while reading the DataStore. // Log any errors that occur while reading the DataStore.
Log.e("SharedPreferences", "Error reading DataStore preferences: ${e.message}") Log.e("SharedPreferences") { "Error reading DataStore preferences: ${e.message}" }
null null
} }
@@ -130,7 +130,7 @@ class TorSharedPreferences(
} catch (e: Exception) { } catch (e: Exception) {
if (e is CancellationException) throw e if (e is CancellationException) throw e
// Log any errors that occur while reading the DataStore. // Log any errors that occur while reading the DataStore.
Log.e("SharedPreferences", "Error saving DataStore preferences: ${e.message}") Log.e("SharedPreferences") { "Error saving DataStore preferences: ${e.message}" }
} }
} }
} }
@@ -127,7 +127,7 @@ class UiSharedPreferences(
} catch (e: Exception) { } catch (e: Exception) {
if (e is CancellationException) throw e if (e is CancellationException) throw e
// Log any errors that occur while reading the DataStore. // Log any errors that occur while reading the DataStore.
Log.e("SharedPreferences", "Error reading DataStore preferences: ${e.message}") Log.e("SharedPreferences") { "Error reading DataStore preferences: ${e.message}" }
try { try {
val oldVersion = LocalPreferences.loadSharedSettings() val oldVersion = LocalPreferences.loadSharedSettings()
@@ -159,7 +159,7 @@ class UiSharedPreferences(
} catch (e: Exception) { } catch (e: Exception) {
if (e is CancellationException) throw e if (e is CancellationException) throw e
// Log any errors that occur while reading the DataStore. // Log any errors that occur while reading the DataStore.
Log.e("SharedPreferences", "Error saving DataStore preferences: ${e.message}") Log.e("SharedPreferences") { "Error saving DataStore preferences: ${e.message}" }
} }
} }
} }
@@ -59,7 +59,7 @@ class ReverseGeolocation {
override fun onError(errorMessage: String?) { override fun onError(errorMessage: String?) {
super.onError(errorMessage) super.onError(errorMessage)
Log.w("ReverseGeoLocation", "Failure $errorMessage") Log.w("ReverseGeoLocation") { "Failure $errorMessage" }
onReady(null) onReady(null)
} }
} }
@@ -41,7 +41,7 @@ object ChoreographerHelper {
if (diff > 35) { if (diff > 35) {
// Follow the frame number // Follow the frame number
val droppedCount = (diff / 16.6).toInt() val droppedCount = (diff / 16.6).toInt()
Log.w("block-canary", "Dropped $droppedCount frames. Skipped $diff ms") Log.w("block-canary") { "Dropped $droppedCount frames. Skipped $diff ms" }
} }
lastFrameTimeNanos = frameTimeNanos lastFrameTimeNanos = frameTimeNanos
Choreographer.getInstance().postFrameCallback(this) Choreographer.getInstance().postFrameCallback(this)
@@ -85,7 +85,7 @@ class NotificationReplyReceiver : BroadcastReceiver() {
notificationManager.cancel(notificationId) notificationManager.cancel(notificationId)
} catch (e: Exception) { } catch (e: Exception) {
if (e is CancellationException) throw e if (e is CancellationException) throw e
Log.e("NotificationReply", "Failed to send reply: ${e.message}") Log.e("NotificationReply") { "Failed to send reply: ${e.message}" }
} finally { } finally {
pendingResult.finish() pendingResult.finish()
@@ -96,7 +96,7 @@ object PlaybackServiceClient {
try { try {
MediaController.releaseFuture(controllerFuture) MediaController.releaseFuture(controllerFuture)
} catch (e: Exception) { } catch (e: Exception) {
Log.e("Playback Client", "Failed to release Playback Client for $id $videoUri ${e.message}") Log.e("Playback Client") { "Failed to release Playback Client for $id $videoUri ${e.message}" }
} }
} }
} }
@@ -58,7 +58,7 @@ class FileHeader(
} }
} catch (e: Exception) { } catch (e: Exception) {
if (e is CancellationException) throw e if (e is CancellationException) throw e
Log.e("ImageDownload", "Couldn't download image from server: ${e.message}") Log.e("ImageDownload") { "Couldn't download image from server: ${e.message}" }
Result.failure(e) Result.failure(e)
} }
@@ -76,7 +76,7 @@ class FileHeader(
Result.success(FileHeader(mimeType, hash, size, dim, blurHash)) Result.success(FileHeader(mimeType, hash, size, dim, blurHash))
} catch (e: Exception) { } catch (e: Exception) {
if (e is CancellationException) throw e if (e is CancellationException) throw e
Log.e("ImageDownload", "Couldn't convert image in to File Header: ${e.message}") Log.e("ImageDownload") { "Couldn't convert image in to File Header: ${e.message}" }
Result.failure(e) Result.failure(e)
} }
} }
@@ -99,7 +99,7 @@ class MediaCompressor {
default(width = 640, format = Bitmap.CompressFormat.JPEG, quality = imageQuality) default(width = 640, format = Bitmap.CompressFormat.JPEG, quality = imageQuality)
} }
if (tempFile != compressedImageFile && !tempFile.delete()) { if (tempFile != compressedImageFile && !tempFile.delete()) {
Log.w("MediaCompressor", "Failed to delete temp file: ${tempFile.absolutePath}") Log.w("MediaCompressor") { "Failed to delete temp file: ${tempFile.absolutePath}" }
} }
Log.d("MediaCompressor") { "Image compression success. New size [${compressedImageFile.length()}]" } Log.d("MediaCompressor") { "Image compression success. New size [${compressedImageFile.length()}]" }
MediaCompressorResult(compressedImageFile.toUri(), MimeTypes.IMAGE_JPEG, compressedImageFile.length()) MediaCompressorResult(compressedImageFile.toUri(), MimeTypes.IMAGE_JPEG, compressedImageFile.length())
@@ -107,7 +107,7 @@ class MediaCompressor {
if (e is CancellationException) throw e if (e is CancellationException) throw e
Log.d("MediaCompressor") { "Image compression failed: ${e.message}" } Log.d("MediaCompressor") { "Image compression failed: ${e.message}" }
if (tempFile?.delete() == false) { if (tempFile?.delete() == false) {
Log.w("MediaCompressor", "Failed to delete temp file: ${tempFile.absolutePath}") Log.w("MediaCompressor") { "Failed to delete temp file: ${tempFile.absolutePath}" }
} }
MediaCompressorResult(uri, contentType, null) MediaCompressorResult(uri, contentType, null)
} }
@@ -172,7 +172,7 @@ object MetadataStripper {
muxer?.release() muxer?.release()
extractor.release() extractor.release()
if (!succeeded && !outputFile.delete()) { if (!succeeded && !outputFile.delete()) {
Log.w("MetadataStripper", "Failed to delete temp file: ${outputFile.absolutePath}") Log.w("MetadataStripper") { "Failed to delete temp file: ${outputFile.absolutePath}" }
} }
} }
return succeeded return succeeded
@@ -202,7 +202,7 @@ object MetadataStripper {
context.contentResolver.openInputStream(uri) context.contentResolver.openInputStream(uri)
?: run { ?: run {
if (!tempFile.delete()) { if (!tempFile.delete()) {
Log.w("MetadataStripper", "Failed to delete temp file: ${tempFile.absolutePath}") Log.w("MetadataStripper") { "Failed to delete temp file: ${tempFile.absolutePath}" }
} }
return StrippingResult(uri, false) return StrippingResult(uri, false)
} }
@@ -223,7 +223,7 @@ object MetadataStripper {
} catch (e: Exception) { } catch (e: Exception) {
if (e is CancellationException) throw e if (e is CancellationException) throw e
if (tempFile?.delete() == false) { if (tempFile?.delete() == false) {
Log.w("MetadataStripper", "Failed to delete temp file: ${tempFile.absolutePath}") Log.w("MetadataStripper") { "Failed to delete temp file: ${tempFile.absolutePath}" }
} }
Log.d("MetadataStripper") { "Failed to strip image metadata: ${e.message}" } Log.d("MetadataStripper") { "Failed to strip image metadata: ${e.message}" }
StrippingResult(uri, false) StrippingResult(uri, false)
@@ -311,7 +311,7 @@ object MetadataStripper {
} }
} ?: run { } ?: run {
if (!tempInputFile.delete()) { if (!tempInputFile.delete()) {
Log.w("MetadataStripper", "Failed to delete temp file: ${tempInputFile.absolutePath}") Log.w("MetadataStripper") { "Failed to delete temp file: ${tempInputFile.absolutePath}" }
} }
return StrippingResult(uri, false) return StrippingResult(uri, false)
} }
@@ -354,7 +354,7 @@ object MetadataStripper {
if (startOffset == 0L && endOffset == fileSize) { if (startOffset == 0L && endOffset == fileSize) {
if (!tempInputFile.delete()) { if (!tempInputFile.delete()) {
Log.w("MetadataStripper", "Failed to delete temp file: ${tempInputFile.absolutePath}") Log.w("MetadataStripper") { "Failed to delete temp file: ${tempInputFile.absolutePath}" }
} }
tempInputFile = null tempInputFile = null
return StrippingResult(uri, true) // no tags found, already clean return StrippingResult(uri, true) // no tags found, already clean
@@ -376,7 +376,7 @@ object MetadataStripper {
} }
} }
if (!tempInputFile.delete()) { if (!tempInputFile.delete()) {
Log.w("MetadataStripper", "Failed to delete temp file: ${tempInputFile.absolutePath}") Log.w("MetadataStripper") { "Failed to delete temp file: ${tempInputFile.absolutePath}" }
} }
tempInputFile = null tempInputFile = null
@@ -385,7 +385,7 @@ object MetadataStripper {
} catch (e: Exception) { } catch (e: Exception) {
if (e is CancellationException) throw e if (e is CancellationException) throw e
if (tempInputFile?.delete() == false) { if (tempInputFile?.delete() == false) {
Log.w("MetadataStripper", "Failed to delete temp file: ${tempInputFile.absolutePath}") Log.w("MetadataStripper") { "Failed to delete temp file: ${tempInputFile.absolutePath}" }
} }
Log.d("MetadataStripper") { "Failed to strip MP3 metadata: ${e.message}" } Log.d("MetadataStripper") { "Failed to strip MP3 metadata: ${e.message}" }
StrippingResult(uri, false) StrippingResult(uri, false)
@@ -233,7 +233,7 @@ object VideoCompressionHelper {
// Sanity check: compression not smaller than original // Sanity check: compression not smaller than original
if (originalSize in 1..size) { if (originalSize in 1..size) {
if (!File(path).delete()) { if (!File(path).delete()) {
Log.w("VideoCompressionHelper", "Failed to delete compressed file: $path") Log.w("VideoCompressionHelper") { "Failed to delete compressed file: $path" }
} }
applicationContext.notifyUser( applicationContext.notifyUser(
"Compressed file larger than original. Using original.", "Compressed file larger than original. Using original.",
@@ -960,7 +960,7 @@ private suspend fun shareVideoFile(
delay(SHARED_VIDEO_CLEANUP_DELAY_MS) delay(SHARED_VIDEO_CLEANUP_DELAY_MS)
sharedFile?.let { file -> sharedFile?.let { file ->
if (!file.delete()) { if (!file.delete()) {
Log.w("ZoomableContentView", "Failed to delete shared file: ${file.path}") Log.w("ZoomableContentView") { "Failed to delete shared file: ${file.path}" }
} }
} }
} }
@@ -974,11 +974,11 @@ private suspend fun shareVideoFile(
// Clean up temp file on error // Clean up temp file on error
if (!tempFile.delete()) { if (!tempFile.delete()) {
Log.w("ZoomableContentView", "Failed to delete temp file: ${tempFile.path}") Log.w("ZoomableContentView") { "Failed to delete temp file: ${tempFile.path}" }
} }
sharedFile?.let { file -> sharedFile?.let { file ->
if (!file.delete()) { if (!file.delete()) {
Log.w("ZoomableContentView", "Failed to delete shared file: ${file.path}") Log.w("ZoomableContentView") { "Failed to delete shared file: ${file.path}" }
} }
} }
@@ -361,7 +361,7 @@ fun DisplayEntryForAUrl(
try { try {
URL(url) URL(url)
} catch (_: Exception) { } catch (_: Exception) {
Log.w("Note Compose", "Invalid URI: $url") Log.w("Note Compose") { "Invalid URI: $url" }
null null
} }
} }
@@ -134,7 +134,7 @@ class EventProcessor(
} }
if (deletedDrafts.isNotEmpty()) { if (deletedDrafts.isNotEmpty()) {
Log.w("EventProcessor", "Deleting ${deletedDrafts.size} draft notes") Log.w("EventProcessor") { "Deleting ${deletedDrafts.size} draft notes" }
account.delete(deletedDrafts) account.delete(deletedDrafts)
} }
} }
@@ -40,7 +40,7 @@ class HiddenAccountsFeedFilter(
LocalCache.getOrCreateUser(it) LocalCache.getOrCreateUser(it)
} catch (e: Exception) { } catch (e: Exception) {
if (e is CancellationException) throw e if (e is CancellationException) throw e
Log.e("HiddenAccountsFeedFilter", "Failed to parse key $it") Log.e("HiddenAccountsFeedFilter") { "Failed to parse key $it" }
null null
} }
} }
@@ -167,7 +167,7 @@ class RobohashAssembler {
if (Hex.isHex(msg) && msg.length > 10) { if (Hex.isHex(msg) && msg.length > 10) {
Hex.decode(msg) Hex.decode(msg)
} else { } else {
Log.w("Robohash", "$msg is not a hex") Log.w("Robohash") { "$msg is not a hex" }
sha256(msg.toByteArray()) sha256(msg.toByteArray())
} }
@@ -23,51 +23,40 @@ package com.vitorpamplona.quartz.utils
import platform.Foundation.NSLog import platform.Foundation.NSLog
actual object PlatformLog { actual object PlatformLog {
actual fun w( private fun log(
level: String,
tag: String, tag: String,
message: String, message: String,
throwable: Throwable?, throwable: Throwable?,
) { ) {
if (throwable != null) { if (throwable != null) {
NSLog("WARN: [$tag] $message. Throwable: $throwable CAUSE ${throwable.cause}") NSLog("$level: [$tag] $message. Throwable: $throwable CAUSE ${throwable.cause}")
} else { } else {
NSLog("WARN: [$tag] $message") NSLog("$level: [$tag] $message")
} }
} }
actual fun w(
tag: String,
message: String,
throwable: Throwable?,
) = log("WARN", tag, message, throwable)
actual fun e( actual fun e(
tag: String, tag: String,
message: String, message: String,
throwable: Throwable?, throwable: Throwable?,
) { ) = log("ERROR", tag, message, throwable)
if (throwable != null) {
NSLog("ERROR: [$tag] $message. Throwable: $throwable CAUSE ${throwable.cause}")
} else {
NSLog("ERROR: [$tag] $message")
}
}
actual fun d( actual fun d(
tag: String, tag: String,
message: String, message: String,
throwable: Throwable?, throwable: Throwable?,
) { ) = log("DEBUG", tag, message, throwable)
if (throwable != null) {
NSLog("DEBUG: [$tag] $message. Throwable: $throwable CAUSE ${throwable.cause}")
} else {
NSLog("DEBUG: [$tag] $message")
}
}
actual fun i( actual fun i(
tag: String, tag: String,
message: String, message: String,
throwable: Throwable?, throwable: Throwable?,
) { ) = log("INFO", tag, message, throwable)
if (throwable != null) {
NSLog("INFO: [$tag] $message. Throwable: $throwable CAUSE ${throwable.cause}")
} else {
NSLog("INFO: [$tag] $message")
}
}
} }
@@ -46,7 +46,7 @@ class AddressSerializer {
if (parts.size > 2 && parts[1].length == 64 && Hex.isHex(parts[1])) { if (parts.size > 2 && parts[1].length == 64 && Hex.isHex(parts[1])) {
if (parts[0].length > 5) { if (parts[0].length > 5) {
// invalid kind // invalid kind
Log.w("AddressableId", "Error parsing. invalid kind $addressId") Log.w("AddressableId") { "Error parsing. invalid kind $addressId" }
null null
} else { } else {
Address(parts[0].toInt(), parts[1], parts.getOrNull(2) ?: "") Address(parts[0].toInt(), parts[1], parts.getOrNull(2) ?: "")
@@ -57,11 +57,11 @@ class AddressSerializer {
if (addr is NAddress) { if (addr is NAddress) {
addr.address() addr.address()
} else { } else {
Log.w("AddressableId", "Error parsing. naddr1 seems invalid: $addressId") Log.w("AddressableId") { "Error parsing. naddr1 seems invalid: $addressId" }
null null
} }
} else { } else {
Log.w("AddressableId", "Error parsing. Not a valid address: $addressId") Log.w("AddressableId") { "Error parsing. Not a valid address: $addressId" }
null null
} }
} }
@@ -71,7 +71,7 @@ class MetadataEvent(
Json.parseToJsonElement(content) as JsonObject Json.parseToJsonElement(content) as JsonObject
} catch (e: Exception) { } catch (e: Exception) {
if (e is CancellationException) throw e if (e is CancellationException) throw e
Log.w("MetadataEvent", "Content Parse Error: ${toNostrUri()} ${e.message}") Log.w("MetadataEvent") { "Content Parse Error: ${toNostrUri()} ${e.message}" }
null null
} }
@@ -80,7 +80,7 @@ class MetadataEvent(
JsonMapper.fromJson<UserMetadata>(content) JsonMapper.fromJson<UserMetadata>(content)
} catch (e: Exception) { } catch (e: Exception) {
if (e is CancellationException) throw e if (e is CancellationException) throw e
Log.w("MetadataEvent", "Content Parse Error: ${toNostrUri()} ${e.message}") Log.w("MetadataEvent") { "Content Parse Error: ${toNostrUri()} ${e.message}" }
null null
} }
@@ -36,7 +36,7 @@ fun List<RelayBasedFilter>.groupByRelay(): Map<NormalizedRelayUrl, List<Filter>>
val result = mutableMapOf<NormalizedRelayUrl, MutableList<Filter>>() val result = mutableMapOf<NormalizedRelayUrl, MutableList<Filter>>()
for (relayBasedFilter in this) { for (relayBasedFilter in this) {
if (relayBasedFilter.filter.isEmpty()) { if (relayBasedFilter.filter.isEmpty()) {
Log.e("FilterError", "Ignoring empty filter for ${relayBasedFilter.relay}") Log.e("FilterError") { "Ignoring empty filter for ${relayBasedFilter.relay}" }
} else { } else {
result.getOrPut(relayBasedFilter.relay) { mutableListOf() }.add(relayBasedFilter.filter) result.getOrPut(relayBasedFilter.relay) { mutableListOf() }.add(relayBasedFilter.filter)
} }
@@ -91,32 +91,32 @@ class Filter(
init { init {
ids?.forEach { ids?.forEach {
if (it.length != 64) Log.e("FilterError", "Invalid id length $it on ${toJson()}") if (it.length != 64) Log.e("FilterError") { "Invalid id length $it on ${toJson()}" }
} }
authors?.forEach { authors?.forEach {
if (it.length != 64) Log.e("FilterError", "Invalid author length $it on ${toJson()}") if (it.length != 64) Log.e("FilterError") { "Invalid author length $it on ${toJson()}" }
} }
// tests common tags. // tests common tags.
if (tags != null) { if (tags != null) {
tags["p"]?.forEach { tags["p"]?.forEach {
if (it.length != 64) Log.e("FilterError", "Invalid p-tag length $it on ${toJson()}") if (it.length != 64) Log.e("FilterError") { "Invalid p-tag length $it on ${toJson()}" }
} }
tags["e"]?.forEach { tags["e"]?.forEach {
if (it.length != 64) Log.e("FilterError", "Invalid e-tag length $it on ${toJson()}") if (it.length != 64) Log.e("FilterError") { "Invalid e-tag length $it on ${toJson()}" }
} }
tags["a"]?.forEach { tags["a"]?.forEach {
if (Address.parse(it) == null) Log.e("FilterError", "Invalid a-tag $it on ${toJson()}") if (Address.parse(it) == null) Log.e("FilterError") { "Invalid a-tag $it on ${toJson()}" }
} }
} }
if (tagsAll != null) { if (tagsAll != null) {
tagsAll["p"]?.forEach { tagsAll["p"]?.forEach {
if (it.length != 64) Log.e("FilterError", "Invalid p-tag length $it on ${toJson()}") if (it.length != 64) Log.e("FilterError") { "Invalid p-tag length $it on ${toJson()}" }
} }
tagsAll["e"]?.forEach { tagsAll["e"]?.forEach {
if (it.length != 64) Log.e("FilterError", "Invalid e-tag length $it on ${toJson()}") if (it.length != 64) Log.e("FilterError") { "Invalid e-tag length $it on ${toJson()}" }
} }
tagsAll["a"]?.forEach { tagsAll["a"]?.forEach {
if (Address.parse(it) == null) Log.e("FilterError", "Invalid a-tag $it on ${toJson()}") if (Address.parse(it) == null) Log.e("FilterError") { "Invalid a-tag $it on ${toJson()}" }
} }
} }
} }
@@ -145,7 +145,7 @@ class RelayUrlNormalizer {
if (trimmed.contains("://")) { if (trimmed.contains("://")) {
// some other scheme we cannot connect to. // some other scheme we cannot connect to.
Log.w("RelayUrlNormalizer", "Rejected $url") Log.w("RelayUrlNormalizer") { "Rejected $url" }
return null return null
} }
@@ -178,14 +178,14 @@ class RelayUrlNormalizer {
normalizedUrls.put(url, NormalizationResult.Success(normalized)) normalizedUrls.put(url, NormalizationResult.Success(normalized))
normalized normalized
} else { } else {
Log.w("NormalizedRelayUrl", "Rejected $url") Log.w("NormalizedRelayUrl") { "Rejected $url" }
normalizedUrls.put(url, NormalizationResult.Error) normalizedUrls.put(url, NormalizationResult.Error)
null null
} }
} catch (e: Exception) { } catch (e: Exception) {
if (e is CancellationException) throw e if (e is CancellationException) throw e
normalizedUrls.put(url, NormalizationResult.Error) normalizedUrls.put(url, NormalizationResult.Error)
Log.w("NormalizedRelayUrl", "Rejected $url") Log.w("NormalizedRelayUrl") { "Rejected $url" }
null null
} }
} }
@@ -73,7 +73,7 @@ class RelaySession(
try { try {
onSend(OptimizedJsonMapper.toJson(message)) onSend(OptimizedJsonMapper.toJson(message))
} catch (e: Exception) { } catch (e: Exception) {
Log.w("ClientSession", "Failed to send to ${e.message}") Log.w("ClientSession") { "Failed to send to ${e.message}" }
} }
} }
@@ -156,7 +156,7 @@ class OpenTimestamps(
): Timestamp { ): Timestamp {
val responses = val responses =
mapNotNullAsync(calendarUrls) { calendarUrl -> mapNotNullAsync(calendarUrls) { calendarUrl ->
Log.i("OpenTimestamps", "Submitting to remote calendar $calendarUrl") Log.i("OpenTimestamps") { "Submitting to remote calendar $calendarUrl" }
calendar.submit(calendarUrl, timestamp.digest) calendar.submit(calendarUrl, timestamp.digest)
} }
@@ -361,7 +361,7 @@ class OpenTimestamps(
val attsFromRemote: MutableSet<TimeAttestation> = upgradedStamp.getAttestations() val attsFromRemote: MutableSet<TimeAttestation> = upgradedStamp.getAttestations()
if (attsFromRemote.isNotEmpty()) { if (attsFromRemote.isNotEmpty()) {
Log.i("OpenTimestamps", "Got 1 attestation(s) from $calendarUrl") Log.i("OpenTimestamps") { "Got 1 attestation(s) from $calendarUrl" }
} }
// Set difference from remote attestations & existing attestations // Set difference from remote attestations & existing attestations
@@ -56,7 +56,7 @@ abstract class OpUnary : Op() {
} }
else -> { else -> {
Log.e("OpenTimestamp", "Unknown operation tag: $tag") Log.e("OpenTimestamp") { "Unknown operation tag: $tag" }
null // TODO: Is this OK? Won't it blow up later? Better to throw? null // TODO: Is this OK? Won't it blow up later? Better to throw?
} }
@@ -62,7 +62,7 @@ class EncryptedInfo(
nonce = Base64.decode(parts[1]), nonce = Base64.decode(parts[1]),
) )
} catch (e: Exception) { } catch (e: Exception) {
Log.w("NIP04", "Unable to Parse encrypted payload: $payload") Log.w("NIP04") { "Unable to Parse encrypted payload: $payload" }
null null
} }
} }
@@ -51,7 +51,7 @@ fun ATag.Companion.parseAtag(
ATag(parts[0].toInt(), parts[1], parts[2], relayHint) ATag(parts[0].toInt(), parts[1], parts[2], relayHint)
} catch (t: Throwable) { } catch (t: Throwable) {
Log.w("ATag", "Error parsing A Tag: $atag: ${t.message}") Log.w("ATag") { "Error parsing A Tag: $atag: ${t.message}" }
null null
} }
@@ -78,7 +78,7 @@ object Nip19Parser {
return type!! + key return type!! + key
} catch (e: Throwable) { } catch (e: Throwable) {
Log.e("NIP19 Parser", "Issue trying to Decode NIP19 $uri: ${e.message}") Log.e("NIP19 Parser") { "Issue trying to Decode NIP19 $uri: ${e.message}" }
} }
return null return null
@@ -98,7 +98,7 @@ object Nip19Parser {
return parseComponents(type, key, additionalChars?.ifEmpty { null }) return parseComponents(type, key, additionalChars?.ifEmpty { null })
} catch (e: Throwable) { } catch (e: Throwable) {
Log.e("NIP19 Parser", "Issue trying to Decode NIP19 $uri: ${e.message}") Log.e("NIP19 Parser") { "Issue trying to Decode NIP19 $uri: ${e.message}" }
} }
return null return null
@@ -127,7 +127,7 @@ object Nip19Parser {
ParseReturn(it, nip19, additionalChars) ParseReturn(it, nip19, additionalChars)
} }
} catch (e: Throwable) { } catch (e: Throwable) {
Log.w("NIP19 Parser", "Issue trying to Decode NIP19 $key: ${e.message}") Log.w("NIP19 Parser") { "Issue trying to Decode NIP19 $key: ${e.message}" }
null null
} }
@@ -55,7 +55,7 @@ data class NAddress(
return parse(key.bechToBytes()) return parse(key.bechToBytes())
} }
} catch (e: Throwable) { } catch (e: Throwable) {
Log.w("NAddress", "Issue trying to Decode NIP19 $this: ${e.message}") Log.w("NAddress") { "Issue trying to Decode NIP19 $this: ${e.message}" }
} }
return null return null
@@ -68,7 +68,7 @@ class ChannelCreateEvent(
} }
} catch (e: Exception) { } catch (e: Exception) {
if (e is CancellationException) throw e if (e is CancellationException) throw e
Log.w("ChannelCreateEvent", "Failure to parse ${this.toJson()}") Log.w("ChannelCreateEvent") { "Failure to parse ${this.toJson()}" }
ChannelDataNorm() ChannelDataNorm()
} }
@@ -74,7 +74,7 @@ class ChannelMetadataEvent(
} }
} catch (e: Exception) { } catch (e: Exception) {
if (e is CancellationException) throw e if (e is CancellationException) throw e
Log.w("ChannelCreateEvent", "Failure to parse ${this.toJson()}") Log.w("ChannelCreateEvent") { "Failure to parse ${this.toJson()}" }
ChannelDataNorm() ChannelDataNorm()
} }
@@ -60,7 +60,7 @@ class DraftWrapEvent(
fromJson(json) fromJson(json)
} catch (e: Exception) { } catch (e: Exception) {
if (e is CancellationException) throw e if (e is CancellationException) throw e
Log.w("DraftEvent", "Unable to parse inner event of a draft: $json") Log.w("DraftEvent") { "Unable to parse inner event of a draft: $json" }
throw e throw e
} }
} }
@@ -43,7 +43,7 @@ class PrivateTagsInContent {
decode(json) decode(json)
} catch (e: Exception) { } catch (e: Exception) {
if (e is CancellationException) throw e if (e is CancellationException) throw e
Log.w("DraftEvent", "Unable to parse inner event of a draft: $json") Log.w("DraftEvent") { "Unable to parse inner event of a draft: $json" }
throw e throw e
} }
} }
@@ -90,7 +90,7 @@ enum class ReportType(
"スパム \uD83D\uDCE3" -> SPAM "スパム \uD83D\uDCE3" -> SPAM
"Pourriel \uD83D\uDCE3" -> SPAM "Pourriel \uD83D\uDCE3" -> SPAM
"violence" -> VIOLENCE "violence" -> VIOLENCE
else -> Log.w("ReportedEventTag", "Report type not supported: `$code` ${tag.joinToString(", ")}").let { OTHER } else -> Log.w("ReportedEventTag") { "Report type not supported: `$code` ${tag.joinToString(", ")}" }.let { OTHER }
} }
} }
} }
@@ -61,7 +61,7 @@ class NIP90ContentDiscoveryResponseEvent(
} }
} }
} catch (e: Throwable) { } catch (e: Throwable) {
Log.w("NIP90ContentDiscoveryResponseEvent", "Error parsing the JSON ${e.message}") Log.w("NIP90ContentDiscoveryResponseEvent") { "Error parsing the JSON ${e.message}" }
} }
return events ?: listOf() return events ?: listOf()
@@ -62,7 +62,7 @@ class LargeDBTests {
try { try {
db.insert(event) db.insert(event)
} catch (e: SQLiteException) { } catch (e: SQLiteException) {
Log.w("LargeDBTests", "Error inserting event: ${e.message} for event: ${event.toJson()}") Log.w("LargeDBTests") { "Error inserting event: ${e.message} for event: ${event.toJson()}" }
} }
} }
} }
@@ -73,7 +73,7 @@ class LargeDBTests {
try { try {
db.insert(event) db.insert(event)
} catch (e: SQLiteException) { } catch (e: SQLiteException) {
Log.w("LargeDBTests", "Error inserting event: ${e.message} for event: ${event.toJson()}") Log.w("LargeDBTests") { "Error inserting event: ${e.message} for event: ${event.toJson()}" }
} }
} }
} }
@@ -24,56 +24,44 @@ import java.time.LocalTime
import java.time.format.DateTimeFormatter import java.time.format.DateTimeFormatter
actual object PlatformLog { actual object PlatformLog {
// Define a formatter for the desired output format (e.g., HH:mm:ss) private val formatter = DateTimeFormatter.ofPattern("HH:mm:ss.SSS")
val formatter: DateTimeFormatter? = DateTimeFormatter.ofPattern("HH:mm:ss.SSS")
fun time() = LocalTime.now().format(formatter) private fun time() = LocalTime.now().format(formatter)
private fun log(
level: String,
tag: String,
message: String,
throwable: Throwable?,
) {
if (throwable != null) {
println("${time()} $level: [$tag] $message. Throwable: ${throwable.message}")
} else {
println("${time()} $level: [$tag] $message")
}
}
actual fun w( actual fun w(
tag: String, tag: String,
message: String, message: String,
throwable: Throwable?, throwable: Throwable?,
) { ) = log("WARN ", tag, message, throwable)
if (throwable != null) {
println("${time()} WARN : [$tag] $message. Throwable: ${throwable.message}")
} else {
println("${time()} WARN : [$tag] $message")
}
}
actual fun e( actual fun e(
tag: String, tag: String,
message: String, message: String,
throwable: Throwable?, throwable: Throwable?,
) { ) = log("ERROR", tag, message, throwable)
if (throwable != null) {
println("${time()} ERROR: [$tag] $message. Throwable: ${throwable.message}")
} else {
println("${time()} ERROR: [$tag] $message")
}
}
actual fun d( actual fun d(
tag: String, tag: String,
message: String, message: String,
throwable: Throwable?, throwable: Throwable?,
) { ) = log("DEBUG", tag, message, throwable)
if (throwable != null) {
println("${time()} DEBUG: [$tag] $message. Throwable: ${throwable.message}")
} else {
println("${time()} DEBUG: [$tag] $message")
}
}
actual fun i( actual fun i(
tag: String, tag: String,
message: String, message: String,
throwable: Throwable?, throwable: Throwable?,
) { ) = log("INFO ", tag, message, throwable)
if (throwable != null) {
println("${time()} INFO : [$tag] $message. Throwable: ${throwable.message}")
} else {
println("${time()} INFO : [$tag] $message")
}
}
} }