Skip to content

Stackdriver logging samples (JUL, Logback, Client library) #826

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 6 commits into from
Aug 25, 2017
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 13 additions & 8 deletions logging/cloud-client/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,27 +3,32 @@
[Stackdriver Logging][logging] allows you to store, search, analyze, monitor,
and alert on log data and events from Google Cloud Platform and Amazon Web
Services.
These sample Java applications demonstrate how to access the Cloud Storage API using
These sample Java applications demonstrate how to access the Stackdriver Logging API using
the [Google Cloud Client Library for Java][google-cloud-java].

[logging]: https://cloud.google.com/logging/
[google-cloud-java]: https://github.com/GoogleCloudPlatform/google-cloud-java

## Quickstart
## Setup

Install [Maven](http://maven.apache.org/).

Build your project with:

mvn clean package -DskipTests

You can then run a given `ClassName` via:

mvn exec:java -Dexec.mainClass=com.example.logging.ClassName \
-DpropertyName=propertyValue \
-Dexec.args="any arguments to the app"

[Setup authentication](https://cloud.google.com/docs/authentication) using a service account.

### Writing a log entry (using the quickstart sample)

mvn exec:java -Dexec.mainClass=com.example.logging.QuickstartSample \
-Dexec.args="my-log"


### List log entries

mvn exec:java -Dexec.mainClass=com.example.logging.ListLogs \
-Dexec.args="my-log"


Logs can also viewed using the [Logs Viewer Console](https://pantheon.corp.google.com/logs/viewer).
10 changes: 5 additions & 5 deletions logging/cloud-client/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -16,15 +16,15 @@
<project>
<modelVersion>4.0.0</modelVersion>
<groupId>com.example.logging</groupId>
<artifactId>logging-google-cloud-samples</artifactId>
<artifactId>logging-google-cloud-samples-api</artifactId>
<packaging>jar</packaging>

<!-- Parent defines config for testing & linting. -->
<parent>
<artifactId>doc-samples</artifactId>
<groupId>com.google.cloud</groupId>
<groupId>com.google.cloud.logging.samples</groupId>
<artifactId>cloud-logging-samples</artifactId>
<version>1.0.0</version>
<relativePath>../..</relativePath>
<relativePath>..</relativePath>
</parent>

<properties>
Expand All @@ -37,7 +37,7 @@
<dependency>
<groupId>com.google.cloud</groupId>
<artifactId>google-cloud-logging</artifactId>
<version>1.3.1</version>
<version>1.4.0</version>
</dependency>

<!-- Test dependencies -->
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,19 +17,26 @@
package com.example.logging;

// [START logging_quickstart]
// Imports the Google Cloud client library

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.util.Collections;

/**
* This sample demonstrates writing logs using the Stackdriver Logging API.
* The library also offers a java.util.logging Handler `com.google.cloud.logging.LoggingHandler`
* Logback integration is also available :
* https://github.com/GoogleCloudPlatform/google-cloud-java/tree/master/google-cloud-contrib/google-cloud-logging-logback
* Using the java.util.logging handler / Logback appender should be preferred to programmatically using the API.
*/
public class QuickstartSample {

/** Expects a new or existing Stackdriver log name as the first argument.*/
public static void main(String... args) throws Exception {

// Instantiates a client
Logging logging = LoggingOptions.getDefaultInstance().getService();

Expand All @@ -40,11 +47,12 @@ public static void main(String... args) throws Exception {
String text = "Hello, world!";

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

// Writes the log entry
// Writes the log entry asynchronously
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Out of curiosity, do we do anything to improve the odds that logs get written even if the app crashes? Can we? Big try / catch in main?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we do offer a logging.flush() but would n't help with the try / catch in main.
I get your point though, so will look into it separately as an issue on google-cloud-java.

logging.write(Collections.singleton(entry));

System.out.printf("Logged: %s%n", text);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,37 +18,37 @@

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

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 java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.util.Collections;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

import java.io.ByteArrayOutputStream;
import java.io.PrintStream;

/**
* Tests for quickstart sample.
*/
@RunWith(JUnit4.class)
@SuppressWarnings("checkstyle:abbreviationaswordinname")
public class QuickstartSampleIT {
public class LoggingIT {

private ByteArrayOutputStream bout;
private PrintStream out;
private Logging logging = LoggingOptions.getDefaultInstance().getService();

private static final void deleteMyLog() {
Logging logging = LoggingOptions.getDefaultInstance().getService();

logging.deleteLog("my-log");
private void deleteLog(String logName) {
logging.deleteLog(logName);
}

@Before
public void setUp() {
deleteMyLog();

bout = new ByteArrayOutputStream();
out = new PrintStream(bout);
System.setOut(out);
Expand All @@ -57,13 +57,36 @@ public void setUp() {
@After
public void tearDown() {
System.setOut(null);
deleteMyLog();
}

@Test
public void testQuickstart() throws Exception {
QuickstartSample.main("my-log");
String logName = "my-log";
deleteLog(logName);
QuickstartSample.main(logName);
String got = bout.toString();
assertThat(got).contains("Logged: Hello, world!");
deleteLog(logName);
}

@Test(timeout = 10000)
public void testWriteAndListLogs() throws Exception {
String logName = "test-log";
deleteLog(logName);
// write a log entry
LogEntry entry = LogEntry.newBuilder(StringPayload.of("Hello world again"))
.setLogName(logName)
.setResource(MonitoredResource.newBuilder("global").build())
.build();
logging.write(Collections.singleton(entry));
// flush out log immediately
logging.flush();
bout.reset();
while (bout.toString().isEmpty()) {
ListLogs.main(logName);
Thread.sleep(1000);
}
assertThat(bout.toString().contains("Hello world again")).isTrue();
deleteLog(logName);
}
}
37 changes: 37 additions & 0 deletions logging/jul/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
# Getting Started with Stackdriver Logging using `java.util.logging`

[Stackdriver Logging][logging] allows you to store, search, analyze, monitor,
and alert on log data and events from Google Cloud Platform and Amazon Web
Services.
These sample Java applications demonstrate how to write logs to Stackdriver using
the default Java Logging API (`java.util.logging`) handler for
[Google Cloud Client Library for Java][google-cloud-java].

[logging]: https://cloud.google.com/logging/
[google-cloud-java]: https://github.com/GoogleCloudPlatform/google-cloud-java

## Setup

Install [Maven](http://maven.apache.org/).

Build your project with:

mvn clean package -DskipTests

[Setup authentication](https://cloud.google.com/docs/authentication) using a service account.

## Configuration

Update [logging.properties](src/main/resources/logging.properties) to configure the handler.

## Enhancers

[ExampleEnhancer.java](src/main/java/com/example/logging/jul/enhancers/ExampleEnhancer.java)
provides an example of enhancing log entries with additional labels.


## Writing log entries
mvn exec:java -Dexec.mainClass=com.example.logging.jul.Quickstart \
-Dexec.args="-Djava.util.logging.file=src/main/resources/logging.properties"

Logs can be viewed using the [Logs Viewer Console](https://pantheon.corp.google.com/logs/viewer).
57 changes: 57 additions & 0 deletions logging/jul/pom.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
<!--
Copyright 2016 Google Inc.

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

http://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.
-->
<project>
<modelVersion>4.0.0</modelVersion>
<groupId>com.example.logging</groupId>
<artifactId>logging-google-cloud-samples-jul</artifactId>
<packaging>jar</packaging>

<!-- Parent defines config for testing & linting. -->
<parent>
<groupId>com.google.cloud.logging.samples</groupId>
<artifactId>cloud-logging-samples</artifactId>
<version>1.0.0</version>
<relativePath>..</relativePath>
</parent>

<properties>
<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>

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

<!-- Test dependencies -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.google.truth</groupId>
<artifactId>truth</artifactId>
<version>0.34</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>
31 changes: 31 additions & 0 deletions logging/jul/src/main/java/com/example/logging/jul/Quickstart.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
/*
Copyright 2017, Google, Inc.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Don't think the "," is nesc.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done. Fixed missing licenses too.


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

http://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.jul;

// [START jul_quickstart]

import java.util.logging.Logger;

public class Quickstart {
private static final Logger logger = Logger.getLogger(Quickstart.class.getName());

public static void main(String[] args) {
logger.info("Logging INFO with java.util.logging");
logger.severe("Logging ERROR with java.util.logging");
}
}
// [END jul_quickstart]
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@

/*
* Copyright 2017 Google Inc.
*
* 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
*
* http://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.jul.enhancers;

import com.google.cloud.logging.LogEntry;
import com.google.cloud.logging.LoggingEnhancer;

// Add / update additional fields to the log entry
public class ExampleEnhancer implements LoggingEnhancer {

@Override
public void enhanceLogEntry(LogEntry.Builder logEntry) {
// add additional labels
logEntry.addLabel("test-label-1", "test-value-1");
}
}
29 changes: 29 additions & 0 deletions logging/jul/src/main/resources/logging.properties
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
# A default java.util.logging configuration.
#
# [START jul_config]
# To use this configuration, add to system properties : -Djava.util.logging.config.file="/path/to/file"
#
.level = INFO

# it is recommended that io.grpc and sun.net logging level is kept at INFO level,
# as both these packages are used by Stackdriver internals and can result in verbose / initialization problems.
io.grpc.netty.level=INFO
sun.net.level=INFO

com.example.logging.jul.Quickstart.handlers=com.google.cloud.logging.LoggingHandler
# default : java.log
com.google.cloud.logging.LoggingHandler.log=custom_log

# default : INFO
com.google.cloud.logging.LoggingHandler.level=FINE

# default : ERROR
com.google.cloud.logging.LoggingHandler.flushLevel=ERROR

# custom formatter
com.google.cloud.logging.LoggingHandler.formatter=java.util.logging.SimpleFormatter
java.util.logging.SimpleFormatter.format=%3$s: %5$s%6$s

#optional enhancers (to add additional fields, labels)
com.google.cloud.logging.LoggingHandler.enhancers=com.example.logging.jul.enhancers.ExampleEnhancer
# [END jul_config]
Loading