1919import com .google .cloud .MetadataConfig ;
2020import com .google .cloud .MonitoredResource ;
2121import com .google .cloud .ServiceOptions ;
22+ import com .google .cloud .logging .LogEntry .Builder ;
2223import com .google .common .base .Strings ;
2324import com .google .common .collect .ImmutableMap ;
25+
2426import java .util .ArrayList ;
2527import java .util .Collections ;
2628import java .util .List ;
@@ -79,16 +81,14 @@ String getKey() {
7981 new ImmutableMap .Builder <String , Label []>()
8082 .put (
8183 Resource .GaeAppFlex .getKey (),
82- new Label [] {
83- Label .InstanceName ,
84- Label .ModuleId ,
85- Label .VersionId ,
86- Label .InstanceId ,
87- Label .Zone
84+ new Label []{
85+ Label .ModuleId ,
86+ Label .VersionId ,
87+ Label .Zone
8888 })
8989 .put (
9090 Resource .GaeAppStandard .getKey (),
91- new Label [] {Label .AppId , Label . ModuleId , Label .VersionId })
91+ new Label [] {Label .ModuleId , Label .VersionId })
9292 .put (Resource .Container .getKey (), new Label [] {Label .ClusterName , Label .Zone })
9393 .put (Resource .GceInstance .getKey (), new Label [] {Label .InstanceId , Label .Zone })
9494 .build ();
@@ -193,12 +193,15 @@ private static String getAppEngineInstanceName() {
193193 }
194194
195195 private static List <LoggingEnhancer > getEnhancers (Resource resourceType ) {
196- List <LoggingEnhancer > enhancers ;
196+ List <LoggingEnhancer > enhancers = new ArrayList <>() ;
197197 switch (resourceType ) {
198198 // Trace logging enhancer is supported on GAE Flex and Standard.
199- case GaeAppStandard :
200199 case GaeAppFlex :
201200 enhancers = new ArrayList <>();
201+ enhancers .add (new LabelLoggingEnhancer (Collections .singletonList (Label .InstanceName )));
202+ enhancers .add (new TraceLoggingEnhancer ());
203+ break ;
204+ case GaeAppStandard :
202205 enhancers .add (new TraceLoggingEnhancer ());
203206 break ;
204207 default :
@@ -207,4 +210,28 @@ private static List<LoggingEnhancer> getEnhancers(Resource resourceType) {
207210 }
208211 return enhancers ;
209212 }
213+
214+ /**
215+ * Adds additional resource-based labels to log entries.
216+ * Labels that can be provided with {@link MonitoredResource.Builder#addLabel(String, String)}
217+ * are restricted to a supported set per resource.
218+ * @see <a href="https://cloud.google.com/logging/docs/api/v2/resource-list">Logging Labels</a>
219+ */
220+ static class LabelLoggingEnhancer implements LoggingEnhancer {
221+ List <Label > labels ;
222+
223+ LabelLoggingEnhancer (List <Label > labels ) {
224+ this .labels = labels ;
225+ }
226+
227+ @ Override
228+ public void enhanceLogEntry (Builder logEntry ) {
229+ for (Label label : labels ) {
230+ String labelValue = MonitoredResourceUtil .getValue (label );
231+ if (labelValue != null ) {
232+ logEntry .addLabel (label .getKey (), labelValue );
233+ }
234+ }
235+ }
236+ }
210237}
0 commit comments