@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)); }
@Override public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object handler, Exception e) throws Exception { // Note: the thread-local is currently not fully cleared, but just set to null // See: https://github.com/GoogleCloudPlatform/google-cloud-java/issues/2746 TraceLoggingEnhancer.setCurrentTraceId(null); } }
@Override public boolean preHandle(HttpServletRequest req, HttpServletResponse resp, Object handler) throws Exception { String traceId = this.traceIdExtractor.extractTraceIdFromRequest(req); if (traceId != null) { TraceLoggingEnhancer.setCurrentTraceId(traceId); } return true; }