com.google.cloud.logging.Logging Java Examples

The following examples show how to use com.google.cloud.logging.Logging. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ListLogs.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
/** Expects an existing Stackdriver log name as an argument. */
public static void main(String... args) throws Exception {
  // [START logging_list_log_entries]
  // Instantiates a client
  LoggingOptions options = LoggingOptions.getDefaultInstance();

  String logName = args[0];

  try (Logging logging = options.getService()) {

    String logFilter = "logName=projects/" + options.getProjectId() + "/logs/" + logName;

    // List all log entries
    Page<LogEntry> entries = logging.listLogEntries(
        EntryListOption.filter(logFilter));
    do {
      for (LogEntry logEntry : entries.iterateAll()) {
        System.out.println(logEntry);
      }
      entries = entries.getNextPage();
    } while (entries != null);

  }
  // [END logging_list_log_entries]
}
 
Example #2
Source File: QuickstartSample.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
/** Expects a new or existing Stackdriver log name as the first argument.*/
public static void main(String... args) throws Exception {

  // Instantiates a client
  Logging logging = LoggingOptions.getDefaultInstance().getService();

  // The name of the log to write to
  String logName = args[0];  // "my-log";

  // The data to write to the log
  String text = "Hello, world!";

  LogEntry entry = LogEntry.newBuilder(StringPayload.of(text))
      .setSeverity(Severity.ERROR)
      .setLogName(logName)
      .setResource(MonitoredResource.newBuilder("global").build())
      .build();

  // Writes the log entry asynchronously
  logging.write(Collections.singleton(entry));

  System.out.printf("Logged: %s%n", text);
}
 
Example #3
Source File: ExampleSystemTest.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
private static String getLogEntriesAsString(String startTimestamp) {
  // Construct Stackdriver logging filter
  // See this page for more info: https://cloud.google.com/logging/docs/view/advanced-queries
  String filter = "resource.type=\"cloud_function\""
      + " AND severity=INFO"
      + " AND resource.labels.function_name=" + FUNCTION_DEPLOYED_NAME
      + String.format(" AND timestamp>=\"%s\"", startTimestamp);

  // Get Stackdriver logging entries
  Page<LogEntry> logEntries =
      loggingClient.listLogEntries(
          Logging.EntryListOption.filter(filter),
          Logging.EntryListOption.sortOrder(
              Logging.SortingField.TIMESTAMP, Logging.SortingOrder.DESCENDING)
      );

  // Serialize Stackdriver logging entries + collect them into a single string
  String logsConcat = StreamSupport.stream(logEntries.getValues().spliterator(), false)
      .map((x) -> x.toString())
      .collect(Collectors.joining("%n"));

  return logsConcat;
}
 
Example #4
Source File: ExampleSystemTest.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
private static String getLogEntriesAsString(String startTimestamp) {
  // Construct Stackdriver logging filter
  // See this page for more info: https://cloud.google.com/logging/docs/view/advanced-queries
  String filter = "resource.type=\"cloud_function\""
      + " AND severity=INFO"
      + " AND resource.labels.function_name=" + FUNCTION_DEPLOYED_NAME
      + String.format(" AND timestamp>=\"%s\"", startTimestamp);

  // Get Stackdriver logging entries
  Page<LogEntry> logEntries =
      loggingClient.listLogEntries(
          Logging.EntryListOption.filter(filter),
          Logging.EntryListOption.sortOrder(
              Logging.SortingField.TIMESTAMP, Logging.SortingOrder.DESCENDING)
      );

  // Serialize Stackdriver logging entries + collect them into a single string
  String logsConcat = StreamSupport.stream(logEntries.getValues().spliterator(), false)
      .map((x) -> x.toString())
      .collect(Collectors.joining("%n"));

  return logsConcat;
}
 
Example #5
Source File: CreateAndListMetrics.java    From google-cloud-java with Apache License 2.0 6 votes vote down vote up
public static void main(String... args) throws Exception {
  // Create a service object
  // Credentials are inferred from the environment
  try (Logging logging = LoggingOptions.getDefaultInstance().getService()) {

    // Create a metric
    MetricInfo metricInfo =
        MetricInfo.newBuilder("test-metric", "severity >= ERROR")
            .setDescription("Log entries with severity higher or equal to ERROR")
            .build();
    logging.create(metricInfo);

    // List metrics
    Page<Metric> metrics = logging.listMetrics();
    for (Metric metric : metrics.iterateAll()) {
      System.out.println(metric);
    }
  }
}
 
