Skip to content
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
40 changes: 2 additions & 38 deletions Bitkit/Services/LightningService.swift
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@
class LightningService {
private var node: Node?
var currentWalletIndex: Int = 0
private var currentLogFilePath: String?

private let syncStatusChangedSubject = PassthroughSubject<UInt64, Never>()

Expand Down Expand Up @@ -83,12 +82,7 @@
config.includeUntrustedPendingInSpendable = true

let builder = Builder.fromConfig(config: config)

Logger.info("LDK-node log path: \(ldkStoragePath)")

let logFilePath = generateLogFilePath()
currentLogFilePath = logFilePath
builder.setFilesystemLogger(logFilePath: logFilePath, maxLogLevel: Env.ldkLogLevel)
builder.setCustomLogger(logWriter: LdkLogWriter())

let resolvedElectrumServerUrl = electrumServerUrl ?? Env.electrumServerUrl

Expand Down Expand Up @@ -527,7 +521,7 @@
}

func closeChannel(_ channel: ChannelDetails, force: Bool = false, forceCloseReason: String? = nil) async throws {
guard let node else {

Check warning on line 524 in Bitkit/Services/LightningService.swift

View workflow job for this annotation

GitHub Actions / Run Tests

value 'node' was defined but never used; consider replacing with boolean test

Check warning on line 524 in Bitkit/Services/LightningService.swift

View workflow job for this annotation

GitHub Actions / Run Integration Tests

value 'node' was defined but never used; consider replacing with boolean test
throw AppError(serviceError: .nodeNotStarted)
}

Expand Down Expand Up @@ -604,11 +598,7 @@
}

func dumpLdkLogs() {
guard let logFilePath = currentLogFilePath else {
Logger.error("No log file path available")
return
}

let logFilePath = Logger.sessionLogFile
let fileURL = URL(fileURLWithPath: logFilePath)

do {
Expand Down Expand Up @@ -644,32 +634,6 @@
return "Nodes: \(allNodes.count), Last Synced: \(lastRgsSyncString)"
}

// MARK: Logging helpers

private func generateLogFilePath() -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd_HH-mm-ss"
dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
let timestamp = dateFormatter.string(from: Date())

let baseDir = Env.logDirectory
let contextPrefix = Env.currentExecutionContext.filenamePrefix
let logFilePath = "\(baseDir)/ldk_\(contextPrefix)_\(timestamp).log"

// Create directory if it doesn't exist
let directory = URL(fileURLWithPath: baseDir)
if !FileManager.default.fileExists(atPath: directory.path) {
do {
try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
} catch {
Logger.error("Failed to create log directory: \(error)")
}
}

Logger.debug("Generated LDK log file path: \(logFilePath)")
return logFilePath
}

// MARK: - Configuration Helpers

private func configureGossipSource(builder: Builder, rgsServerUrl: String?) {
Expand Down Expand Up @@ -788,7 +752,7 @@
onEvent?(event)

switch event {
case let .paymentSuccessful(paymentId, paymentHash, paymentPreimage, feePaidMsat):

Check warning on line 755 in Bitkit/Services/LightningService.swift

View workflow job for this annotation

GitHub Actions / Run Tests

immutable value 'paymentPreimage' was never used; consider replacing with '_' or removing it

Check warning on line 755 in Bitkit/Services/LightningService.swift

View workflow job for this annotation

GitHub Actions / Run Integration Tests

immutable value 'paymentPreimage' was never used; consider replacing with '_' or removing it
Logger.info("✅ Payment successful: paymentId: \(paymentId ?? "?") paymentHash: \(paymentHash) feePaidMsat: \(feePaidMsat ?? 0)")
Task {
let hash = paymentId ?? paymentHash
Expand All @@ -813,7 +777,7 @@
Logger.warn("No paymentId or paymentHash available for failed payment", context: "LightningService")
}
}
case let .paymentReceived(paymentId, paymentHash, amountMsat, feePaidMsat):

Check warning on line 780 in Bitkit/Services/LightningService.swift

View workflow job for this annotation

GitHub Actions / Run Tests

immutable value 'feePaidMsat' was never used; consider replacing with '_' or removing it

Check warning on line 780 in Bitkit/Services/LightningService.swift

View workflow job for this annotation

GitHub Actions / Run Integration Tests

immutable value 'feePaidMsat' was never used; consider replacing with '_' or removing it
Logger.info("🤑 Payment received: paymentId: \(paymentId ?? "?") paymentHash: \(paymentHash) amountMsat: \(amountMsat)")
Task {
let hash = paymentId ?? paymentHash
Expand All @@ -823,7 +787,7 @@
Logger.error("Failed to handle payment received for \(hash): \(error)", context: "LightningService")
}
}
case let .paymentClaimable(paymentId, paymentHash, claimableAmountMsat, claimDeadline, customRecords):

Check warning on line 790 in Bitkit/Services/LightningService.swift

View workflow job for this annotation

GitHub Actions / Run Tests

immutable value 'customRecords' was never used; consider replacing with '_' or removing it

Check warning on line 790 in Bitkit/Services/LightningService.swift

View workflow job for this annotation

GitHub Actions / Run Tests

immutable value 'claimDeadline' was never used; consider replacing with '_' or removing it

Check warning on line 790 in Bitkit/Services/LightningService.swift

View workflow job for this annotation

