com.google.cloud.MonitoredResource Java Examples

The following examples show how to use com.google.cloud.MonitoredResource. 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: 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 #2
Source File: LoggingIT.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
@Test(timeout = 60000)
public void testWriteAndListLogs() throws Exception {
  // write a log entry
  LogEntry entry = LogEntry.newBuilder(StringPayload.of("Hello world again"))
      .setLogName(TEST_WRITE_LOG)
      .setResource(MonitoredResource.newBuilder("global").build())
      .build();
  logging.write(Collections.singleton(entry));
  // flush out log immediately
  logging.flush();
  bout.reset();
  // Check if the log is listed yet
  while (bout.toString().isEmpty()) {
    ListLogs.main(TEST_WRITE_LOG);
    Thread.sleep(5000);
  }
  assertThat(bout.toString().contains("Hello world again")).isTrue();
}
 
Example #3
Source File: CustomLoggingServlet.java    From tomcat-runtime with Apache License 2.0 6 votes vote down vote up
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
    throws ServletException, IOException {

  JsonNode body = objectMapper.readTree(req.getReader());
  String logName = body.path("log_name").asText();
  String token = body.path("token").asText();
  Severity severity = Severity.valueOf(body.path("level").asText());

  LogEntry logEntry = LogEntry.newBuilder(Payload.StringPayload.of(token))
      .setLogName(logName)
      .setSeverity(severity)
      .setResource(MonitoredResource.newBuilder("global").build())
      .build();

  logging.write(Collections.singletonList(logEntry));

  resp.setContentType("text/plain");
  resp.getWriter().println(URLEncoder.encode(logName, "UTF-8"));
}
 
Example #4
Source File: LoggingSnippets.java    From google-cloud-java with Apache License 2.0 6 votes vote down vote up
/**
 * Example of writing log entries and providing a default log name and monitored resource. Logging
 * writes are asynchronous by default. {@link Logging#setWriteSynchronicity(Synchronicity)} can be
 * used to update the synchronicity.
 */
// [TARGET write(Iterable, WriteOption...)]
// [VARIABLE "my_log_name"]
public void write(String logName) {
  // [START logging_write_log_entry]
  List<LogEntry> entries = new ArrayList<>();
  entries.add(LogEntry.of(StringPayload.of("Entry payload")));
  Map<String, Object> jsonMap = new HashMap<>();
  jsonMap.put("key", "value");
  entries.add(LogEntry.of(JsonPayload.of(jsonMap)));
  logging.write(
      entries,
      WriteOption.logName(logName),
      WriteOption.resource(MonitoredResource.newBuilder("global").build()));
  // [END logging_write_log_entry]
}
 
Example #5
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 #6
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 #7
Source File: StackdriverMonitor.java    From data-transfer-project with Apache License 2.0 4 votes vote down vote up
private void log(Severity severity, Supplier<String> supplier, Object... data) {
  MonitoredResource.Builder resourceBuilder =
      MonitoredResource.newBuilder("generic_task")
          .addLabel("project_id", projectId)
          // This is slightly backwards as in GCP a job can have many tasks
          // but to line up with the DTP terminology around a job we'll use
          // GCP's job to line up with DTP's job.
          .addLabel("task_id", getHostName());

  if (null != jobId) {
    resourceBuilder.addLabel("job", jobId);
  }

  StringBuilder logMessage = new StringBuilder();
  logMessage.append(supplier.get());

  if (data != null) {
    for (Object datum : data) {
      if (datum instanceof Throwable) {
        logMessage.append(format("\n%s", Throwables.getStackTraceAsString(((Throwable) datum))));
      } else if (datum instanceof UUID) {
        logMessage.append(format("\nJobId: %s", ((UUID) datum)));
      } else if (datum instanceof EventCode) {
        logMessage.append(format("\nEventCode: %s", (EventCode) datum));
      } else if (datum != null) {
        logMessage.append(format("\n%s", datum));
      }
    }
  }

  LogEntry entry =
      LogEntry.newBuilder(Payload.StringPayload.of(logMessage.toString()))
          .setSeverity(severity)
          .setLogName(LOG_NAME)
          .setResource(resourceBuilder.build())
          .build();

  try {
    // Writes the log entry asynchronously
    logging.write(Collections.singleton(entry));
  } catch (Throwable t) {
    System.out.println("Problem logging: " + t.getMessage());
    t.printStackTrace(System.out);
  }
}