Home > Java > javaTutorial > What are the monitoring and logging strategies for using Java functions?

What are the monitoring and logging strategies for using Java functions?

王林
Release: 2024-04-24 18:06:01
Original
842 people have browsed it

Strategies for monitoring and logging Java functions: Monitoring: Using the Cloud Monitoring API: Provides visibility into performance and metrics. Send custom metric data points and time series. Logging: Use Stackdriver Logging: Log events for debugging and troubleshooting. Use the Cloud Logging API: Send and receive log entries. Through Stackdriver Logging: direct recording, providing convenient log statements and configuration.

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

Monitoring and logging strategies using Java functions

Introduction

Monitoring and logging are critical to maintaining stable and reliable Java functions. This article discusses different ways to implement these strategies in Java functions.

Monitoring

  • Using the Cloud Monitoring API: The API provides deep visibility into function performance and other metrics.
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());
  }
}
Copy after login
  • Use Stackdriver Logging: Log events in function execution, providing valuable insights for debugging and troubleshooting.
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());
  }
}
Copy after login

Logging

  • Using the Cloud Logging API: A general-purpose logging service for logging from Java functions Send and receive log entries.
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();
    }
  }
}
Copy after login
  • Use Stackdriver Logging: Record directly to Stackdriver Logging, providing convenient log statements and recording configuration.
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());
  }
}
Copy after login

By using these strategies, you can effectively monitor and log Java functions to improve stability, detect errors, and speed up troubleshooting.

The above is the detailed content of What are the monitoring and logging strategies for using Java functions?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template