|
| 1 | +/* |
| 2 | + * Copyright 2016 Google Inc. |
| 3 | + * |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | + * you may not use this file except in compliance with the License. |
| 6 | + * You may obtain a copy of the License at |
| 7 | + * |
| 8 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | + * |
| 10 | + * Unless required by applicable law or agreed to in writing, software |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + * See the License for the specific language governing permissions and |
| 14 | + * limitations under the License. |
| 15 | + */ |
| 16 | + |
| 17 | +package com.example.logging; |
| 18 | + |
| 19 | +// [START logging_quickstart] |
| 20 | +import com.google.cloud.MonitoredResource; |
| 21 | +import com.google.cloud.logging.LogEntry; |
| 22 | +import com.google.cloud.logging.Logging; |
| 23 | +import com.google.cloud.logging.LoggingOptions; |
| 24 | +import com.google.cloud.logging.Payload.StringPayload; |
| 25 | +import com.google.cloud.logging.Severity; |
| 26 | +import java.util.Collections; |
| 27 | + |
| 28 | +/** |
| 29 | + * This sample demonstrates writing logs using the Stackdriver Logging API. The library also offers |
| 30 | + * a java.util.logging Handler `com.google.cloud.logging.LoggingHandler` Logback integration is also |
| 31 | + * available : |
| 32 | + * https://github.com/googleapis/google-cloud-java/tree/master/google-cloud-clients/google-cloud-contrib/google-cloud-logging-logback |
| 33 | + * Using the java.util.logging handler / Logback appender should be preferred to using the API |
| 34 | + * directly. |
| 35 | + */ |
| 36 | +public class QuickstartSample { |
| 37 | + |
| 38 | + /** Expects a new or existing Stackdriver log name as the first argument. */ |
| 39 | + public static void main(String... args) throws Exception { |
| 40 | + |
| 41 | + // Instantiates a client |
| 42 | + Logging logging = LoggingOptions.getDefaultInstance().getService(); |
| 43 | + |
| 44 | + // The name of the log to write to |
| 45 | + String logName = args[0]; // "my-log"; |
| 46 | + |
| 47 | + // The data to write to the log |
| 48 | + String text = "Hello, world!"; |
| 49 | + |
| 50 | + LogEntry entry = |
| 51 | + LogEntry.newBuilder(StringPayload.of(text)) |
| 52 | + .setSeverity(Severity.ERROR) |
| 53 | + .setLogName(logName) |
| 54 | + .setResource(MonitoredResource.newBuilder("global").build()) |
| 55 | + .build(); |
| 56 | + |
| 57 | + // Writes the log entry asynchronously |
| 58 | + logging.write(Collections.singleton(entry)); |
| 59 | + |
| 60 | + System.out.printf("Logged: %s%n", text); |
| 61 | + } |
| 62 | +} |
| 63 | +// [END logging_quickstart] |
0 commit comments