How to use Stackdriver Structured Logging in App Engine Flex Java environment

前端 未结 2 1011
你的背包
你的背包 2020-12-20 05:37

Google App Engine flexible environment automatically pipes stdout and stderr to Stackdriver (Google Cloud Logging). But this only supports plain text log message without any

2条回答
  •  暖寄归人
    2020-12-20 06:07

    You could use the Logback appender + Implement LoggingEnhacer

    public class LogEnhancer implements LoggingEnhancer {
    
    
      @Override
      public void enhanceLogEntry(LogEntry.Builder logEntry) {
        // add Labels
        logEntry.addLabel("project", "conversational-services");
    
        // Transform textPayload to JSONPayload
        ObjectMapper mapper = new ObjectMapper();
        Builder structBuilder = Struct.newBuilder();
        String textPayload = logEntry.build().getPayload().getData().toString();
        try {
          // Validate JSON Payload
          mapper.readTree(textPayload);
          JsonFormat.parser().merge(textPayload, structBuilder);
          logEntry.setPayload(JsonPayload.of(structBuilder.build()));
        } catch (InvalidProtocolBufferException e) {
          // Error reporting an error! FML
          System.err.println(e.getMessage());
        } catch (IOException e) {
          // Do nothing (there is not a JSON Payload)
        }
    
      }
    
    }
    

    This class add labels and transform a JSON String in a JSONPayload

    You need to specify the LoggingEnhacer on the logback.xml file

    
    
      
    
        
          INFO
        
        application.log 
        gae_app 
        
         [path_for_your_logging_enhancer_class]
        WARN 
      
    
      
        
      
    
    

提交回复
热议问题