ホームページ  >  記事  >  Java  >  Java 関数を使用するための監視およびロギング戦略は何ですか?

Java 関数を使用するための監視およびロギング戦略は何ですか?

王林
王林オリジナル
2024-04-24 18:06:01778ブラウズ

Java 関数のモニタリングとロギングの戦略: モニタリング: Cloud Monitoring API の使用: パフォーマンスと指標の可視性を提供します。カスタム メトリック データ ポイントと時系列を送信します。ロギング: Stackdriver を使用します。 ロギング: デバッグとトラブルシューティングのためにイベントを記録します。 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<Object> {
    
      private static final Logging logging = LoggingOptions.getDefaultInstance().getService();
    
      @Override
      public void accept(Object message, Context context) {
        var payload = (Map<String, Object>) message;
    
        // 创建一个日志条目
        Map<String, String> 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 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。