Example #6
Source File: CreateAndListSinks.java    From google-cloud-java with Apache License 2.0 6 votes vote down vote up
public static void main(String... args) throws Exception {
  // Create a service object
  // Credentials are inferred from the environment
  try (Logging logging = LoggingOptions.getDefaultInstance().getService()) {

    // Create a sink to back log entries to a BigQuery dataset
    SinkInfo sinkInfo =
        SinkInfo.newBuilder("test-sink", DatasetDestination.of("test-dataset"))
            .setFilter("severity >= ERROR")
            .build();
    logging.create(sinkInfo);

    // List sinks
    Page<Sink> sinks = logging.listSinks();
    for (Sink sink : sinks.iterateAll()) {
      System.out.println(sink);
    }
  }
}
 
Example #7
Source File: LoggingExample.java    From google-cloud-java with Apache License 2.0 5 votes vote down vote up
@Override
public void run(Logging logging, String filter) {
  Page<LogEntry> entryPage;
  if (filter == null) {
    entryPage = logging.listLogEntries();
  } else {
    entryPage = logging.listLogEntries(EntryListOption.filter(filter));
  }
  for (LogEntry entry : entryPage.iterateAll()) {
    System.out.println(entry);
  }
}
 
Example #8
Source File: WriteAndListLogEntries.java    From google-cloud-java with Apache License 2.0 5 votes vote down vote up
public static void main(String... args) throws Exception {
  // Create a service object
  // Credentials are inferred from the environment
  LoggingOptions options = LoggingOptions.getDefaultInstance();
  try (Logging logging = options.getService()) {

    // Create a log entry
    LogEntry firstEntry =
        LogEntry.newBuilder(StringPayload.of("message"))
            .setLogName("test-log")
            .setResource(
                MonitoredResource.newBuilder("global")
                    .addLabel("project_id", options.getProjectId())
                    .build())
            .build();
    logging.write(Collections.singleton(firstEntry));

    // List log entries
    Page<LogEntry> entries =
        logging.listLogEntries(
            EntryListOption.filter(
                "logName=projects/" + options.getProjectId() + "/logs/test-log"));
    for (LogEntry logEntry : entries.iterateAll()) {
      System.out.println(logEntry);
    }
  }
}
 
Example #9
Source File: LoggingExample.java    From google-cloud-java with Apache License 2.0 5 votes vote down vote up
@Override
public void run(Logging logging, LogEntry entry) {
  MonitoredResource resource =
      MonitoredResource.newBuilder("global")
          .addLabel("project_id", logging.getOptions().getProjectId())
          .build();
  LogEntry entryWithResource = entry.toBuilder().setResource(resource).build();
  logging.write(Collections.singleton(entryWithResource));
  System.out.printf("Written entry %s%n", entryWithResource);
}
 
Example #10
Source File: LoggingExample.java    From google-cloud-java with Apache License 2.0 5 votes vote down vote up
@Override
public void run(Logging logging, Void arg) {
  for (MonitoredResourceDescriptor descriptor :
      logging.listMonitoredResourceDescriptors().iterateAll()) {
    System.out.println(descriptor);
  }
}
 
Example #11
Source File: LoggingExample.java    From google-cloud-java with Apache License 2.0 4 votes vote down vote up
@Override
public void run(Logging logging, Void arg) {
  for (Metric metric : logging.listMetrics().iterateAll()) {
    System.out.println(metric);
  }
}
 
Example #12
Source File: LoggingExample.java    From google-cloud-java with Apache License 2.0 4 votes vote down vote up
@Override
public void run(Logging logging, String logName) {
  logging.deleteLog(logName);
  System.out.printf("Deleted log %s%n", logName);
}
 
Example #13
Source File: LoggingExample.java    From google-cloud-java with Apache License 2.0 4 votes vote down vote up
@Override
public void run(Logging logging, SinkInfo sink) {
  System.out.printf("Created sink %s%n", logging.create(sink));
}
 
Example #14
Source File: LoggingExample.java    From google-cloud-java with Apache License 2.0 4 votes vote down vote up
@Override
public void run(Logging logging, String sink) {
  logging.deleteSink(sink);
  System.out.printf("Deleted sink %s%n", sink);
}
 
