pf5ub3a78 1 month ago
parent 4908f5449c
commit 23671e12d8

@ -0,0 +1,108 @@
package com.soa.monitoring;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.util.concurrent.ConcurrentHashMap;
import java.util.Map;
/**
* -
*/
public class ServiceMonitor {
private static final Logger logger = LogManager.getLogger(ServiceMonitor.class);
private static ServiceMonitor instance;
private final Map<String, ServiceMetrics> metricsMap = new ConcurrentHashMap<>();
private ServiceMonitor() {}
/**
*
*/
public static synchronized ServiceMonitor getInstance() {
if (instance == null) {
instance = new ServiceMonitor();
}
return instance;
}
/**
*
*/
public long startMonitoring(String serviceName) {
return System.currentTimeMillis();
}
/**
*
*/
public void endMonitoring(String serviceName, long startTime, boolean success) {
long executionTime = System.currentTimeMillis() - startTime;
ServiceMetrics metrics = metricsMap.computeIfAbsent(serviceName, k -> new ServiceMetrics());
metrics.recordCall(executionTime, success);
logger.info("Service: {} - Execution time: {}ms, Status: {}",
serviceName, executionTime, success ? "SUCCESS" : "FAILED");
// 检查性能阈值
if (executionTime > 1000) { // 1秒阈值
logger.warn("Service {} performance warning: execution time {}ms exceeds threshold",
serviceName, executionTime);
}
}
/**
*
*/
public ServiceMetrics getServiceMetrics(String serviceName) {
return metricsMap.get(serviceName);
}
/**
*
*/
public void printMonitoringReport() {
logger.info("===== SERVICE MONITORING REPORT =====");
for (Map.Entry<String, ServiceMetrics> entry : metricsMap.entrySet()) {
String serviceName = entry.getKey();
ServiceMetrics metrics = entry.getValue();
logger.info("Service: {}", serviceName);
logger.info(" Total calls: {}", metrics.getTotalCalls());
logger.info(" Successful calls: {}", metrics.getSuccessfulCalls());
logger.info(" Failed calls: {}", metrics.getFailedCalls());
logger.info(" Avg response time: {}ms", metrics.getAvgResponseTime());
logger.info(" Error rate: {}%", metrics.getErrorRate());
}
logger.info("===================================");
}
/**
*
*/
public static class ServiceMetrics {
private long totalCalls = 0;
private long successfulCalls = 0;
private long failedCalls = 0;
private long totalResponseTime = 0;
public synchronized void recordCall(long executionTime, boolean success) {
totalCalls++;
totalResponseTime += executionTime;
if (success) {
successfulCalls++;
} else {
failedCalls++;
}
}
public long getTotalCalls() { return totalCalls; }
public long getSuccessfulCalls() { return successfulCalls; }
public long getFailedCalls() { return failedCalls; }
public double getAvgResponseTime() {
return totalCalls > 0 ? (double) totalResponseTime / totalCalls : 0;
}
public double getErrorRate() {
return totalCalls > 0 ? (double) failedCalls / totalCalls * 100 : 0;
}
}
}
Loading…
Cancel
Save