Skip to content

Commit 0975462

Browse files
committed
feat: add duplicate log prevention and improve timezone handling with fallbacks
1 parent 35535d6 commit 0975462

File tree

3 files changed

+40
-8
lines changed

3 files changed

+40
-8
lines changed

frontend/static/js/logs.js

Lines changed: 16 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,9 @@ window.LogsModule = {
2727

2828
// Load user's timezone setting from the backend
2929
loadUserTimezone: function() {
30+
// Set immediate fallback to prevent warnings during loading
31+
this.userTimezone = this.userTimezone || 'UTC';
32+
3033
fetch('/api/settings')
3134
.then(response => response.json())
3235
.then(settings => {
@@ -91,17 +94,23 @@ window.LogsModule = {
9194

9295
// Convert UTC timestamp to user's timezone
9396
convertToUserTimezone: function(utcTimestamp) {
94-
if (!utcTimestamp || !this.userTimezone) {
95-
console.warn('[LogsModule] Missing timestamp or timezone:', {utcTimestamp, userTimezone: this.userTimezone});
96-
return { date: utcTimestamp?.split(' ')[0] || '', time: utcTimestamp?.split(' ')[1] || '' };
97+
if (!utcTimestamp) {
98+
console.debug('[LogsModule] No timestamp provided for conversion');
99+
return { date: '', time: '' };
100+
}
101+
102+
if (!this.userTimezone) {
103+
// Set fallback if timezone not loaded yet
104+
this.userTimezone = 'UTC';
105+
console.debug('[LogsModule] Timezone not loaded yet, using UTC fallback');
97106
}
98107

99108
try {
100-
console.log('[LogsModule] Converting timestamp:', utcTimestamp, 'from UTC to', this.userTimezone);
109+
console.debug('[LogsModule] Converting timestamp:', utcTimestamp, 'from UTC to', this.userTimezone);
101110

102111
// Parse UTC timestamp - ensure it's treated as UTC
103112
const utcDate = new Date(utcTimestamp + ' UTC');
104-
console.log('[LogsModule] Parsed UTC date:', utcDate.toISOString());
113+
console.debug('[LogsModule] Parsed UTC date:', utcDate.toISOString());
105114

106115
// Convert to user's timezone using toLocaleString
107116
const userDateString = utcDate.toLocaleString("en-CA", {
@@ -115,7 +124,7 @@ window.LogsModule = {
115124
hour12: false
116125
});
117126

118-
console.log('[LogsModule] Converted to user timezone:', userDateString);
127+
console.debug('[LogsModule] Converted to user timezone:', userDateString);
119128

120129
// Parse the formatted string "2025-06-05, 14:09:54"
121130
const [datePart, timePart] = userDateString.split(', ');
@@ -125,7 +134,7 @@ window.LogsModule = {
125134
time: timePart
126135
};
127136

128-
console.log('[LogsModule] Final result:', result);
137+
console.debug('[LogsModule] Final result:', result);
129138
return result;
130139

131140
} catch (error) {

src/primary/background.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -454,7 +454,7 @@ def app_specific_loop(app_type: str) -> None:
454454
# Calculate next cycle time in user's timezone without microseconds
455455
next_cycle_time = now_user_tz + datetime.timedelta(seconds=sleep_seconds)
456456

457-
app_logger.info(f"Current time ({user_tz}): {now_user_tz.strftime('%Y-%m-%d %H:%M:%S')}")
457+
app_logger.debug(f"Current time ({user_tz}): {now_user_tz.strftime('%Y-%m-%d %H:%M:%S')}")
458458
app_logger.info(f"Next cycle will begin at {next_cycle_time.strftime('%Y-%m-%d %H:%M:%S')} ({user_tz})")
459459
app_logger.info(f"Sleep duration: {sleep_seconds} seconds")
460460

src/primary/utils/history_utils.py

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,15 @@
11
#!/usr/bin/env python3
22

3+
import time
34
from src.primary.history_manager import add_history_entry
45
from src.primary.utils.logger import get_logger
56

67
logger = get_logger("history")
78

9+
# Cache to prevent duplicate log entries within a short time window
10+
_recent_log_entries = {}
11+
_DUPLICATE_WINDOW_SECONDS = 30
12+
813
def log_processed_media(app_type, media_name, media_id, instance_name, operation_type="missing"):
914
"""
1015
Log when media is processed by an app instance
@@ -20,6 +25,22 @@ def log_processed_media(app_type, media_name, media_id, instance_name, operation
2025
- bool - Success or failure
2126
"""
2227
try:
28+
# Create a unique key for this log entry
29+
entry_key = f"{app_type}|{instance_name}|{media_name}|{operation_type}"
30+
current_time = time.time()
31+
32+
# Check if this exact entry was logged recently
33+
if entry_key in _recent_log_entries:
34+
last_logged = _recent_log_entries[entry_key]
35+
if current_time - last_logged < _DUPLICATE_WINDOW_SECONDS:
36+
logger.debug(f"Skipping duplicate history entry for {app_type} - {instance_name}: {media_name} (last logged {current_time - last_logged:.1f}s ago)")
37+
return True
38+
39+
# Clean up old entries from cache
40+
expired_keys = [k for k, v in _recent_log_entries.items() if current_time - v > _DUPLICATE_WINDOW_SECONDS]
41+
for key in expired_keys:
42+
del _recent_log_entries[key]
43+
2344
logger.debug(f"Logging history entry for {app_type} - {instance_name}: '{media_name}' (ID: {media_id})")
2445

2546
entry_data = {
@@ -31,6 +52,8 @@ def log_processed_media(app_type, media_name, media_id, instance_name, operation
3152

3253
result = add_history_entry(app_type, entry_data)
3354
if result:
55+
# Record this entry in our cache
56+
_recent_log_entries[entry_key] = current_time
3457
logger.info(f"Logged history entry for {app_type} - {instance_name}: {media_name} ({operation_type})")
3558
return True
3659
else:

0 commit comments

Comments
 (0)