A client for Cloud Logging - Real-time log management and analysis.
Here's a simple usage example for using google-cloud from Compute Engine/App Engine Flexible. This example shows how to write and list log entries. For the complete source code see WriteAndListLogEntries.java.
LoggingOptions options = LoggingOptions.getDefaultInstance();
try(Logging logging = options.getService()) {
LogEntry firstEntry = LogEntry.newBuilder(StringPayload.of("message"))
.setLogName("test-log")
.setResource(MonitoredResource.builder("global")
.addLabel("project_id", options.getProjectId())
.build())
.build();
logging.write(Collections.singleton(firstEntry));
Page<LogEntry> entries = logging.listLogEntries(
EntryListOption.filter("logName=projects/" + options.getProjectId() + "/logs/test-log"));
Iterator<LogEntry> entryIterator = entries.iterateAll();
while (entryIterator.hasNext()) {
System.out.println(entryIterator.next());
}
}
This second example shows how to use a java.util.logging.Logger to write log entries
to Cloud Logging. The snippet installs a Cloud Logging handler using
LoggingHandler.addHandler(Logger, LoggingHandler)
. Notice that this could also be done through
the logging.properties
file, adding the following line:
com.google.cloud.examples.logging.snippets.AddLoggingHandler.handlers=com.google.cloud.logging.LoggingHandler
For the complete source code see AddLoggingHandler.java.
Logger logger = Logger.getLogger(AddLoggingHandler.class.getName());
LoggingHandler.addHandler(logger, new LoggingHandler());
logger.warning("test warning");
See Also: Cloud Logging
Classes
Context
Class to hold context attributes including information about {@see HttpRequest} and tracing.
Context.Builder
A builder for {@see Context} objects.
ContextHandler
Class provides a per-thread storage of the {@see Context} instances.
Exclusion
Specifies a set of log entries that are not to be stored in Logging. If your GCP resource receives a large volume of logs, you can use exclusions to reduce your chargeable logs. Exclusions are processed after log sinks, so you can export log entries before they are excluded. Note that organization-level and folder-level exclusions don't apply to child resources, and that you can't exclude audit log entries.
Exclusion.Builder
A builder for Exclusion
objects.
HttpRequest
Objects of this class represent information about the (optional) HTTP request associated with a log entry. See Also: Http Request
HttpRequest.Builder
A builder for HttpRequest
objects.
HttpRequest.RequestMethod
The HTTP request method.
LogDestinationName
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)
LogEntry
A Cloud Logging log entry. All log entries are represented via objects of this class. Log entries can have different type of payloads: an UTF-8 string (see Payload.StringPayload), a JSON object (see Payload.JsonPayload, or a protobuf object (see Payload.ProtoPayload). Entries can also store additional information about the operation or the HTTP request that generated the log (see LogEntry#getOperation() and LogEntry#getHttpRequest(), respectively). See Also: Log Entries and Logs
LogEntry.Builder
A builder for LogEntry
objects.
LogEntryIterator
The class implements {@see Iterator} interface over {@see LogEntry} by iterating through {@see
TailLogEntriesResponse} streamed by BidiStream
. This class is instantiated by {@see
LogEntryServerStream} and is not intended to be used explicitly.
LogEntryServerStream
The class implements {@Iterable } interface over {@see LogEntry}. It wraps around {@BidiStream } bi-directional gRPC stream to support iterating through ingested responses. The class uses {@see LogEntryIterator} to iterate through the processed responses. The stream should be explicitly canceled by calling {@see LogEntryServerStream#cancel()} method. The class does not provide recovery or resuming functionality over the stream.
To iterate run:
LogEntryServerStream stream;
// code to initialize stream
for (LogEntry log : stream) {
// do something with logs
}
stream.cancel();
The iteration can be blocked on waiting for another response sent in the stream.
Logging.EntryListOption
Class for specifying options for listing log entries.
Logging.ListOption
Class for specifying options for listing sinks, monitored resources and monitored resource descriptors.
Logging.TailOption
Class for specifying options for tailing log entries.
Logging.WriteOption
Class for specifying options for writing log entries.
LoggingHandler
A logging handler that outputs logs generated with java.util.logging.Logger to Cloud Logging.
Java logging levels (see java.util.logging.Level) are mapped to the following Google Cloud Logging severities:
Java Level | Cloud Logging Severity |
---|---|
SEVERE | ERROR |
WARNING | WARNING |
INFO | INFO |
CONFIG | INFO |
FINE | DEBUG |
FINER | DEBUG |
FINEST | DEBUG |
Original Java logging levels are added as labels (with levelName
and
levelValue
keys, respectively) to the corresponding Cloud Logging LogEntry. You can read
entry labels using LogEntry#getLabels(). To use logging levels that correspond to Cloud
Logging severities you can use LoggingLevel.
Configuration: By default each LoggingHandler
is initialized using the
following LogManager
configuration properties (that you can set in the
logging.properties
file). If properties are not defined (or have invalid values) then the
specified default values are used.
com.google.cloud.logging.LoggingHandler.log
the log name (defaults tojava.log
).com.google.cloud.logging.LoggingHandler.level
specifies the default level for the handler (defaults toLevel.INFO
).com.google.cloud.logging.LoggingHandler.filter
specifies the name of a Filter class to use (defaults to no filter).com.google.cloud.logging.LoggingHandler.formatter
specifies the name of a Formatter class to use (defaults to SimpleFormatter).com.google.cloud.logging.LoggingHandler.flushLevel
specifies the flush log level. When a log with this level is published, logs are transmitted to the Cloud Logging service (defaults to LoggingLevel#ERROR).com.google.cloud.logging.LoggingHandler.enhancers
specifies a comma separated list of LoggingEnhancer classes. This handler will call each enhancer list whenever it builds a LogEntry instance (defaults to empty list).com.google.cloud.logging.LoggingHandler.resourceType
the type name to use when creating the default MonitoredResource (defaults to auto-detected resource type, else "global").com.google.cloud.logging.Synchronicity
the synchronicity of the write method to use to write logs to the Cloud Logging service (defaults to Synchronicity#ASYNC).com.google.cloud.logging.LoggingHandler.autoPopulateMetadata
is a boolean flag that opts-out the population of the log entries metadata before the logs are sent to Cloud Logging (defaults totrue
).com.google.cloud.logging.LoggingHandler.redirectToStdout
is a boolean flag that opts-in redirecting the output of the handler to STDOUT instead of ingesting logs to Cloud Logging using Logging API (defaults totrue
). Redirecting logs can be used in Google Cloud environments with installed logging agent to delegate log ingestions to the agent. Redirected logs are formatted as one line Json string following the structured logging guidelines.
To add a LoggingHandler
to an existing Logger and be sure to avoid infinite
recursion when logging, use the #addHandler(Logger, LoggingHandler) method. Alternatively
you can add the handler via logging.properties
. For example using the following line:
com.example.mypackage.handlers=com.google.cloud.logging.LoggingHandler
See Also: Structured logging
LoggingLevel
This class adds some additional Java logging levels for Cloud Logging. Added levels fill in the gap between Java logging levels and Cloud Logging severities.
Added levels in descending order are (between parenthesis the relation with Java logging levels):
- EMERGENCY
- ALERT
- CRITICAL
- ERROR (
WARNING < ERROR < SEVERE
) - NOTICE (
INFO < NOTICE < WARNING
) - DEBUG (
ALL < DEBUG < FINES
T
Notice that ERROR
is lower than java.util.logging.Level#SEVERE but higher than
java.util.logging.Level#WARNING. DEBUG
instead is lower than java.util.logging.Level#FINEST but higher than java.util.logging.Level#ALL.
LoggingOptions
LoggingOptions.Builder
LoggingOptions.DefaultLoggingFactory
LoggingOptions.DefaultLoggingRpcFactory
MetadataLoader
Metric
Cloud Logging metrics describe logs-based metric. The value of the metric is the number of log entries that match a logs filter (see #getFilter()).
Metric
adds a layer of service-related functionality over MetricInfo. Objects
of this class are immutable. To get a Metric
object with the most recent information use
#reload or #reloadAsync.
See Also: Logs-based Metrics
Metric.Builder
A builder for Metric
objects.
MetricInfo
Cloud Logging metrics describe logs-based metric. The value of the metric is the number of log entries that match a logs filter (see #getFilter()). See Also: Logs-based Metrics
MetricInfo.Builder
A builder for MetricInfo
objects.
MonitoredResourceUtil
Monitored resource construction utilities to detect resource type and add labels. Used by logging framework adapters to configure default resource. See usage in LoggingHandler.
Operation
Additional information about a potentially long-running operation with which a log entry is associated. See Also: Log Entry Operation
Operation.Builder
A builder for Operation
objects.
Payload<T>
A base class for log entry payloads. See Also: Log Entries and Logs
Payload.JsonPayload
A log entry's JSON payload.
Payload.ProtoPayload
A log entry payload as a protobuf object.
Payload.StringPayload
A log entry payload as an UTF-8 string.
Sink
Cloud Logging sinks can be used to control the export of your logs. Each sink specifies the export of a set of log entries to a certain destination. A sink consists of a name, unique to the project, a filter for choosing the log entries to export and a destination for the log entries.
Sink destination can either be a Google Cloud Storage bucket (see SinkInfo.Destination.BucketDestination, a Google Cloud BigQuery dataset (see SinkInfo.Destination.DatasetDestination) or a Google CloudPub/Sub topic (see SinkInfo.Destination.TopicDestination).
Sink
adds a layer of service-related functionality over SinkInfo. Objects of
this class are immutable. To get a Sink
object with the most recent information use
#reload or #reloadAsync.
See Also: About Sinks
Sink.Builder
A builder for Sink
objects.
SinkInfo
Cloud Logging sinks can be used to control the export of your logs. Each sink specifies the export of a set of log entries to a certain destination. A sink consists of a name, unique to the project, a filter for choosing the log entries to export and a destination for the log entries.
Sink destination can either be a Google Cloud Storage bucket (see Destination.BucketDestination, a Google Cloud BigQuery dataset (see Destination.DatasetDestination) or a Google Cloud Pub/Sub topic (see Destination.TopicDestination). See Also: About Sinks
SinkInfo.Builder
A builder for SinkInfo
objects.
SinkInfo.Destination
SinkInfo.Destination.BucketDestination
Class for specifying a Google Cloud Storage bucket as destination for the sink.
SinkInfo.Destination.DatasetDestination
Class for specifying a Google Cloud BigQuery dataset as destination for the sink.
SinkInfo.Destination.LoggingBucketDestination
SinkInfo.Destination.TopicDestination
Class for specifying a Google Cloud BigQuery dataset as destination for the sink.
SourceLocation
Additional information about the source code location that produced the log entry.
SourceLocation.Builder
A builder for SourceLocation
objects.
TimestampDefaultFilter
TraceLoggingEnhancer
Interfaces
ITimestampDefaultFilter
Encapsulates implementation of default time filter. This is needed for testing since we can't mock static classes with EasyMock
Logging
LoggingEnhancer
An enhancer for log entries. Used to add custom labels to the LogEntry.Builder
LoggingFactory
An interface for Logging factories.
ResourceTypeEnvironmentGetter
Enums
LogDestinationName.DestinationType
Logging.SortingField
Fields according to which log entries can be sorted.
Logging.SortingOrder
Sorting orders available when listing log entries.
MonitoredResourceUtil.Label
Payload.Type
Type for a log entry payload.
Severity
The severity of the event described in a log entry. These guideline severity levels are ordered,
with numerically smaller levels treated as less severe than numerically larger levels. If the
source of the log entries uses a different set of severity levels, the client should select the
closest corresponding Severity
value.
SinkInfo.Destination.Type
Type of destination for Cloud Logging sink.
SinkInfo.VersionFormat
Available log entry formats. Log entries can be written to Cloud Logging in either format and can be exported in either format. Version 2 is the preferred format.
Synchronicity
Used to specify the behavior of write calls to the Cloud Logging service. Specifying SYNC will make synchronous calls; specifying ASYNC will make asynchronous calls. The default behavior is ASYNC.
Exceptions
LoggingException
Logging service exception.