GitHub Actions / Run Integration Tests

immutable value 'customRecords' was never used; consider replacing with '_' or removing it

Check warning on line 790 in Bitkit/Services/LightningService.swift

View workflow job for this annotation

GitHub Actions / Run Integration Tests

immutable value 'claimDeadline' was never used; consider replacing with '_' or removing it
Logger.info(
"🫰 Payment claimable: paymentId: \(paymentId) paymentHash: \(paymentHash) claimableAmountMsat: \(claimableAmountMsat)"
)
Expand Down Expand Up @@ -852,7 +816,7 @@

if let channel {
await registerClosedChannel(channel: channel, reason: reasonString)
await MainActor.run {

Check warning on line 819 in Bitkit/Services/LightningService.swift

View workflow job for this annotation

GitHub Actions / Run Tests

result of call to 'run(resultType:body:)' is unused

Check warning on line 819 in Bitkit/Services/LightningService.swift

View workflow job for this annotation

GitHub Actions / Run Integration Tests

result of call to 'run(resultType:body:)' is unused
channelCache.removeValue(forKey: channelIdString)
}
} else {
Expand All @@ -875,7 +839,7 @@
Logger.error("Failed to handle transaction received for \(txid): \(error)", context: "LightningService")
}
}
case let .onchainTransactionConfirmed(txid, blockHash, blockHeight, confirmationTime, details):

Check warning on line 842 in Bitkit/Services/LightningService.swift

View workflow job for this annotation

GitHub Actions / Run Tests

immutable value 'confirmationTime' was never used; consider replacing with '_' or removing it

Check warning on line 842 in Bitkit/Services/LightningService.swift

View workflow job for this annotation

GitHub Actions / Run Tests

immutable value 'blockHash' was never used; consider replacing with '_' or removing it

Check warning on line 842 in Bitkit/Services/LightningService.swift

View workflow job for this annotation

GitHub Actions / Run Integration Tests

immutable value 'confirmationTime' was never used; consider replacing with '_' or removing it

Check warning on line 842 in Bitkit/Services/LightningService.swift

View workflow job for this annotation

GitHub Actions / Run Integration Tests

immutable value 'blockHash' was never used; consider replacing with '_' or removing it
Logger.info("✅ Onchain transaction confirmed: txid=\(txid) blockHeight=\(blockHeight) amountSats=\(details.amountSats)")
Task {
do {
Expand Down Expand Up @@ -929,7 +893,7 @@

// MARK: Balance Events

case let .balanceChanged(oldSpendableOnchain, newSpendableOnchain, oldTotalOnchain, newTotalOnchain, oldLightning, newLightning):

Check warning on line 896 in Bitkit/Services/LightningService.swift

View workflow job for this annotation

GitHub Actions / Run Tests

immutable value 'newTotalOnchain' was never used; consider replacing with '_' or removing it

Check warning on line 896 in Bitkit/Services/LightningService.swift

View workflow job for this annotation

GitHub Actions / Run Tests

immutable value 'oldTotalOnchain' was never used; consider replacing with '_' or removing it

Check warning on line 896 in Bitkit/Services/LightningService.swift

View workflow job for this annotation

GitHub Actions / Run Integration Tests

immutable value 'newTotalOnchain' was never used; consider replacing with '_' or removing it

Check warning on line 896 in Bitkit/Services/LightningService.swift

View workflow job for this annotation

GitHub Actions / Run Integration Tests

immutable value 'oldTotalOnchain' was never used; consider replacing with '_' or removing it
Logger
.info("💰 Balance changed: onchain=\(oldSpendableOnchain)->\(newSpendableOnchain) lightning=\(oldLightning)->\(newLightning)")

Expand Down
45 changes: 44 additions & 1 deletion Bitkit/Utilities/Logger.swift
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
import Foundation
import LDKNode

// MARK: - Logger

class Logger {
private init() {}
Expand Down Expand Up @@ -96,7 +99,7 @@ class Logger {
}
}

// Cleans up both bitkit and ldk log files
// Cleans up log files
static func cleanUpOldLogFiles(maxTotalSizeMB: Int = 20) {
queue.async {
let baseDir = Env.logDirectory
Expand Down Expand Up @@ -148,3 +151,43 @@ class Logger {
}
}
}

// MARK: - LdkLogWriter

final class LdkLogWriter: LogWriter {
private let maxLogLevel: LogLevel

init(maxLogLevel: LogLevel = Env.ldkLogLevel) {
self.maxLogLevel = maxLogLevel
}

func log(record: LogRecord) {
guard logLevelOrder(record.level) >= logLevelOrder(maxLogLevel) else { return }

let context = "[LDK] [\(record.modulePath):\(record.line)]"

switch record.level {
case .gossip, .trace, .debug:
Logger.debug(record.args, context: context)
case .info:
Logger.info(record.args, context: context)
case .warn:
Logger.warn(record.args, context: context)
case .error:
Logger.error(record.args, context: context)
}
}

/// Returns the numeric order of a LogLevel for comparison purposes.
/// Higher values are more severe (error > warn > info > debug > trace > gossip).
private func logLevelOrder(_ level: LogLevel) -> Int {
switch level {
case .gossip: return 1
case .trace: return 2
case .debug: return 3
case .info: return 4
case .warn: return 5
case .error: return 6
}
}
}
Loading