2222import com .google .cloud .logging .Logging ;
2323import com .google .cloud .logging .LoggingOptions ;
2424import com .google .cloud .logging .Payload .JsonPayload ;
25+ import com .google .cloud .logging .Payload .StringPayload ;
2526import com .google .cloud .logging .Severity ;
2627import com .google .common .collect .ImmutableMap ;
28+ import java .util .Arrays ;
2729import java .util .Collections ;
30+ import java .util .List ;
2831import java .util .Map ;
2932
3033public class WriteLogEntry {
@@ -35,23 +38,44 @@ public static void main(String[] args) throws Exception {
3538
3639 // Instantiates a client
3740 try (Logging logging = LoggingOptions .getDefaultInstance ().getService ()) {
38- Map <String , String > payload =
39- ImmutableMap .of (
40- "name" , "King Arthur" , "quest" , "Find the Holy Grail" , "favorite_color" , "Blue" );
41- LogEntry entry =
42- LogEntry .newBuilder (JsonPayload .of (payload ))
43- .setSeverity (Severity .INFO )
44- .setLogName (logName )
45- .setResource (MonitoredResource .newBuilder ("global" ).build ())
46- .build ();
47-
48- // Writes the log entry asynchronously
49- logging .write (Collections .singleton (entry ));
41+ List <LogEntry > entries = createLogEntries (logName );
42+
43+ // Writes one text log entry.
44+ logging .write (Collections .singleton (entries .get (0 )));
45+
46+ // Writes a batch of text and structured log entries.
47+ logging .write (entries );
5048
5149 // Optional - flush any pending log entries just before Logging is closed
5250 logging .flush ();
5351 }
5452 System .out .printf ("Wrote to %s\n " , logName );
5553 }
54+
55+ static List <LogEntry > createLogEntries (String logName ) {
56+ MonitoredResource resource = MonitoredResource .newBuilder ("global" ).build ();
57+ Map <String , String > labels = ImmutableMap .of ("sample" , "write-log-entry" );
58+
59+ LogEntry textEntry =
60+ LogEntry .newBuilder (StringPayload .of ("Text log entry written from Java." ))
61+ .setSeverity (Severity .INFO )
62+ .setLogName (logName )
63+ .setResource (resource )
64+ .setLabels (labels )
65+ .build ();
66+
67+ Map <String , Object > jsonPayload =
68+ ImmutableMap .of (
69+ "message" , "Structured log entry written from Java." , "component" , "sample" );
70+ LogEntry structEntry =
71+ LogEntry .newBuilder (JsonPayload .of (jsonPayload ))
72+ .setSeverity (Severity .WARNING )
73+ .setLogName (logName )
74+ .setResource (resource )
75+ .setLabels (labels )
76+ .build ();
77+
78+ return Arrays .asList (textEntry , structEntry );
79+ }
5680}
5781// [END logging_write_log_entry]
0 commit comments