Skip to content

Commit 73a865d

Browse files
committed
Log limit
1 parent 86d680c commit 73a865d

File tree

3 files changed

+38
-17
lines changed

3 files changed

+38
-17
lines changed

LoopFollow/Controllers/Nightscout/BGData.swift

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -18,13 +18,13 @@ extension MainViewController {
1818
dexShare?.fetchData(count) { (err, result) -> () in
1919

2020
if let error = err {
21-
LogManager.shared.log(category: .dexcom, message: "Error fetching Dexcom data: \(error.localizedDescription)")
21+
LogManager.shared.log(category: .dexcom, message: "Error fetching Dexcom data: \(error.localizedDescription)", limitIdentifier: "Error fetching Dexcom data")
2222
self.webLoadNSBGData()
2323
return
2424
}
2525

2626
guard let data = result else {
27-
LogManager.shared.log(category: .dexcom, message: "Received nil data from Dexcom")
27+
LogManager.shared.log(category: .dexcom, message: "Received nil data from Dexcom", limitIdentifier: "Received nil data from Dexcom")
2828
self.webLoadNSBGData()
2929
return
3030
}
@@ -33,7 +33,7 @@ extension MainViewController {
3333
let latestDate = data[0].date
3434
let now = dateTimeUtils.getNowTimeIntervalUTC()
3535
if (latestDate + 330) < now && IsNightscoutEnabled() {
36-
LogManager.shared.log(category: .dexcom, message: "Dexcom data is old, loading from NS instead")
36+
LogManager.shared.log(category: .dexcom, message: "Dexcom data is old, loading from NS instead", limitIdentifier: "Dexcom data is old, loading from NS instead")
3737
self.webLoadNSBGData()
3838
return
3939
}
@@ -104,7 +104,7 @@ extension MainViewController {
104104
self.ProcessDexBGData(data: nsData2, sourceName: sourceName)
105105
}
106106
case .failure(let error):
107-
LogManager.shared.log(category: .nightscout, message: "Failed to fetch data: \(error)")
107+
LogManager.shared.log(category: .nightscout, message: "Failed to fetch bg data: \(error)", limitIdentifier: "Failed to fetch bg data")
108108
DispatchQueue.main.async {
109109
TaskScheduler.shared.rescheduleTask(
110110
id: .fetchBG,
@@ -123,8 +123,9 @@ extension MainViewController {
123123
// Dexcom BG Data Response processor
124124
func ProcessDexBGData(data: [ShareGlucoseData], sourceName: String){
125125
let graphHours = 24 * UserDefaultsRepository.downloadDays.value
126-
127-
if data.count == 0 {
126+
127+
guard !data.isEmpty else {
128+
LogManager.shared.log(category: .nightscout, message: "No bg data received. Skipping processing.", limitIdentifier: "No bg data received. Skipping processing.")
128129
return
129130
}
130131
let latestDate = data[0].date

LoopFollow/Controllers/Nightscout/DeviceStatus.swift

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -30,12 +30,11 @@ extension MainViewController {
3030
}
3131

3232
private func handleDeviceStatusError() {
33-
LogManager.shared.log(category: .deviceStatus, message: "Device status fetch failed!")
33+
LogManager.shared.log(category: .deviceStatus, message: "Device status fetch failed!", limitIdentifier: "Device status fetch failed!")
3434
DispatchQueue.main.async {
3535
TaskScheduler.shared.rescheduleTask(id: .deviceStatus, to: Date().addingTimeInterval(10))
36+
self.evaluateNotLooping()
3637
}
37-
38-
evaluateNotLooping()
3938
}
4039

4140
func evaluateNotLooping() {

LoopFollow/Log/LogManager.swift

Lines changed: 29 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,9 @@ class LogManager {
1515
private let logDirectory: URL
1616
private let dateFormatter: DateFormatter
1717
private let consoleQueue = DispatchQueue(label: "com.loopfollow.log.console", qos: .background)
18+
19+
private let rateLimitQueue = DispatchQueue(label: "com.loopfollow.log.ratelimit")
20+
private var lastLoggedTimestamps: [String: Date] = [:]
1821

1922
enum Category: String, CaseIterable {
2023
case bluetooth = "Bluetooth"
@@ -30,26 +33,46 @@ class LogManager {
3033
}
3134

3235
init() {
33-
// Create log directory in the app's Documents folder
3436
let documentsDirectory = fileManager.urls(for: .documentDirectory, in: .userDomainMask).first!
3537
logDirectory = documentsDirectory.appendingPathComponent("Logs")
36-
37-
// Ensure the directory exists
3838
if !fileManager.fileExists(atPath: logDirectory.path) {
3939
try? fileManager.createDirectory(at: logDirectory, withIntermediateDirectories: true, attributes: nil)
4040
}
41-
4241
dateFormatter = DateFormatter()
4342
dateFormatter.dateFormat = "yyyy-MM-dd"
4443
}
45-
46-
func log(category: Category, message: String, isDebug: Bool = false) {
44+
45+
/// Logs a message with an optional rate limit.
46+
///
47+
/// - Parameters:
48+
/// - category: The log category.
49+
/// - message: The message to log.
50+
/// - isDebug: Indicates if this is a debug log.
51+
/// - limitIdentifier: Optional key to rate-limit similar log messages.
52+
/// - limitInterval: Time interval (in seconds) to wait before logging the same type again.
53+
func log(category: Category, message: String, isDebug: Bool = false, limitIdentifier: String? = nil, limitInterval: TimeInterval = 300) {
4754
let timestamp = DateFormatter.localizedString(from: Date(), dateStyle: .none, timeStyle: .medium)
4855
let logMessage = "[\(timestamp)] [\(category.rawValue)] \(message)"
4956

5057
consoleQueue.async {
5158
print(logMessage)
5259
}
60+
61+
if let key = limitIdentifier, !Storage.shared.debugLogLevel.value {
62+
let shouldLog: Bool = rateLimitQueue.sync {
63+
if let lastLogged = lastLoggedTimestamps[key] {
64+
let interval = Date().timeIntervalSince(lastLogged)
65+
if interval < limitInterval {
66+
return false
67+
}
68+
}
69+
lastLoggedTimestamps[key] = Date()
70+
return true
71+
}
72+
if !shouldLog {
73+
return
74+
}
75+
}
5376

5477
if !isDebug || Storage.shared.debugLogLevel.value {
5578
let logFileURL = self.currentLogFileURL
@@ -60,7 +83,6 @@ class LogManager {
6083
func cleanupOldLogs() {
6184
let today = dateFormatter.string(from: Date())
6285
let yesterday = dateFormatter.string(from: Calendar.current.date(byAdding: .day, value: -1, to: Date())!)
63-
6486
do {
6587
let logFiles = try fileManager.contentsOfDirectory(at: logDirectory, includingPropertiesForKeys: nil)
6688
for logFile in logFiles {
@@ -93,7 +115,6 @@ class LogManager {
93115
if !fileManager.fileExists(atPath: fileURL.path) {
94116
fileManager.createFile(atPath: fileURL.path, contents: nil, attributes: nil)
95117
}
96-
97118
if let fileHandle = try? FileHandle(forWritingTo: fileURL) {
98119
defer { fileHandle.closeFile() }
99120
fileHandle.seekToEndOfFile()

0 commit comments

Comments
 (0)