Refine search
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); } } } }
private void compareLogEntry(LogEntry expected, LogEntry value) { assertEquals(expected, value); assertEquals(expected.getLogName(), value.getLogName()); assertEquals(expected.getResource(), value.getResource()); assertEquals(expected.getTimestamp(), value.getTimestamp()); assertEquals(expected.getReceiveTimestamp(), value.getReceiveTimestamp()); assertEquals(expected.getSeverity(), value.getSeverity()); assertEquals(expected.getInsertId(), value.getInsertId()); assertEquals(expected.getHttpRequest(), value.getHttpRequest()); assertEquals(expected.getLabels(), value.getLabels()); assertEquals(expected.getOperation(), value.getOperation()); assertEquals(expected.getTrace(), value.getTrace()); assertEquals(expected.getSpanId(), value.getSpanId()); assertEquals(expected.getTraceSampled(), value.getTraceSampled()); assertEquals(expected.getSourceLocation(), value.getSourceLocation()); assertEquals(expected.getPayload(), value.getPayload()); assertEquals(expected.hashCode(), value.hashCode()); } }
@Test public void testToAndFromPb() { compareLogEntry(STRING_ENTRY, LogEntry.fromPb(STRING_ENTRY.toPb("project"))); compareLogEntry(JSON_ENTRY, LogEntry.fromPb(JSON_ENTRY.toPb("project"))); compareLogEntry(PROTO_ENTRY, LogEntry.fromPb(PROTO_ENTRY.toPb("project"))); LogEntry logEntry = LogEntry.of(STRING_PAYLOAD); compareLogEntry(logEntry, LogEntry.fromPb(logEntry.toPb("project"))); logEntry = LogEntry.of(LOG_NAME, RESOURCE, STRING_PAYLOAD); compareLogEntry(logEntry, LogEntry.fromPb(logEntry.toPb("project"))); }
String filter = createEqualityFilter("logName", logName); Iterator<LogEntry> iterator = logging().listLogEntries(EntryListOption.filter(filter)).iterateAll().iterator(); while (!iterator.hasNext()) { Thread.sleep(500L); iterator = logging().listLogEntries(EntryListOption.filter(filter)).iterateAll().iterator(); assertThat(entry.getPayload() instanceof StringPayload).isTrue(); assertThat(entry.<StringPayload>getPayload().getData()).contains("Message"); assertThat(entry.getLogName()).isEqualTo(logId); assertThat(entry.getLabels()) .containsExactly("levelName", "INFO", "levelValue", String.valueOf(Level.INFO.intValue())); MonitoredResource monitoredResource = new LoggingConfig(handler.getClass().getName()) .getMonitoredResource(options.getProjectId()); assertThat(entry.getResource().getType()).isEqualTo(monitoredResource.getType()); assertThat(entry.getResource().getLabels()).containsEntry("project_id", options.getProjectId()); assertThat(entry.getHttpRequest()).isNull(); assertThat(entry.getSeverity()).isEqualTo(Severity.INFO); assertThat(entry.getOperation()).isNull(); assertThat(entry.getInsertId()).isNotNull(); assertThat(entry.getTimestamp()).isNotNull(); assertThat(iterator.hasNext()).isFalse(); logger.removeHandler(handler);
@Test public void testSyncWrite() { expect(options.getProjectId()).andReturn(PROJECT).anyTimes(); expect(options.getService()).andReturn(logging); LogEntry entry = LogEntry.newBuilder(Payload.StringPayload.of(MESSAGE)) .setSeverity(Severity.DEBUG) .addLabel("levelName", "FINEST") .addLabel("levelValue", String.valueOf(Level.FINEST.intValue())) .setTimestamp(123456789L) .build(); logging.setFlushSeverity(Severity.ERROR); expectLastCall().once(); logging.setWriteSynchronicity(Synchronicity.ASYNC); expectLastCall().once(); logging.setWriteSynchronicity(Synchronicity.SYNC); expectLastCall().once(); logging.write(ImmutableList.of(entry), DEFAULT_OPTIONS); expectLastCall().once(); replay(options, logging); LoggingHandler handler = new LoggingHandler(LOG_NAME, options, DEFAULT_RESOURCE); handler.setLevel(Level.ALL); handler.setSynchronicity(Synchronicity.SYNC); handler.setFormatter(new TestFormatter()); LogRecord record = new LogRecord(Level.FINEST, MESSAGE); record.setMillis(123456789L); handler.publish(record); }
@Test public void testFlushLevelConfigUpdatesLoggingFlushSeverity() { LogEntry logEntry = LogEntry.newBuilder(StringPayload.of("this is a test")) .setTimestamp(100000L) .setSeverity(Severity.WARNING) .setLabels( new ImmutableMap.Builder<String, String>() .put("levelName", "WARN") .put("levelValue", String.valueOf(30000L)) .build()) .build(); logging.setFlushSeverity(Severity.WARNING); Capture<Iterable<LogEntry>> capturedArgument = Capture.newInstance(); logging.write(capture(capturedArgument), (WriteOption) anyObject(), (WriteOption) anyObject()); replay(logging); Timestamp timestamp = Timestamp.ofTimeSecondsAndNanos(100000, 0); LoggingEvent loggingEvent = createLoggingEvent(Level.WARN, timestamp.getSeconds()); // error is the default, updating to warn for test loggingAppender.setFlushLevel(Level.WARN); loggingAppender.start(); loggingAppender.doAppend(loggingEvent); verify(logging); assertThat(capturedArgument.getValue().iterator().hasNext()).isTrue(); assertThat(capturedArgument.getValue().iterator().next()).isEqualTo(logEntry); }
/** 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); } }
/** Creates a {@code LogEntry} object given the entry payload. */ public static LogEntry of(Payload<?> payload) { return newBuilder(payload).build(); }
@Test public void enhanceLogEntry_AddBlankSpanToLogEntry() { LogEntry logEntry = getEnhancedLogEntry( new OpenCensusTraceLoggingEnhancer("my-test-project-7"), BlankSpan.INSTANCE); assertFalse(logEntry.getTraceSampled()); assertThat(logEntry.getTrace()) .isEqualTo("projects/my-test-project-7/traces/00000000000000000000000000000000"); assertThat(logEntry.getSpanId()).isEqualTo("0000000000000000"); }
static LogEntry fromPb(com.google.logging.v2.LogEntry entryPb) { Builder builder = newBuilder(Payload.fromPb(entryPb)); builder.setLabels(entryPb.getLabelsMap()); builder.setSeverity(Severity.fromPb(entryPb.getSeverity())); if (!entryPb.getLogName().equals("")) { builder.setLogName(ProjectLogName.parse(entryPb.getLogName()).getLog()); Long millis = millisFromTimestamp(entryPb.getTimestamp()); if (millis != 0) { builder.setTimestamp(millis); Long millis = millisFromTimestamp(entryPb.getReceiveTimestamp()); if (millis != 0) { builder.setReceiveTimestamp(millis);
/** * 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] }
builder.setTimestamp(timestampFromMillis(timestamp)); builder.setReceiveTimestamp(timestampFromMillis(receiveTimestamp)); builder.setTrace(getTrace()); builder.setSpanId(getSpanId());
nameValuePairs.add(new BasicNameValuePair("tracename",sessionName +"-"+ entry.getStrategy().toString())); nameValuePairs.add(new BasicNameValuePair("latitude", Double.toString(entry.getLocation().getLatitude()))); nameValuePairs.add(new BasicNameValuePair("longitude", Double.toString(entry.getLocation().getLongitude()))); nameValuePairs.add(new BasicNameValuePair("timestamp", Long.toString(entry.getTimestamp())));
@Test public void enhanceLogEntry_ConvertNullProjectIdToEmptyString() { LogEntry logEntry = getEnhancedLogEntry( new OpenCensusTraceLoggingEnhancer(null), new TestSpan( SpanContext.create( TraceId.fromLowerBase16("bfb4248a24325a905873a1d43001d9a0"), SpanId.fromLowerBase16("6f23f9afd448e272"), TraceOptions.builder().setIsSampled(true).build(), EMPTY_TRACESTATE))); assertThat(logEntry.getTrace()).isEqualTo("projects//traces/bfb4248a24325a905873a1d43001d9a0"); }
@Override public LogEntry apply(com.google.logging.v2.LogEntry pb) { return fromPb(pb); } };
public void write(Iterable<LogEntry> logEntries, WriteOption... options) { if (inWriteCall.get() != null) { return; } inWriteCall.set(true); try { writeLogEntries(logEntries, options); if (flushSeverity != null) { for (LogEntry logEntry : logEntries) { // flush pending writes if log severity at or above flush severity if (logEntry.getSeverity().compareTo(flushSeverity) >= 0) { flush(); break; } } } } finally { inWriteCall.remove(); } }
ImmutableMap.of( "project_id", options.getProjectId(), "instance_id", "instance", String filter = createEqualityFilter("logName", logName); Iterator<LogEntry> iterator = logging().listLogEntries(EntryListOption.filter(filter)).iterateAll().iterator(); while (!iterator.hasNext()) { Thread.sleep(500L); iterator = logging().listLogEntries(EntryListOption.filter(filter)).iterateAll().iterator(); assertTrue(entry.getPayload() instanceof StringPayload); assertTrue(entry.<StringPayload>getPayload().getData().contains("Message")); assertEquals(logId, entry.getLogName()); assertEquals( ImmutableMap.of( "levelName", "WARNING", "levelValue", String.valueOf(Level.WARNING.intValue())), entry.getLabels()); assertEquals(resource, entry.getResource()); assertNull(entry.getHttpRequest()); assertEquals(Severity.WARNING, entry.getSeverity()); assertNull(entry.getOperation()); assertNotNull(entry.getInsertId()); assertNotNull(entry.getTimestamp()); assertFalse(iterator.hasNext()); logger.removeHandler(handler);
@Test public void testEnhancersAddCorrectLabelsToLogEntries() { LogEntry logEntry = LogEntry.newBuilder(StringPayload.of("this is a test")) .setTimestamp(100000L) .setSeverity(Severity.WARNING) .setLabels( new ImmutableMap.Builder<String, String>() .put("levelName", "WARN") .put("levelValue", String.valueOf(30000L)) .put("test-label-1", "test-value-1") .put("test-label-2", "test-value-2") .build()) .build(); logging.setFlushSeverity(Severity.ERROR); Capture<Iterable<LogEntry>> capturedArgument = Capture.newInstance(); logging.write(capture(capturedArgument), (WriteOption) anyObject(), (WriteOption) anyObject()); expectLastCall().once(); replay(logging); loggingAppender.addEnhancer("com.example.enhancers.TestLoggingEnhancer"); loggingAppender.addEnhancer("com.example.enhancers.AnotherTestLoggingEnhancer"); loggingAppender.start(); Timestamp timestamp = Timestamp.ofTimeSecondsAndNanos(100000, 0); LoggingEvent loggingEvent = createLoggingEvent(Level.WARN, timestamp.getSeconds()); loggingAppender.doAppend(loggingEvent); verify(logging); assertThat(capturedArgument.getValue().iterator().hasNext()).isTrue(); assertThat(capturedArgument.getValue().iterator().next()).isEqualTo(logEntry); }
/** * Creates a {@code LogEntry} object given the log name, the monitored resource and the entry * payload. */ public static LogEntry of(String logName, MonitoredResource resource, Payload<?> payload) { return newBuilder(payload).setLogName(logName).setResource(resource).build(); }