首頁 > Java > java教程 > 主體

使用 Java 函數的監控和日誌記錄策略有哪些?

王林
發布: 2024-04-24 18:06:01
原創
713 人瀏覽過

監控和日誌記錄 Java 函數的策略:監控:使用 Cloud Monitoring API:提供對效能和指標的可見性。發送自訂指標資料點和時間序列。日誌記錄:使用 Stackdriver Logging:記錄事件,進行偵錯和故障排除。使用 Cloud Logging API:傳送和接收日誌條目。透過 Stackdriver Logging:直接記錄,提供方便的日誌語句和設定。

使用 Java 函数的监控和日志记录策略有哪些?

使用Java 函數的監控與日誌記錄策略

簡介

監控和日誌記錄對於維護穩定可靠的Java 函數至關重要。本文討論了在 Java 函數中實作這些策略的不同方法。

監控

  • 使用 Cloud Monitoring API:此 API 提供了對函數效能和其他指標的深入可見性。
import com.google.cloud.functions.HttpFunction;
import com.google.cloud.functions.HttpRequest;
import com.google.cloud.functions.HttpResponse;
import com.google.cloud.monitoring.v3.MetricServiceClient;
import com.google.monitoring.v3.CustomMetric;
import com.google.monitoring.v3.ProjectName;
import com.google.monitoring.v3.TimeInterval;
import com.google.monitoring.v3.TimeSeries;
import com.google.protobuf.Struct;
import com.google.protobuf.Value;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

public class Monitor implements HttpFunction {

  private static final String projectId = System.getenv("GOOGLE_CLOUD_PROJECT");
  private static final MetricServiceClient metricClient = MetricServiceClient.create();
  private static final ProjectName projectName = ProjectName.of(projectId);

  @Override
  public void service(HttpRequest request, HttpResponse response)
      throws IOException {
    var writer = new PrintWriter(response.getWriter());

    // 创建一个自定义指标
    var metric =
        CustomMetric.newBuilder()
            .setType("custom.googleapis.com/my_metric")
            .setMetricKind(CustomMetric.MetricKind.GAUGE)
            .setValueType(CustomMetric.ValueType.DOUBLE)
            .build();

    // 发送指标数据点
    var requestBuilder = TimeSeries.newBuilder()
        .setMetric(metric.getName())
        .setResource(projectName.toString())
        .addMetrics(
            CustomMetric.newBuilder()
                .setDoubleValue(Math.random() * 100)
                .build());

    var timestamp = new Date().getTime() / 1000.0;
    requestBuilder.setInterval(
        TimeInterval.newBuilder()
            .setStartTime(com.google.protobuf.Timestamp.newBuilder().setSeconds(timestamp).build())
            .setEndTime(com.google.protobuf.Timestamp.newBuilder().setSeconds(timestamp).build())
            .build());

    TimeSeries series = requestBuilder.build();

    metricClient.createTimeSeries(projectName, series);
    writer.printf("Metric sent at: %s\n", new Date());
  }
}
登入後複製
  • 使用 Stackdriver Logging:記錄函數執行中的事件,提供對偵錯和故障排除的有價值見解。
import com.google.cloud.functions.HttpFunction;
import com.google.cloud.functions.HttpRequest;
import com.google.cloud.functions.HttpResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.logging.Logger;

public class Log implements HttpFunction {

  private static final Logger logger = Logger.getLogger(Log.class.getName());

  @Override
  public void service(HttpRequest request, HttpResponse response)
      throws IOException {
    var writer = new PrintWriter(response.getWriter());

    // 记录信息级别日志消息
    logger.info("Function executed successfully.");
    writer.printf("Logged at: %s\n", new Date());
  }
}
登入後複製

日誌記錄

  • #使用Cloud Logging API:一個通用的日誌記錄服務,用於從Java 函數傳送和接收日誌條目。
import com.google.api.gax.rpc.ApiException;
import com.google.cloud.functions.BackgroundFunction;
import com.google.cloud.functions.Context;
import com.google.cloud.logging.LogEntry;
import com.google.cloud.logging.Logging;
import com.google.cloud.logging.LoggingOptions;
import java.util.HashMap;
import java.util.Map;

public class CloudLog implements BackgroundFunction {

  private static final Logging logging = LoggingOptions.getDefaultInstance().getService();

  @Override
  public void accept(Object message, Context context) {
    var payload = (Map) message;

    // 创建一个日志条目
    Map labels = new HashMap<>();
    labels.put("function", context.getFunctionName());
    labels.put("region", context.getRegion());
    LogEntry entry =
        LogEntry.newBuilder(payload.toString())
            .setSeverity(LogEntry.Severity.INFO)
            .setLabels(labels)
            .build();

    // 发送日志条目
    try {
      logging.write(LogEntry.of(entry));
    } catch (ApiException e) {
      e.printStackTrace();
    }
  }
}
登入後複製
  • 使用 Stackdriver Logging:直接記錄到 Stackdriver Logging,提供方便的日誌語句和記錄配置。
import com.google.cloud.functions.HttpFunction;
import com.google.cloud.functions.HttpRequest;
import com.google.cloud.functions.HttpResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.logging.Level;
import java.util.logging.Logger;

public class Log implements HttpFunction {

  private static final Logger logger = Logger.getLogger(Log.class.getName());

  @Override
  public void service(HttpRequest request, HttpResponse response)
      throws IOException {
    var writer = new PrintWriter(response.getWriter());

    // 记录警告级别日志消息
    logger.log(Level.WARNING, "Function encountered an issue.");
    writer.printf("Logged at: %s\n", new Date());
  }
}
登入後複製

透過使用這些策略,可以有效地監控和記錄 Java 函數,從而改進穩定性,檢測錯誤並加快故障排除。

以上是使用 Java 函數的監控和日誌記錄策略有哪些?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!