Skip to content
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

feat: Add destination property into LogEntry #720

Merged
merged 11 commits into from Oct 24, 2021
4 changes: 2 additions & 2 deletions README.md
Expand Up @@ -58,13 +58,13 @@ implementation 'com.google.cloud:google-cloud-logging'
If you are using Gradle without BOM, add this to your dependencies

```Groovy
implementation 'com.google.cloud:google-cloud-logging:3.2.0'
implementation 'com.google.cloud:google-cloud-logging:3.3.0'
```

If you are using SBT, add this to your dependencies

```Scala
libraryDependencies += "com.google.cloud" % "google-cloud-logging" % "3.2.0"
libraryDependencies += "com.google.cloud" % "google-cloud-logging" % "3.3.0"
```

## Authentication
Expand Down
@@ -0,0 +1,125 @@
/*
* Copyright 2021 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.google.cloud.logging;

import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;

import com.google.logging.v2.LogName;
import java.util.Map;

/**
* Class for specifying resource name of the log to which this log entry belongs (see 'logName'
* parameter in https://cloud.google.com/logging/docs/reference/v2/rest/v2/LogEntry)
*/
public final class LogDestinationName extends Option {

enum DestinationType implements Option.OptionType {
PROJECT,
FOLDER,
ORGANIZATION,
BILLINGACCOUNT;

@SuppressWarnings("unchecked")
<T> T get(Map<Option.OptionType, ?> options) {
return (T) options.get(this);
}
}

private LogDestinationName(Option.OptionType option, Object value) {
super(option, value);
checkArgument(!checkNotNull(value).toString().trim().isEmpty());
}

/**
* Returns an option which sets and validates project ID resource name for log entries.
*
* @param id corresponds to PROJECT_ID token in 'logName' field described in
* https://cloud.google.com/logging/docs/reference/v2/rest/v2/LogEntry
*/
public static LogDestinationName project(String id) {
return new LogDestinationName(DestinationType.PROJECT, id);
}

/**
* Returns an option which sets and validates project ID resource name for log entries.
*
* @param id corresponds to FOLDER_ID token in 'logName' field described in
* https://cloud.google.com/logging/docs/reference/v2/rest/v2/LogEntry
*/
public static LogDestinationName folder(String id) {
return new LogDestinationName(DestinationType.FOLDER, id);
}

/**
* Returns an option which sets and validates project ID resource name for log entries.
*
* @param id corresponds to ORGANIZATION_ID token in 'logName' field described in
* https://cloud.google.com/logging/docs/reference/v2/rest/v2/LogEntry
*/
public static LogDestinationName organization(String id) {
return new LogDestinationName(DestinationType.ORGANIZATION, id);
}

/**
* Returns an option which sets and validates project ID resource name for log entries.
*
* @param id corresponds to BILLING_ACCOUNT_ID token in 'logName' field described in
* https://cloud.google.com/logging/docs/reference/v2/rest/v2/LogEntry
*/
public static LogDestinationName billingAccount(String id) {
return new LogDestinationName(DestinationType.BILLINGACCOUNT, id);
}

/** Creates a {@code LogEntry} object from given log ID and the destination resource. */
public static LogName toLogName(String logId, LogDestinationName destination) {
losalex marked this conversation as resolved.
Show resolved Hide resolved
if (logId == null || destination == null) {
return null;
}

if (DestinationType.PROJECT == destination.getOptionType()) {
return LogName.ofProjectLogName(destination.getValue().toString(), logId);
} else if (DestinationType.FOLDER == destination.getOptionType()) {
return LogName.ofFolderLogName(destination.getValue().toString(), logId);
} else if (DestinationType.ORGANIZATION == destination.getOptionType()) {
return LogName.ofOrganizationLogName(destination.getValue().toString(), logId);
} else if (DestinationType.BILLINGACCOUNT == destination.getOptionType()) {
return LogName.ofBillingAccountLogName(destination.getValue().toString(), logId);
}

return null;
losalex marked this conversation as resolved.
Show resolved Hide resolved
}

/** Creates a {@code LogDestinationName} object given from given {@code LogName}. */
public static LogDestinationName fromLogName(LogName logName) {
if (logName == null) {
return null;
}

if (logName.getProject() != null) {
return project(logName.getProject());
} else if (logName.getBillingAccount() != null) {
return billingAccount(logName.getBillingAccount());
} else if (logName.getFolder() != null) {
return folder(logName.getFolder());
} else if (logName.getOrganization() != null) {
return organization(logName.getOrganization());
}

return null;
}
}
Expand Up @@ -66,6 +66,7 @@ public LogEntry apply(com.google.logging.v2.LogEntry pb) {
private final boolean traceSampled;
private final SourceLocation sourceLocation;
private final Payload<?> payload;
private final LogDestinationName destination;

/** A builder for {@code LogEntry} objects. */
public static class Builder {
Expand All @@ -84,6 +85,7 @@ public static class Builder {
private boolean traceSampled;
private SourceLocation sourceLocation;
private Payload<?> payload;
private LogDestinationName destination;

Builder(Payload<?> payload) {
this.payload = payload;
Expand All @@ -104,6 +106,7 @@ public static class Builder {
this.traceSampled = entry.traceSampled;
this.sourceLocation = entry.sourceLocation;
this.payload = entry.payload;
this.destination = entry.destination;
}

/**
Expand Down Expand Up @@ -282,6 +285,12 @@ public Builder setPayload(Payload<?> payload) {
return this;
}

/** Sets the log path destination name type associated with the log entry. */
public Builder setDestination(LogDestinationName destination) {
this.destination = destination;
return this;
}

/** Creates a {@code LogEntry} object for this builder. */
public LogEntry build() {
return new LogEntry(this);
Expand All @@ -303,6 +312,7 @@ public LogEntry build() {
this.traceSampled = builder.traceSampled;
this.sourceLocation = builder.sourceLocation;
this.payload = builder.payload;
this.destination = builder.destination;
}

/**
Expand Down Expand Up @@ -438,6 +448,16 @@ public <T extends Payload<?>> T getPayload() {
return (T) payload;
}

/**
* Returns the log path destination name type associated with log entry. By default, project name
* based destination is used.
*
* @see <a href="https://cloud.google.com/logging/docs/reference/v2/rest/v2/LogEntry">logName</a>
*/
public LogDestinationName getDestination() {
return destination;
}

@Override
public int hashCode() {
return Objects.hash(
Expand All @@ -454,7 +474,8 @@ public int hashCode() {
getSpanId(),
traceSampled,
sourceLocation,
payload);
payload,
destination);
}

@Override
Expand All @@ -479,7 +500,8 @@ public boolean equals(Object obj) {
&& Objects.equals(getSpanId(), other.getSpanId())
&& Objects.equals(traceSampled, other.traceSampled)
&& Objects.equals(sourceLocation, other.sourceLocation)
&& Objects.equals(payload, other.payload);
&& Objects.equals(payload, other.payload)
&& Objects.equals(destination, other.destination);
}

@Override
Expand All @@ -499,6 +521,7 @@ public String toString() {
.add("traceSampled", traceSampled)
.add("sourceLocation", sourceLocation)
.add("payload", payload)
.add("destination", destination)
.toString();
}

Expand All @@ -510,8 +533,15 @@ public Builder toBuilder() {
com.google.logging.v2.LogEntry toPb(String projectId) {
com.google.logging.v2.LogEntry.Builder builder = payload.toPb();
builder.putAllLabels(labels);

if (logName != null) {
builder.setLogName(LogName.ofProjectLogName(projectId, logName).toString());
LogName name = LogDestinationName.toLogName(logName, destination);

if (name == null) {
builder.setLogName(LogName.ofProjectLogName(projectId, logName).toString());
} else {
builder.setLogName(name.toString());
}
losalex marked this conversation as resolved.
Show resolved Hide resolved
}
if (resource != null) {
builder.setResource(resource.toPb());
Expand Down Expand Up @@ -570,7 +600,19 @@ static LogEntry fromPb(com.google.logging.v2.LogEntry entryPb) {
builder.setLabels(entryPb.getLabelsMap());
builder.setSeverity(Severity.fromPb(entryPb.getSeverity()));
if (!entryPb.getLogName().equals("")) {
builder.setLogName(LogName.parse(entryPb.getLogName()).getLog());
LogName name = LogName.parse(entryPb.getLogName());
builder.setLogName(name.getLog());
LogDestinationName resource = LogDestinationName.fromLogName(name);
/**
* Limitation: we dont know if project ID was provided originally by destination parameter
* explicitly or was taken from credentials (since we do not serialize ResourceName object
* into PB payload). This mean that for project ID we assume it was taken from credentials
* (thus we never create destination object for project ID based path)
*/
if (resource != null
&& !resource.getOptionType().equals(LogDestinationName.DestinationType.PROJECT)) {
builder.setDestination(LogDestinationName.fromLogName(name));
}
losalex marked this conversation as resolved.
Show resolved Hide resolved
}
if (!entryPb.getResource().equals(com.google.api.MonitoredResource.getDefaultInstance())) {
builder.setResource(MonitoredResource.fromPb(entryPb.getResource()));
Expand Down
Expand Up @@ -74,6 +74,11 @@ public String toString() {
JsonPayload.of(ImmutableMap.<String, Object>of("key", "val"));
private static final ProtoPayload PROTO_PAYLOAD =
ProtoPayload.of(Any.pack(Empty.getDefaultInstance()));
private static final LogDestinationName projectName = LogDestinationName.project("project");
losalex marked this conversation as resolved.
Show resolved Hide resolved
private static final LogDestinationName billingName =
LogDestinationName.billingAccount("000000-111111-222222");
private static final LogDestinationName folderName = LogDestinationName.folder("123456789");
private static final LogDestinationName orgName = LogDestinationName.organization("1122334455");
losalex marked this conversation as resolved.
Show resolved Hide resolved
private static final LogEntry STRING_ENTRY =
LogEntry.newBuilder(STRING_PAYLOAD)
.setLogName(LOG_NAME)
Expand Down Expand Up @@ -122,6 +127,57 @@ public String toString() {
.setTraceSampled(TRACE_SAMPLED)
.setSourceLocation(SOURCE_LOCATION)
.build();
private static final LogEntry STRING_ENTRY_BILLING =
losalex marked this conversation as resolved.
Show resolved Hide resolved
LogEntry.newBuilder(STRING_PAYLOAD)
.setLogName(LOG_NAME)
.setDestination(billingName)
.setResource(RESOURCE)
.setTimestamp(TIMESTAMP)
.setReceiveTimestamp(RECEIVE_TIMESTAMP)
.setSeverity(SEVERITY)
.setInsertId(INSERT_ID)
.setHttpRequest(HTTP_REQUEST)
.setLabels(LABELS)
.setOperation(OPERATION)
.setTrace(TRACE_FORMATTER)
.setSpanId(SPAN_ID_FORMATTER)
.setTraceSampled(TRACE_SAMPLED)
.setSourceLocation(SOURCE_LOCATION)
.build();
private static final LogEntry STRING_ENTRY_FOLDER =
LogEntry.newBuilder(STRING_PAYLOAD)
.setLogName(LOG_NAME)
.setDestination(folderName)
.setResource(RESOURCE)
.setTimestamp(TIMESTAMP)
.setReceiveTimestamp(RECEIVE_TIMESTAMP)
.setSeverity(SEVERITY)
.setInsertId(INSERT_ID)
.setHttpRequest(HTTP_REQUEST)
.setLabels(LABELS)
.setOperation(OPERATION)
.setTrace(TRACE_FORMATTER)
.setSpanId(SPAN_ID_FORMATTER)
.setTraceSampled(TRACE_SAMPLED)
.setSourceLocation(SOURCE_LOCATION)
.build();
private static final LogEntry STRING_ENTRY_ORG =
LogEntry.newBuilder(STRING_PAYLOAD)
.setLogName(LOG_NAME)
.setDestination(orgName)
.setResource(RESOURCE)
.setTimestamp(TIMESTAMP)
.setReceiveTimestamp(RECEIVE_TIMESTAMP)
.setSeverity(SEVERITY)
.setInsertId(INSERT_ID)
.setHttpRequest(HTTP_REQUEST)
.setLabels(LABELS)
.setOperation(OPERATION)
.setTrace(TRACE_FORMATTER)
.setSpanId(SPAN_ID_FORMATTER)
.setTraceSampled(TRACE_SAMPLED)
.setSourceLocation(SOURCE_LOCATION)
.build();

@Test
public void testOf() {
Expand Down Expand Up @@ -317,10 +373,35 @@ public void testToAndFromPb() {
compareLogEntry(STRING_ENTRY, LogEntry.fromPb(STRING_ENTRY.toPb("project")));
compareLogEntry(JSON_ENTRY, LogEntry.fromPb(JSON_ENTRY.toPb("project")));
compareLogEntry(PROTO_ENTRY, LogEntry.fromPb(PROTO_ENTRY.toPb("project")));
compareLogEntry(STRING_ENTRY_BILLING, LogEntry.fromPb(STRING_ENTRY_BILLING.toPb("project")));
compareLogEntry(STRING_ENTRY_FOLDER, LogEntry.fromPb(STRING_ENTRY_FOLDER.toPb("project")));
compareLogEntry(STRING_ENTRY_ORG, LogEntry.fromPb(STRING_ENTRY_ORG.toPb("project")));
losalex marked this conversation as resolved.
Show resolved Hide resolved
LogEntry logEntry = LogEntry.of(STRING_PAYLOAD);
compareLogEntry(logEntry, LogEntry.fromPb(logEntry.toPb("project")));
logEntry = LogEntry.of(LOG_NAME, RESOURCE, STRING_PAYLOAD);
compareLogEntry(logEntry, LogEntry.fromPb(logEntry.toPb("project")));
logEntry =
LogEntry.newBuilder(STRING_PAYLOAD)
.setLogName(LOG_NAME)
.setResource(RESOURCE)
.setDestination(folderName)
.build();
compareLogEntry(logEntry, LogEntry.fromPb(logEntry.toPb("project")));
losalex marked this conversation as resolved.
Show resolved Hide resolved
}

@Test(expected = AssertionError.class)
public void testToAndFromPbWithExpectedFailure() {
LogEntry logEntry =
LogEntry.newBuilder(STRING_PAYLOAD)
.setLogName(LOG_NAME)
.setResource(RESOURCE)
.setDestination(projectName)
.build();
/**
* Project ID destination should never be serialized into PB payload, thus below call should
* always fail for inconsistency
*/
compareLogEntry(logEntry, LogEntry.fromPb(logEntry.toPb("project")));
losalex marked this conversation as resolved.
Show resolved Hide resolved
}

private void compareLogEntry(LogEntry expected, LogEntry value) {
Expand Down