Skip to content

Commit

Permalink
docs(sample): Add sample for Native Image support in Logging (#880)
Browse files Browse the repository at this point in the history
* docs(sample): Add sample for Native Image support
  • Loading branch information
mpeddada1 committed Mar 8, 2022
1 parent cebc54e commit 7e59bf3
Show file tree
Hide file tree
Showing 6 changed files with 342 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Expand Up @@ -302,6 +302,7 @@ Samples are in the [`samples/`](https://github.com/googleapis/java-logging/tree/

| Sample | Source Code | Try it |
| --------------------------- | --------------------------------- | ------ |
| Native Image Logging Sample | [source code](https://github.com/googleapis/java-logging/blob/main/samples/native-image-sample/src/main/java/com/example/logging/NativeImageLoggingSample.java) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/java-logging&page=editor&open_in_editor=samples/native-image-sample/src/main/java/com/example/logging/NativeImageLoggingSample.java) |
| Get Sink Metadata | [source code](https://github.com/googleapis/java-logging/blob/main/samples/snippets/src/main/java/com/example/logging/GetSinkMetadata.java) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/java-logging&page=editor&open_in_editor=samples/snippets/src/main/java/com/example/logging/GetSinkMetadata.java) |
| List Log Entries | [source code](https://github.com/googleapis/java-logging/blob/main/samples/snippets/src/main/java/com/example/logging/ListLogEntries.java) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/java-logging&page=editor&open_in_editor=samples/snippets/src/main/java/com/example/logging/ListLogEntries.java) |
| List Logs | [source code](https://github.com/googleapis/java-logging/blob/main/samples/snippets/src/main/java/com/example/logging/ListLogs.java) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/java-logging&page=editor&open_in_editor=samples/snippets/src/main/java/com/example/logging/ListLogs.java) |
Expand Down
71 changes: 71 additions & 0 deletions samples/native-image-sample/README.md
@@ -0,0 +1,71 @@
# Cloud Logging Client Libraries with Native Image

This application uses the Google Cloud [Logging Client Libraries](https://github.com/googleapis/java-logging) and can be compiled with Native Image Native Image.

## Setup Instructions

You will need to follow these prerequisite steps in order to run the samples:

1. If you have not already, [create a Google Cloud Platform Project](https://cloud.google.com/resource-manager/docs/creating-managing-projects#creating_a_project).

2. Install the [Google Cloud SDK](https://cloud.google.com/sdk/) which will allow you to run the sample with your project's credentials.

Once installed, log in with Application Default Credentials using the following command:

```
gcloud auth application-default login
```

**Note:** Authenticating with Application Default Credentials is convenient to use during development, but we recommend [alternate methods of authentication](https://cloud.google.com/docs/authentication/production) during production use.

3. Install the GraalVM compiler.

You can follow the [official installation instructions](https://www.graalvm.org/docs/getting-started/#install-graalvm) from the GraalVM website.
After following the instructions, ensure that you install the native image extension installed by running:

```
gu install native-image
```

Once you finish following the instructions, verify that the default version of Java is set to the GraalVM version by running `java -version` in a terminal.

You will see something similar to the below output:

```
$ java -version
openjdk version "11.0.7" 2020-04-14
OpenJDK Runtime Environment GraalVM CE 20.1.0 (build 11.0.7+10-jvmci-20.1-b02)
OpenJDK 64-Bit Server VM GraalVM CE 20.1.0 (build 11.0.7+10-jvmci-20.1-b02, mixed mode, sharing)
```

4. Enable the [Logging APIs](https://console.cloud.google.com/flows/enableapi?apiid=logging.googleapis.com).

## Sample

Navigate to this directory in a new terminal.

1. Compile the application using the Native Image Compiler. This step may take a few minutes.

```
mvn package -P native -DskipTests
```

2. Run the application:

```
./target/native-image-sample
```

3. The application will log a message to your local terminal and to Google Cloud Console.

Navigate to the [Cloud Console Logs Viewer](https://console.cloud.google.com/logs/viewer) to view you logs and find the newly generated log entry in Cloud Console:
```
This is a log produced by Native Image.
```
### Sample Integration test with Native Image Support
In order to run the sample integration test as a native image, call the following command:

```
mvn test -Pnative
```
170 changes: 170 additions & 0 deletions samples/native-image-sample/pom.xml
@@ -0,0 +1,170 @@
<?xml version='1.0' encoding='UTF-8'?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

<modelVersion>4.0.0</modelVersion>
<groupId>com.example.logging</groupId>
<artifactId>native-image-sample</artifactId>
<name>Native Image Sample</name>
<url>https://github.com/googleapis/java-logging</url>

<!--
The parent pom defines common style checks and testing strategies for our samples.
Removing or replacing it should not affect the execution of the samples in anyway.
-->
<parent>
<groupId>com.google.cloud.samples</groupId>
<artifactId>shared-configuration</artifactId>
<version>1.2.0</version>
</parent>

<properties>
<!-- Java 8 because the Kokoro Sample test uses that Java version -->
<maven.compiler.target>1.8</maven.compiler.target>
<maven.compiler.source>1.8</maven.compiler.source>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>

<dependencyManagement>
<dependencies>
<dependency>
<groupId>com.google.cloud</groupId>
<artifactId>libraries-bom</artifactId>
<version>24.3.0</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>

<dependencies>
<dependency>
<groupId>com.google.cloud</groupId>
<artifactId>google-cloud-logging</artifactId>
</dependency>

<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.google.truth</groupId>
<artifactId>truth</artifactId>
<version>1.1.3</version>
<scope>test</scope>
</dependency>
</dependencies>

<build>
<!-- This plugin enables building the application to a JAR *not* using Native Image -->
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>3.2.2</version>
<configuration>
<archive>
<manifest>
<addClasspath>true</addClasspath>
<classpathPrefix>dependency-jars/</classpathPrefix>
<mainClass>com.example.logging.NativeImageLoggingSample</mainClass>
</manifest>
</archive>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<version>3.2.0</version>
<executions>
<execution>
<id>copy-dependencies</id>
<phase>package</phase>
<goals>
<goal>copy-dependencies</goal>
</goals>
<configuration>
<outputDirectory>
${project.build.directory}/dependency-jars/
</outputDirectory>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>

<!-- Native Profile-->
<profiles>
<profile>
<id>native</id>

<dependencies>
<dependency>
<groupId>com.google.cloud</groupId>
<artifactId>native-image-support</artifactId>
<version>0.12.0</version>
</dependency>
<dependency>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
<version>5.8.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.graalvm.buildtools</groupId>
<artifactId>junit-platform-native</artifactId>
<version>0.9.9</version>
<scope>test</scope>
</dependency>
</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin
</artifactId> <!-- Must use older version of surefire plugin for native-image testing. -->
<version>2.22.2</version>
<configuration>
<includes>
<include>**/IT*</include>
</includes>
</configuration>
</plugin>
<plugin>
<groupId>org.graalvm.buildtools</groupId>
<artifactId>native-maven-plugin</artifactId>
<version>0.9.9</version>
<extensions>true</extensions>
<configuration>
<mainClass>com.example.logging.NativeImageLoggingSample</mainClass>
<buildArgs>
<buildArg>--no-fallback</buildArg>
<buildArg>--no-server</buildArg>
</buildArgs>
</configuration>
<executions>
<execution>
<id>build-native</id>
<goals>
<goal>build</goal>
<goal>test</goal>
</goals>
<phase>package</phase>
</execution>
<execution>
<id>test-native</id>
<goals>
<goal>test</goal>
</goals>
<phase>test</phase>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
</profiles>
</project>
@@ -0,0 +1,64 @@
/*
* Copyright 2022 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.example.logging;

import com.google.cloud.MonitoredResource;
import com.google.cloud.logging.LogEntry;
import com.google.cloud.logging.Logging;
import com.google.cloud.logging.LoggingOptions;
import com.google.cloud.logging.Payload.StringPayload;
import com.google.cloud.logging.Severity;
import java.time.Duration;
import java.time.Instant;
import java.util.Collections;

/** Basic sample application which writes a log message to Cloud Logging. */
public class NativeImageLoggingSample {

/** Runs the Logging Sample Application. */
public static void main(String[] args) throws Exception {
Instant startTime = Instant.now();
// Instantiates a client
Logging client = LoggingOptions.getDefaultInstance().getService();

// The name of the log to write to
String logName = "nativeimage_logging_sample.log";

// The data to write to the log
String text = "This is a log produced by Native Image.";

LogEntry entry =
LogEntry.newBuilder(StringPayload.of(text))
.setSeverity(Severity.INFO)
.setLogName(logName)
.setResource(MonitoredResource.newBuilder("global").build())
.build();

client.write(Collections.singleton(entry));
client.flush();
client.close();

System.out.println(String.format("Logged: %s", text));
System.out.println("Log message written to Cloud Logging.");
System.out.println(
"See your logs in the Cloud Console: https://console.cloud.google.com/logs/viewer "
+ "(Might take a few seconds to load.)");
Instant endTime = Instant.now();
Duration duration = Duration.between(startTime, endTime);
System.out.println("Duration: " + duration.toString());
}
}
@@ -0,0 +1,35 @@
/*
* Copyright 2022 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.example.logging;

import static com.google.common.truth.Truth.assertThat;

import com.google.cloud.testing.junit4.StdOutCaptureRule;
import org.junit.Rule;
import org.junit.Test;

public class ITNativeImageLoggingSample {

@Rule public StdOutCaptureRule stdOut = new StdOutCaptureRule();

@Test
public void testLogging() throws Exception {
NativeImageLoggingSample.main(new String[] {});
assertThat(stdOut.getCapturedOutputAsUtf8String())
.contains("Logged: This is a log produced by Native Image.");
}
}
1 change: 1 addition & 0 deletions samples/pom.xml
Expand Up @@ -31,6 +31,7 @@
<module>snapshot</module>
<module>install-without-bom</module>
<module>snippets</module>
<module>native-image-sample</module>
</modules>

<build>
Expand Down

0 comments on commit 7e59bf3

Please sign in to comment.