Disable the debug console logs for production

This commit is contained in:
Tola Leng
2025-07-10 22:14:17 +07:00
parent 917d8a6d29
commit 2d2bd790b0
33 changed files with 270 additions and 270 deletions
@@ -22,12 +22,12 @@ export const useRealTimeUpdates = ({
useEffect(() => {
if (!serviceId) return;
console.log(`Setting up real-time updates for service: ${serviceId}`);
// console.log(`Setting up real-time updates for service: ${serviceId}`);
try {
// Subscribe to the service record for real-time updates
const subscription = pb.collection('services').subscribe(serviceId, function(e) {
console.log("Service updated:", e.record);
// console.log("Service updated:", e.record);
// Update our local state with the new data
if (e.record) {
@@ -47,7 +47,7 @@ export const useRealTimeUpdates = ({
// Subscribe to uptime data updates
const uptimeSubscription = pb.collection('uptime_data').subscribe('*', function(e) {
if (e.record && e.record.service_id === serviceId) {
console.log("New uptime data:", e.record);
// console.log("New uptime data:", e.record);
// Add the new uptime data to our list if it's within the selected date range
const timestamp = new Date(e.record.timestamp);
@@ -73,16 +73,16 @@ export const useRealTimeUpdates = ({
// Clean up the subscriptions
return () => {
console.log(`Cleaning up subscriptions for service: ${serviceId}`);
// console.log(`Cleaning up subscriptions for service: ${serviceId}`);
try {
pb.collection('services').unsubscribe(serviceId);
pb.collection('uptime_data').unsubscribe('*');
} catch (error) {
console.error("Error cleaning up subscriptions:", error);
// console.error("Error cleaning up subscriptions:", error);
}
};
} catch (error) {
console.error("Error setting up real-time updates:", error);
// console.error("Error setting up real-time updates:", error);
}
}, [serviceId, startDate, endDate, setService, setUptimeData]);
};
@@ -38,7 +38,7 @@ export const useServiceData = (serviceId: string | undefined, startDate: Date, e
description: `Service status changed to ${newStatus}`,
});
} catch (error) {
console.error("Failed to update service status:", error);
// console.error("Failed to update service status:", error);
setService(prevService => prevService);
toast({
@@ -52,12 +52,12 @@ export const useServiceData = (serviceId: string | undefined, startDate: Date, e
const fetchUptimeData = async (serviceId: string, start: Date, end: Date, selectedRange?: DateRangeOption | string, regionalAgent?: string) => {
try {
if (!service) {
console.log('No service data available for uptime fetch');
// console.log('No service data available for uptime fetch');
return [];
}
const currentAgent = regionalAgent || selectedRegionalAgent;
console.log(`Fetching uptime data: ${start.toISOString()} to ${end.toISOString()} for range: ${selectedRange}, service type: ${service.type}, regional agent: ${currentAgent}`);
// console.log(`Fetching uptime data: ${start.toISOString()} to ${end.toISOString()} for range: ${selectedRange}, service type: ${service.type}, regional agent: ${currentAgent}`);
// Clear existing data immediately when switching agents
setUptimeData([]);
@@ -70,17 +70,17 @@ export const useServiceData = (serviceId: string | undefined, startDate: Date, e
limit = 400;
}
console.log(`Using limit ${limit} for range ${selectedRange}`);
// console.log(`Using limit ${limit} for range ${selectedRange}`);
let history: UptimeData[] = [];
if (currentAgent === "all") {
// Fetch data from all sources (default + all online regional agents)
console.log(`Fetching data from all monitoring sources`);
// console.log(`Fetching data from all monitoring sources`);
// Fetch default monitoring data
const defaultData = await uptimeService.getUptimeHistory(serviceId, limit, start, end, service.type);
console.log(`Retrieved ${defaultData.length} default monitoring records`);
// console.log(`Retrieved ${defaultData.length} default monitoring records`);
// Mark default data with source identifier
const markedDefaultData = defaultData.map(record => ({
@@ -100,7 +100,7 @@ export const useServiceData = (serviceId: string | undefined, startDate: Date, e
const regionalData = await uptimeService.getUptimeHistoryByRegionalAgent(
serviceId, limit, start, end, service.type, agent.region_name, agent.agent_id
);
console.log(`Retrieved ${regionalData.length} records from ${agent.region_name}`);
// console.log(`Retrieved ${regionalData.length} records from ${agent.region_name}`);
// Mark regional data with source identifier
const markedRegionalData = regionalData.map(record => ({
@@ -112,18 +112,18 @@ export const useServiceData = (serviceId: string | undefined, startDate: Date, e
history = [...history, ...markedRegionalData];
} catch (error) {
console.error(`Error fetching data from ${agent.region_name}:`, error);
// console.error(`Error fetching data from ${agent.region_name}:`, error);
}
}
console.log(`Total combined records: ${history.length}`);
// console.log(`Total combined records: ${history.length}`);
} else {
// Fetch regional agent specific data
const [regionName, agentId] = currentAgent.split("|");
console.log(`Fetching regional agent data for region: ${regionName}, agent: ${agentId} from ${service.type} collection`);
// console.log(`Fetching regional agent data for region: ${regionName}, agent: ${agentId} from ${service.type} collection`);
history = await uptimeService.getUptimeHistoryByRegionalAgent(serviceId, limit, start, end, service.type, regionName, agentId);
console.log(`Retrieved ${history.length} regional monitoring records`);
// console.log(`Retrieved ${history.length} regional monitoring records`);
}
// Sort by timestamp (newest first)
@@ -131,11 +131,11 @@ export const useServiceData = (serviceId: string | undefined, startDate: Date, e
new Date(b.timestamp).getTime() - new Date(a.timestamp).getTime()
);
console.log(`Final dataset: ${filteredHistory.length} records for ${currentAgent === "all" ? "all sources" : "regional"} monitoring`);
//console.log(`Final dataset: ${filteredHistory.length} records for ${currentAgent === "all" ? "all sources" : "regional"} monitoring`);
setUptimeData(filteredHistory);
return filteredHistory;
} catch (error) {
console.error("Error fetching uptime data:", error);
// console.error("Error fetching uptime data:", error);
toast({
variant: "destructive",
title: "Error",
@@ -146,7 +146,7 @@ export const useServiceData = (serviceId: string | undefined, startDate: Date, e
};
const handleRegionalAgentChange = (agent: string) => {
console.log(`Regional agent changed from ${selectedRegionalAgent} to: ${agent}`);
// console.log(`Regional agent changed from ${selectedRegionalAgent} to: ${agent}`);
// Clear data immediately when switching
setUptimeData([]);
@@ -154,7 +154,7 @@ export const useServiceData = (serviceId: string | undefined, startDate: Date, e
// Refetch data with new agent selection
if (serviceId && !isLoading && service) {
console.log(`Refetching data for new agent: ${agent}`);
// console.log(`Refetching data for new agent: ${agent}`);
fetchUptimeData(serviceId, startDate, endDate, '24h', agent);
}
};
@@ -196,13 +196,13 @@ export const useServiceData = (serviceId: string | undefined, startDate: Date, e
alerts: serviceData.alerts || "unmuted"
};
console.log(`Loaded service: ${formattedService.name} (${formattedService.type})`);
// console.log(`Loaded service: ${formattedService.name} (${formattedService.type})`);
setService(formattedService);
// Small delay to ensure state is updated before fetching uptime data
await new Promise(resolve => setTimeout(resolve, 100));
} catch (error) {
console.error("Error fetching service:", error);
// console.error("Error fetching service:", error);
toast({
variant: "destructive",
title: "Error",
@@ -220,7 +220,7 @@ export const useServiceData = (serviceId: string | undefined, startDate: Date, e
// Update data when date range changes or when service is loaded
useEffect(() => {
if (serviceId && !isLoading && service) {
console.log(`Date range changed or service loaded, refetching data for ${serviceId}: ${startDate.toISOString()} to ${endDate.toISOString()}`);
// console.log(`Date range changed or service loaded, refetching data for ${serviceId}: ${startDate.toISOString()} to ${endDate.toISOString()}`);
fetchUptimeData(serviceId, startDate, endDate, '24h', selectedRegionalAgent);
}
}, [startDate, endDate, serviceId, isLoading, service, selectedRegionalAgent, regionalAgents]);
@@ -28,7 +28,7 @@ export function ServiceMonitoringButton({ service, onStatusChange }: ServiceMoni
if (isMonitoring) {
// Pause monitoring
console.log(`Pausing monitoring for service ${service.id} (${service.name})`);
// console.log(`Pausing monitoring for service ${service.id} (${service.name})`);
await serviceService.pauseMonitoring(service.id);
setIsMonitoring(false);
@@ -36,7 +36,7 @@ export function ServiceMonitoringButton({ service, onStatusChange }: ServiceMoni
// Send notification for paused status (only here, not in pauseMonitoring.ts)
if (service.alerts !== "muted") {
console.log("Sending pause notification from UI component");
// console.log("Sending pause notification from UI component");
// IMPORTANT: Direct call to the notification service to ensure a message is sent
await notificationService.sendNotification({
service: service,
@@ -51,7 +51,7 @@ export function ServiceMonitoringButton({ service, onStatusChange }: ServiceMoni
});
} else {
// Start/resume monitoring
console.log(`Starting monitoring for service ${service.id} (${service.name})`);
// console.log(`Starting monitoring for service ${service.id} (${service.name})`);
// First ensure we update the status in the database to not be paused anymore
await serviceService.resumeMonitoring(service.id);
@@ -66,7 +66,7 @@ export function ServiceMonitoringButton({ service, onStatusChange }: ServiceMoni
});
}
} catch (error) {
console.error("Error toggling monitoring:", error);
// console.error("Error toggling monitoring:", error);
toast({
variant: "destructive",
title: "Error",
@@ -56,7 +56,7 @@ export const UptimeBar = ({ uptime, status, serviceId, interval, serviceType }:
);
}
console.log('UptimeBar rendering consolidated items:', consolidatedItems.length);
// console.log('UptimeBar rendering consolidated items:', consolidatedItems.length);
return (
<div className="w-52">
@@ -78,9 +78,9 @@ export const UptimeBar = ({ uptime, status, serviceId, interval, serviceType }:
statuses.includes('paused') ? 'paused' : 'unknown';
}
console.log(`Bar ${index} - Timestamp: ${slot.timestamp}, Items: ${slot.items.length}, Primary Status: ${primaryStatus}, Has Valid Data: ${hasValidData}`);
// console.log(`Bar ${index} - Timestamp: ${slot.timestamp}, Items: ${slot.items.length}, Primary Status: ${primaryStatus}, Has Valid Data: ${hasValidData}`);
slot.items.forEach((item, itemIndex) => {
console.log(` Item ${itemIndex}: Source=${item.source}, Status=${item.status}, ResponseTime=${item.responseTime}, IsDefault=${item.isDefault}`);
// console.log(` Item ${itemIndex}: Source=${item.source}, Status=${item.status}, ResponseTime=${item.responseTime}, IsDefault=${item.isDefault}`);
});
return (
@@ -46,23 +46,23 @@ export const useConsolidatedUptimeData = ({ serviceId, serviceType, status, inte
queryKey: ['consolidatedUptimeHistory', serviceId, serviceType],
queryFn: async () => {
if (!serviceId) {
console.log('No serviceId provided, skipping fetch');
// console.log('No serviceId provided, skipping fetch');
return [];
}
console.log(`Fetching consolidated uptime data for service ${serviceId} of type ${serviceType}`);
// console.log(`Fetching consolidated uptime data for service ${serviceId} of type ${serviceType}`);
// Get ALL uptime history data - this should include both default and regional data
const rawData = await uptimeService.getUptimeHistory(serviceId, 100, undefined, undefined, serviceType);
console.log(`Retrieved ${rawData.length} total records for service ${serviceId}`);
console.log('Raw data sample:', rawData.slice(0, 5).map(d => ({
timestamp: d.timestamp,
region_name: d.region_name,
agent_id: d.agent_id,
status: d.status,
service_id: d.service_id,
response_time: d.responseTime
})));
// console.log(`Retrieved ${rawData.length} total records for service ${serviceId}`);
// console.log('Raw data sample:', rawData.slice(0, 5).map(d => ({
// timestamp: d.timestamp,
// region_name: d.region_name,
// agent_id: d.agent_id,
// status: d.status,
// service_id: d.service_id,
// response_time: d.responseTime
// })));
return rawData;
},
@@ -78,7 +78,7 @@ export const useConsolidatedUptimeData = ({ serviceId, serviceType, status, inte
const processConsolidatedData = (data: UptimeData[]): ConsolidatedTimeSlot[] => {
if (!data || data.length === 0) return [];
console.log(`Processing ${data.length} uptime records for consolidation`);
// console.log(`Processing ${data.length} uptime records for consolidation`);
// Create a map to group records by normalized timestamp (minute precision)
const timeSlotMap = new Map<string, Array<UptimeData & { source: string; isDefault: boolean }>>();
@@ -99,17 +99,17 @@ export const useConsolidatedUptimeData = ({ serviceId, serviceType, status, inte
// Regional monitoring data
sourceName = `${regionName} (Agent ${agentId})`;
isDefault = false;
console.log(`Found regional data: ${sourceName} for normalized timestamp ${normalizedTimestamp}`);
// console.log(`Found regional data: ${sourceName} for normalized timestamp ${normalizedTimestamp}`);
} else if (agentId && !regionName) {
// Default monitoring with specific agent
sourceName = `Default (Agent ${agentId})`;
isDefault = true;
console.log(`Found default monitoring: ${sourceName} for normalized timestamp ${normalizedTimestamp}`);
// console.log(`Found default monitoring: ${sourceName} for normalized timestamp ${normalizedTimestamp}`);
} else {
// Default monitoring fallback
sourceName = 'Default System Check (Agent 1)';
isDefault = true;
console.log(`Using fallback default monitoring for normalized timestamp ${normalizedTimestamp}`);
// console.log(`Using fallback default monitoring for normalized timestamp ${normalizedTimestamp}`);
}
// Get or create the array for this normalized timestamp
@@ -130,9 +130,9 @@ export const useConsolidatedUptimeData = ({ serviceId, serviceType, status, inte
isDefault
});
console.log(`Added record to normalized timestamp ${normalizedTimestamp}: Source=${sourceName}, Status=${record.status}, IsDefault=${isDefault}, ResponseTime=${record.responseTime}ms`);
// console.log(`Added record to normalized timestamp ${normalizedTimestamp}: Source=${sourceName}, Status=${record.status}, IsDefault=${isDefault}, ResponseTime=${record.responseTime}ms`);
} else {
console.log(`Skipping duplicate record for source ${sourceName} at timestamp ${normalizedTimestamp}`);
// console.log(`Skipping duplicate record for source ${sourceName} at timestamp ${normalizedTimestamp}`);
}
});
@@ -150,13 +150,13 @@ export const useConsolidatedUptimeData = ({ serviceId, serviceType, status, inte
.sort((a, b) => new Date(b.timestamp).getTime() - new Date(a.timestamp).getTime())
.slice(0, 20); // Take the most recent 20 time slots
console.log(`Created ${consolidatedTimeline.length} consolidated time slots with normalized timestamps`);
consolidatedTimeline.forEach((slot, index) => {
console.log(`Slot ${index} - Normalized Timestamp: ${slot.timestamp}, Items: ${slot.items.length}`);
slot.items.forEach((item, itemIndex) => {
console.log(` Item ${itemIndex}: Source=${item.source}, Status=${item.status}, ResponseTime=${item.responseTime}ms, IsDefault=${item.isDefault}`);
});
});
// console.log(`Created ${consolidatedTimeline.length} consolidated time slots with normalized timestamps`);
// consolidatedTimeline.forEach((slot, index) => {
// console.log(`Slot ${index} - Normalized Timestamp: ${slot.timestamp}, Items: ${slot.items.length}`);
// slot.items.forEach((item, itemIndex) => {
// console.log(` Item ${itemIndex}: Source=${item.source}, Status=${item.status}, ResponseTime=${item.responseTime}ms, IsDefault=${item.isDefault}`);
// });
// });
return consolidatedTimeline;
};
@@ -164,12 +164,12 @@ export const useConsolidatedUptimeData = ({ serviceId, serviceType, status, inte
// Update consolidated items when data changes
useEffect(() => {
if (uptimeData && uptimeData.length > 0) {
console.log(`Processing consolidated uptime data for service ${serviceId}`);
// console.log(`Processing consolidated uptime data for service ${serviceId}`);
const processedData = processConsolidatedData(uptimeData);
// If service is currently paused, override ONLY the latest (first) bar with paused status
if (status === "paused" && processedData.length > 0) {
console.log(`Service ${serviceId} is paused, overriding latest bar with paused status`);
// console.log(`Service ${serviceId} is paused, overriding latest bar with paused status`);
// Create a paused entry for the latest timestamp
const latestTimestamp = new Date();
@@ -191,11 +191,11 @@ export const useConsolidatedUptimeData = ({ serviceId, serviceType, status, inte
// Replace the first item with paused status, keep the rest as historical data
const updatedData = [pausedSlot, ...processedData.slice(0, 19)];
console.log(`Updated data with paused latest bar, total bars: ${updatedData.length}`);
// console.log(`Updated data with paused latest bar, total bars: ${updatedData.length}`);
setConsolidatedItems(updatedData);
} else {
// Service is active (up/down/warning) - merge real data with any existing paused bars
console.log(`Service ${serviceId} is active with status: ${status}, merging with existing paused bars`);
// console.log(`Service ${serviceId} is active with status: ${status}, merging with existing paused bars`);
// Get existing paused bars from current state
const existingPausedBars = consolidatedItems.filter(slot =>
@@ -213,7 +213,7 @@ export const useConsolidatedUptimeData = ({ serviceId, serviceType, status, inte
const hasConflict = processedData.some(slot => slot.timestamp === pausedSlot.timestamp);
if (!hasConflict) {
mergedData.push(pausedSlot);
console.log(`Preserved paused bar at timestamp: ${pausedSlot.timestamp}`);
// console.log(`Preserved paused bar at timestamp: ${pausedSlot.timestamp}`);
}
});
@@ -222,12 +222,12 @@ export const useConsolidatedUptimeData = ({ serviceId, serviceType, status, inte
.sort((a, b) => new Date(b.timestamp).getTime() - new Date(a.timestamp).getTime())
.slice(0, 20);
console.log(`Final merged data has ${finalData.length} slots`);
// console.log(`Final merged data has ${finalData.length} slots`);
setConsolidatedItems(finalData);
}
} else if (!serviceId || (uptimeData && uptimeData.length === 0)) {
// Generate placeholder data when no real data is available
console.log(`No uptime data available for service ${serviceId}, generating placeholder with status: ${status}`);
// console.log(`No uptime data available for service ${serviceId}, generating placeholder with status: ${status}`);
// Use the actual service status for placeholder data
const statusValue = status === "paused" ? "paused" :
@@ -252,7 +252,7 @@ export const useConsolidatedUptimeData = ({ serviceId, serviceType, status, inte
};
});
console.log(`Generated ${placeholderHistory.length} placeholder slots with status: ${statusValue}`);
// console.log(`Generated ${placeholderHistory.length} placeholder slots with status: ${statusValue}`);
setConsolidatedItems(placeholderHistory);
}
}, [uptimeData, serviceId, status, interval, consolidatedItems]);
@@ -23,7 +23,7 @@ export function useServiceActions(initialServices: Service[]) {
};
const handleViewDetail = (service: Service) => {
console.log(`Navigating to service detail for service ID: ${service.id}`);
// console.log(`Navigating to service detail for service ID: ${service.id}`);
navigate(`/service/${service.id}`);
};
@@ -115,7 +115,7 @@ export function useServiceActions(initialServices: Service[]) {
setSelectedService(null);
} catch (error) {
console.error("Error deleting service:", error);
// console.error("Error deleting service:", error);
toast({
variant: "destructive",
title: "Error",
@@ -134,7 +134,7 @@ export function useServiceActions(initialServices: Service[]) {
// Toggle the mute alerts status for this specific service
const newMuteStatus = !isMuted;
console.log(`${newMuteStatus ? "Muting" : "Unmuting"} alerts for service ${service.id} (${service.name})`);
// console.log(`${newMuteStatus ? "Muting" : "Unmuting"} alerts for service ${service.id} (${service.name})`);
// First update the local state immediately for better UI responsiveness
// Using proper type casting to ensure TypeScript knows we're creating valid Service objects
@@ -165,7 +165,7 @@ export function useServiceActions(initialServices: Service[]) {
await queryClient.invalidateQueries({ queryKey: ["services"] });
} catch (error) {
console.error("Error updating alert settings:", error);
// console.error("Error updating alert settings:", error);
// Revert the local state change if the server update failed
const revertedServices = services.map(s => {
@@ -27,8 +27,8 @@ export function LatestChecksTable({ uptimeData }: { uptimeData: UptimeData[] })
// Filter incidents by status
const incidents = useMemo(() => {
const statusChanges = getStatusChangeEvents(uptimeData);
console.log(`Total status changes: ${statusChanges.length}`);
console.log(`Status types in incidents: ${[...new Set(statusChanges.map(i => i.status))].join(', ')}`);
// console.log(`Total status changes: ${statusChanges.length}`);
// console.log(`Status types in incidents: ${[...new Set(statusChanges.map(i => i.status))].join(', ')}`);
if (statusFilter === "all") return statusChanges;
@@ -58,7 +58,7 @@ export function LatestChecksTable({ uptimeData }: { uptimeData: UptimeData[] })
// Calculate items per page for pagination display
const itemsPerPage = pageSize === "all" ? incidents.length : parseInt(pageSize, 10);
console.log(`Status Filter: ${statusFilter}, Incidents: ${incidents.length}, Includes paused: ${incidents.some(i => i.status === 'paused')}`);
// console.log(`Status Filter: ${statusFilter}, Incidents: ${incidents.length}, Includes paused: ${incidents.some(i => i.status === 'paused')}`);
return (
<Card className={`mb-6 transition-colors ${theme === 'dark' ? 'bg-card border-border' : 'bg-white border-gray-200'}`}>
@@ -68,7 +68,7 @@ export const getStatusChangeEvents = (uptimeData: UptimeData[]): UptimeData[] =>
}
}
console.log(`Found ${statusChanges.length} status changes, including paused status changes: ${statusChanges.some(i => i.status === 'paused')}`);
// console.log(`Found ${statusChanges.length} status changes, including paused status changes: ${statusChanges.some(i => i.status === 'paused')}`);
return statusChanges;
};