Example #15
Source File: LoggingExample.java    From google-cloud-java with Apache License 2.0 4 votes vote down vote up
@Override
public void run(Logging logging, String sink) {
  System.out.printf("Sink info: %s%n", logging.getSink(sink));
}
 
Example #16
Source File: LoggingExample.java    From google-cloud-java with Apache License 2.0 4 votes vote down vote up
@Override
public void run(Logging logging, Void arg) {
  for (Sink sink : logging.listSinks().iterateAll()) {
    System.out.println(sink);
  }
}
 
Example #17
Source File: LoggingExample.java    From google-cloud-java with Apache License 2.0 4 votes vote down vote up
@Override
public void run(Logging logging, MetricInfo metric) {
  System.out.printf("Created metric %s%n", logging.create(metric));
}
 
Example #18
Source File: LoggingExample.java    From google-cloud-java with Apache License 2.0 4 votes vote down vote up
@Override
public void run(Logging logging, String metric) {
  logging.deleteMetric(metric);
  System.out.printf("Deleted metric %s%n", metric);
}
 
Example #19
Source File: LoggingExample.java    From google-cloud-java with Apache License 2.0 4 votes vote down vote up
@Override
public void run(Logging logging, String metric) {
  System.out.printf("Metric info: %s%n", logging.getMetric(metric));
}
 
Example #20
Source File: StackdriverMonitor.java    From data-transfer-project with Apache License 2.0 4 votes vote down vote up
public StackdriverMonitor(Logging logging, String projectId) {
  this.logging = logging;
  this.projectId = projectId;
}
 
Example #21
Source File: LoggingExample.java    From google-cloud-java with Apache License 2.0 4 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
void run(Logging logging, Tuple<LoggingAction, Object> subaction) throws Exception {
  subaction.x().run(logging, subaction.y());
}
 
Example #22
Source File: LoggingSnippets.java    From google-cloud-java with Apache License 2.0 4 votes vote down vote up
public LoggingSnippets(Logging logging) {
  this.logging = logging;
}
 
Example #23
Source File: TraceSampleApplicationTests.java    From spring-cloud-gcp with Apache License 2.0 4 votes vote down vote up
@Test
public void testTracesAreLoggedCorrectly() {
	HttpHeaders headers = new HttpHeaders();

	String uuidString = UUID.randomUUID().toString().replaceAll("-", "");

	headers.add("x-cloud-trace-context", uuidString);
	this.testRestTemplate.exchange(this.url, HttpMethod.GET, new HttpEntity<>(headers), String.class);

	GetTraceRequest getTraceRequest = GetTraceRequest.newBuilder()
			.setProjectId(this.projectIdProvider.getProjectId())
			.setTraceId(uuidString)
			.build();

	String logFilter = String.format(
			"trace=projects/%s/traces/%s", this.projectIdProvider.getProjectId(), uuidString);

	await().atMost(4, TimeUnit.MINUTES)
			.pollInterval(Duration.TWO_SECONDS)
			.ignoreExceptions()
			.untilAsserted(() -> {

		Trace trace = this.traceServiceStub.getTrace(getTraceRequest);
		assertThat(trace.getTraceId()).isEqualTo(uuidString);
		assertThat(trace.getSpansCount()).isEqualTo(8);

		// verify custom tags
		assertThat(trace.getSpans(0).getLabelsMap().get("environment")).isEqualTo("QA");
		assertThat(trace.getSpans(0).getLabelsMap().get("session-id")).isNotNull();

		List<LogEntry> logEntries = new ArrayList<>();
		this.logClient.listLogEntries(Logging.EntryListOption.filter(logFilter)).iterateAll()
				.forEach((le) -> {
					logEntries.add(le);
					assertThat(le.getTrace()).matches(
							"projects/" + this.projectIdProvider.getProjectId() + "/traces/([a-z0-9]){32}");
					assertThat(le.getSpanId()).matches("([a-z0-9]){16}");
				});


		List<String> logContents = logEntries.stream()
				.map((logEntry) -> (String) ((JsonPayload) logEntry.getPayload())
						.getDataAsMap().get("message"))
				.collect(Collectors.toList());

		assertThat(logContents).contains("starting busy work");
		assertThat(logContents).contains("finished busy work");
	});
}
 
Example #24
Source File: LoggingExample.java    From google-cloud-java with Apache License 2.0 votes vote down vote up
abstract void run(Logging logging, T arg) throws Exception;