@Override protected void append(ILoggingEvent e) { LogEntry logEntry = logEntryFor(e); getLogging().write(Collections.singleton(logEntry), defaultWriteOptions); }
@Override public void run() { try { logging.write(ImmutableList.of(LOG_ENTRY1)); logging.flush(); } catch (Exception ex) { exceptions.incrementAndGet(); } } };
/** * 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] }
@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); }
@Test public void testWriteLogEntries() { WriteLogEntriesRequest request = WriteLogEntriesRequest.newBuilder() .addAllEntries( Iterables.transform( ImmutableList.of(LOG_ENTRY1, LOG_ENTRY2), LogEntry.toPbFunction(PROJECT))) .build(); WriteLogEntriesResponse response = WriteLogEntriesResponse.newBuilder().build(); EasyMock.expect(loggingRpcMock.write(request)).andReturn(ApiFutures.immediateFuture(response)); EasyMock.replay(rpcFactoryMock, loggingRpcMock); logging = options.getService(); logging.write(ImmutableList.of(LOG_ENTRY1, LOG_ENTRY2)); }
@Test public void testWriteLogEntriesWithSeverityFlushEnabled() { WriteLogEntriesRequest request = WriteLogEntriesRequest.newBuilder() .addAllEntries( Iterables.transform( ImmutableList.of(LOG_ENTRY1, LOG_ENTRY2), LogEntry.toPbFunction(PROJECT))) .build(); WriteLogEntriesResponse response = WriteLogEntriesResponse.newBuilder().build(); EasyMock.expect(loggingRpcMock.write(request)).andReturn(ApiFutures.immediateFuture(response)); EasyMock.replay(rpcFactoryMock, loggingRpcMock); logging = options.getService(); logging.setFlushSeverity(Severity.DEFAULT); logging.write(ImmutableList.of(LOG_ENTRY1, LOG_ENTRY2)); }
@Test public void testWriteLogEntriesAsync() throws ExecutionException, InterruptedException { WriteLogEntriesRequest request = WriteLogEntriesRequest.newBuilder() .addAllEntries( Iterables.transform( ImmutableList.of(LOG_ENTRY1, LOG_ENTRY2), LogEntry.toPbFunction(PROJECT))) .build(); WriteLogEntriesResponse response = WriteLogEntriesResponse.newBuilder().build(); EasyMock.expect(loggingRpcMock.write(request)).andReturn(ApiFutures.immediateFuture(response)); EasyMock.replay(rpcFactoryMock, loggingRpcMock); logging = options.getService(); logging.write(ImmutableList.of(LOG_ENTRY1, LOG_ENTRY2)); logging.flush(); }
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); } } } }
@Test public void testAddHandler() { expect(options.getProjectId()).andReturn(PROJECT).anyTimes(); expect(options.getService()).andReturn(logging); logging.setFlushSeverity(Severity.ERROR); expectLastCall().once(); logging.setWriteSynchronicity(Synchronicity.ASYNC); expectLastCall().andVoid(); logging.write(ImmutableList.of(FINEST_ENTRY), DEFAULT_OPTIONS); expectLastCall().once(); replay(options, logging); LoggingHandler handler = new LoggingHandler(LOG_NAME, options, DEFAULT_RESOURCE) { @Override public void close() { // Make close NOOP to avoid mock close exception } }; handler.setLevel(Level.ALL); handler.setFormatter(new TestFormatter()); Logger logger = Logger.getLogger(getClass().getName()); logger.setLevel(Level.ALL); LoggingHandler.addHandler(logger, handler); logger.log(newLogRecord(Level.FINEST, MESSAGE)); }
@Test public void testWriteLogEntriesDoesnotEnableFlushByDefault() { WriteLogEntriesRequest request = WriteLogEntriesRequest.newBuilder() .addAllEntries( Iterables.transform( ImmutableList.of( LOG_ENTRY1, LOG_ENTRY2.toBuilder().setSeverity(Severity.EMERGENCY).build()), LogEntry.toPbFunction(PROJECT))) .build(); ApiFuture<WriteLogEntriesResponse> apiFuture = SettableApiFuture.create(); EasyMock.expect(loggingRpcMock.write(request)).andReturn(apiFuture); EasyMock.replay(rpcFactoryMock, loggingRpcMock); logging = options.getService(); logging.write( ImmutableList.of( LOG_ENTRY1, LOG_ENTRY2.toBuilder().setSeverity(Severity.EMERGENCY).build())); }
@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); }
@Test public void testWriteLogEntriesWithOptions() { Map<String, String> labels = ImmutableMap.of("key", "value"); WriteLogEntriesRequest request = WriteLogEntriesRequest.newBuilder() .putAllLabels(labels) .setLogName(LOG_NAME_PB) .setResource(MONITORED_RESOURCE.toPb()) .addAllEntries( Iterables.transform( ImmutableList.of(LOG_ENTRY1, LOG_ENTRY2), LogEntry.toPbFunction(PROJECT))) .build(); WriteLogEntriesResponse response = WriteLogEntriesResponse.newBuilder().build(); EasyMock.expect(loggingRpcMock.write(request)).andReturn(ApiFutures.immediateFuture(response)); EasyMock.replay(rpcFactoryMock, loggingRpcMock); logging = options.getService(); logging.write( ImmutableList.of(LOG_ENTRY1, LOG_ENTRY2), WriteOption.logName(LOG_NAME), WriteOption.resource(MONITORED_RESOURCE), WriteOption.labels(labels)); }
@Test public void testReportWriteError() { expect(options.getProjectId()).andReturn(PROJECT).anyTimes(); expect(options.getService()).andReturn(logging); RuntimeException ex = new RuntimeException(); logging.setFlushSeverity(Severity.ERROR); expectLastCall().once(); logging.setWriteSynchronicity(Synchronicity.ASYNC); expectLastCall().once(); logging.write(ImmutableList.of(FINEST_ENTRY), DEFAULT_OPTIONS); expectLastCall().andStubThrow(ex); replay(options, logging); ErrorManager errorManager = EasyMock.createStrictMock(ErrorManager.class); errorManager.error(null, ex, ErrorManager.WRITE_FAILURE); expectLastCall().once(); replay(errorManager); Handler handler = new LoggingHandler(LOG_NAME, options, DEFAULT_RESOURCE); handler.setLevel(Level.ALL); handler.setErrorManager(errorManager); handler.setFormatter(new TestFormatter()); handler.publish(newLogRecord(Level.FINEST, MESSAGE)); verify(errorManager); }
@Test public void testEnhancedLogEntry() { expect(options.getProjectId()).andReturn(PROJECT).anyTimes(); expect(options.getService()).andReturn(logging); MonitoredResource resource = MonitoredResource.of("custom", ImmutableMap.<String, String>of()); logging.setFlushSeverity(Severity.ERROR); expectLastCall().once(); logging.setWriteSynchronicity(Synchronicity.ASYNC); expectLastCall().once(); logging.write( ImmutableList.of(FINEST_ENHANCED_ENTRY), WriteOption.logName(LOG_NAME), WriteOption.resource(resource), WriteOption.labels(BASE_SEVERITY_MAP)); expectLastCall().once(); replay(options, logging); LoggingEnhancer enhancer = new LoggingEnhancer() { @Override public void enhanceLogEntry(Builder builder) { builder.addLabel("enhanced", "true"); } }; Handler handler = new LoggingHandler(LOG_NAME, options, resource, Collections.singletonList(enhancer)); handler.setLevel(Level.ALL); handler.setFormatter(new TestFormatter()); handler.publish(newLogRecord(Level.FINEST, MESSAGE)); }
@Test public void testWriteLogEntriesAsyncWithOptions() { Map<String, String> labels = ImmutableMap.of("key", "value"); WriteLogEntriesRequest request = WriteLogEntriesRequest.newBuilder() .putAllLabels(labels) .setLogName(LOG_NAME_PB) .setResource(MONITORED_RESOURCE.toPb()) .addAllEntries( Iterables.transform( ImmutableList.of(LOG_ENTRY1, LOG_ENTRY2), LogEntry.toPbFunction(PROJECT))) .build(); WriteLogEntriesResponse response = WriteLogEntriesResponse.newBuilder().build(); EasyMock.expect(loggingRpcMock.write(request)).andReturn(ApiFutures.immediateFuture(response)); EasyMock.replay(rpcFactoryMock, loggingRpcMock); logging = options.getService(); logging.write( ImmutableList.of(LOG_ENTRY1, LOG_ENTRY2), WriteOption.logName(LOG_NAME), WriteOption.resource(MONITORED_RESOURCE), WriteOption.labels(labels)); logging.flush(); }
@Test public void testPublishCustomResource() { expect(options.getProjectId()).andReturn(PROJECT).anyTimes(); expect(options.getService()).andReturn(logging); logging.setFlushSeverity(Severity.ERROR); expectLastCall().once(); logging.setWriteSynchronicity(Synchronicity.ASYNC); expectLastCall().once(); MonitoredResource resource = MonitoredResource.of("custom", ImmutableMap.<String, String>of()); logging.write( ImmutableList.of(FINEST_ENTRY), WriteOption.logName(LOG_NAME), WriteOption.resource(resource), WriteOption.labels(BASE_SEVERITY_MAP)); expectLastCall().once(); replay(options, logging); Handler handler = new LoggingHandler(LOG_NAME, options, resource); handler.setLevel(Level.ALL); handler.setFormatter(new TestFormatter()); handler.publish(newLogRecord(Level.FINEST, MESSAGE)); }
@Test public void testTraceEnhancedLogEntry() { expect(options.getProjectId()).andReturn(PROJECT).anyTimes(); expect(options.getService()).andReturn(logging); MonitoredResource resource = MonitoredResource.of("custom", ImmutableMap.<String, String>of()); logging.setFlushSeverity(Severity.ERROR); expectLastCall().once(); logging.setWriteSynchronicity(Synchronicity.ASYNC); expectLastCall().once(); logging.write( ImmutableList.of(TRACE_ENTRY), WriteOption.logName(LOG_NAME), WriteOption.resource(resource), WriteOption.labels(BASE_SEVERITY_MAP)); expectLastCall().once(); replay(options, logging); LoggingEnhancer enhancer = new TraceLoggingEnhancer(); TraceLoggingEnhancer.setCurrentTraceId("projects/projectId/traces/traceId"); Handler handler = new LoggingHandler(LOG_NAME, options, resource, Collections.singletonList(enhancer)); handler.setLevel(Level.ALL); handler.setFormatter(new TestFormatter()); handler.publish(newLogRecord(Level.FINEST, MESSAGE)); }
@Test public void testClose() throws Exception { expect(options.getProjectId()).andReturn(PROJECT).anyTimes(); expect(options.getService()).andReturn(logging); logging.setFlushSeverity(Severity.ERROR); expectLastCall().once(); logging.setWriteSynchronicity(Synchronicity.ASYNC); expectLastCall().once(); logging.write(ImmutableList.of(FINEST_ENTRY), DEFAULT_OPTIONS); expectLastCall().once(); logging.close(); expectLastCall().once(); replay(options, logging); Handler handler = new LoggingHandler(LOG_NAME, options, DEFAULT_RESOURCE); handler.setLevel(Level.ALL); handler.setFormatter(new TestFormatter()); handler.publish(newLogRecord(Level.FINEST, MESSAGE)); handler.close(); handler.close(); } }
@Test public void testDefaultWriteOptionsHasExpectedDefaults() { logging.setFlushSeverity(Severity.ERROR); Capture<WriteOption> logNameArg = Capture.newInstance(); Capture<WriteOption> resourceArg = Capture.newInstance(); logging.write((Iterable<LogEntry>) anyObject(), capture(logNameArg), capture(resourceArg)); expectLastCall().once(); replay(logging); loggingAppender.start(); Timestamp timestamp = Timestamp.ofTimeSecondsAndNanos(100000, 0); LoggingEvent loggingEvent = createLoggingEvent(Level.ERROR, timestamp.getSeconds()); loggingAppender.doAppend(loggingEvent); assertThat(logNameArg.getValue()).isEqualTo(defaultWriteOptions[0]); // TODO(chingor): Fix this test to work on GCE and locally // assertThat(resourceArg.getValue()).isEqualTo(defaultWriteOptions[1]); }
public void testFlushLevel() { expect(options.getProjectId()).andReturn(PROJECT).anyTimes(); expect(options.getService()).andReturn(logging); logging.setFlushSeverity(Severity.ERROR); expectLastCall().once(); logging.setWriteSynchronicity(Synchronicity.ASYNC); expectLastCall().once(); logging.setFlushSeverity(Severity.WARNING); expectLastCall().once(); logging.write( ImmutableList.of( FINEST_ENTRY, FINER_ENTRY, FINE_ENTRY, CONFIG_ENTRY, INFO_ENTRY, WARNING_ENTRY), DEFAULT_OPTIONS); expectLastCall().once(); replay(options, logging); LoggingHandler handler = new LoggingHandler(LOG_NAME, options, DEFAULT_RESOURCE); handler.setLevel(Level.ALL); handler.setFlushLevel(Level.WARNING); handler.setFormatter(new TestFormatter()); handler.publish(newLogRecord(Level.FINEST, MESSAGE)); handler.publish(newLogRecord(Level.FINER, MESSAGE)); handler.publish(newLogRecord(Level.FINE, MESSAGE)); handler.publish(newLogRecord(Level.CONFIG, MESSAGE)); handler.publish(newLogRecord(Level.INFO, MESSAGE)); handler.publish(newLogRecord(Level.WARNING, MESSAGE)); }