Copyright 2016 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 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.
API/gRPC features intentionally missing from this client: - You cannot have the server pick the time of the entry. This client always sends a time. - There is no way to provide a protocol buffer payload. - No support for the "partial success" feature when writing log entries.
TODO(jba): test whether forward-slash characters in the log ID must be URL-encoded. These features are missing now, but will likely be added: - There is no way to specify CallOptions.

package logging

import (
	
	
	
	
	
	
	
	
	
	
	
	
	

	
	
	vkit 
	
	
	
	structpb 
	tspb 
	
	
	mrpb 
	logtypepb 
	logpb 
)

ReadScope is the scope for reading from the logging service.
	ReadScope = "https://www.googleapis.com/auth/logging.read"
WriteScope is the scope for writing to the logging service.
	WriteScope = "https://www.googleapis.com/auth/logging.write"
AdminScope is the scope for administrative actions on the logging service.
	AdminScope = "https://www.googleapis.com/auth/logging.admin"
)

defaultErrorCapacity is the capacity of the channel used to deliver errors to the OnError function.
DefaultDelayThreshold is the default value for the DelayThreshold LoggerOption.
DefaultEntryCountThreshold is the default value for the EntryCountThreshold LoggerOption.
DefaultEntryByteThreshold is the default value for the EntryByteThreshold LoggerOption.
	DefaultEntryByteThreshold = 1 << 20 // 1MiB
DefaultBufferedByteLimit is the default value for the BufferedByteLimit LoggerOption.
	DefaultBufferedByteLimit = 1 << 30 // 1GiB
defaultWriteTimeout is the timeout for the underlying write API calls. As write API calls are not idempotent, they are not retried on timeout. This timeout is to allow clients to degrade gracefully if underlying logging service is temporarily impaired for some reason.
For testing:
var now = time.Now
ErrOverflow signals that the number of buffered entries for a Logger exceeds its BufferLimit.
ErrOversizedEntry signals that an entry's size exceeds the maximum number of bytes that will be sent in a single call to the logging service.
Client is a Logging client. A Client is associated with a single Cloud project.
type Client struct {
	client  *vkit.Client   // client for the logging service
	parent  string         // e.g. "projects/proj-id"
	errc    chan error     // should be buffered to minimize dropped errors
	donec   chan struct{}  // closed on Client.Close to close Logger bundlers
	loggers sync.WaitGroup // so we can wait for loggers to close
	closed  bool

	mu      sync.Mutex
	nErrs   int   // number of errors we saw
	lastErr error // last error we saw
OnError is called when an error occurs in a call to Log or Flush. The error may be due to an invalid Entry, an overflow because BufferLimit was reached (in which case the error will be ErrOverflow) or an error communicating with the logging service. OnError is called with errors from all Loggers. It is never called concurrently. OnError is expected to return quickly; if errors occur while OnError is running, some may not be reported. The default behavior is to call log.Printf. This field should be set only once, before any method of Client is called.
	OnError func(err error)
}
NewClient returns a new logging client associated with the provided parent. A parent can take any of the following forms: projects/PROJECT_ID folders/FOLDER_ID billingAccounts/ACCOUNT_ID organizations/ORG_ID for backwards compatibility, a string with no '/' is also allowed and is interpreted as a project ID. By default NewClient uses WriteScope. To use a different scope, call NewClient using a WithScopes option (see https://godoc.org/google.golang.org/api/option#WithScopes).
func ( context.Context,  string,  ...option.ClientOption) (*Client, error) {
	if !strings.ContainsRune(, '/') {
		 = "projects/" + 
	}
	 = append([]option.ClientOption{
		option.WithEndpoint(internal.ProdAddr),
		option.WithScopes(WriteScope),
	}, ...)
	,  := vkit.NewClient(, ...)
	if  != nil {
		return nil, 
	}
	.SetGoogleClientInfo("gccl", version.Repo)
	 := &Client{
		client:  ,
		parent:  ,
		errc:    make(chan error, defaultErrorCapacity), // create a small buffer for errors
		donec:   make(chan struct{}),
		OnError: func( error) { log.Printf("logging client: %v", ) },
Call the user's function synchronously, to make life easier for them.
	go func() {
This reference to OnError is memory-safe if the user sets OnError before calling any client methods. The reference happens before the first read from client.errc, which happens before the first write to client.errc, which happens before any call, which happens before the user sets OnError.
			if  := .OnError;  != nil {
				()
			} else {
				log.Printf("logging (parent %q): %v", , )
			}
		}
	}()
	return , nil
}

var unixZeroTimestamp *tspb.Timestamp

func () {
	var  error
	unixZeroTimestamp,  = ptypes.TimestampProto(time.Unix(0, 0))
	if  != nil {
		panic()
	}
}
Ping reports whether the client's connection to the logging service and the authentication configuration are valid. To accomplish this, Ping writes a log entry "ping" to a log named "ping".
func ( *Client) ( context.Context) error {
	 := &logpb.LogEntry{
		Payload:   &logpb.LogEntry_TextPayload{TextPayload: "ping"},
		Timestamp: unixZeroTimestamp, // Identical timestamps and insert IDs are both
		InsertId:  "ping",            // necessary for the service to dedup these entries.
	}
	,  := .client.WriteLogEntries(, &logpb.WriteLogEntriesRequest{
		LogName:  internal.LogPath(.parent, "ping"),
		Resource: monitoredResource(.parent),
		Entries:  []*logpb.LogEntry{},
	})
	return 
}
error puts the error on the client's error channel without blocking, and records summary error info.
func ( *Client) ( error) {
	select {
	case .errc <- :
	default:
	}
	.mu.Lock()
	.lastErr = 
	.nErrs++
	.mu.Unlock()
}

func ( *Client) () error {
	var  error
	.mu.Lock()
	if .lastErr != nil {
		 = fmt.Errorf("saw %d errors; last: %v", .nErrs, .lastErr)
		.nErrs = 0
		.lastErr = nil
	}
	.mu.Unlock()
	return 
}
A Logger is used to write log messages to a single log. It can be configured with a log ID, common monitored resource, and a set of common labels.
type Logger struct {
	client     *Client
	logName    string // "projects/{projectID}/logs/{logID}"
	stdLoggers map[Severity]*log.Logger
	bundler    *bundler.Bundler
A LoggerOption is a configuration option for a Logger.
type LoggerOption interface {
	set(*Logger)
}
CommonResource sets the monitored resource associated with all log entries written from a Logger. If not provided, the resource is automatically detected based on the running environment. This value can be overridden per-entry by setting an Entry's Resource field.
func ( *mrpb.MonitoredResource) LoggerOption { return commonResource{} }

type commonResource struct{ *mrpb.MonitoredResource }

func ( commonResource) ( *Logger) { .commonResource = .MonitoredResource }

var detectedResource struct {
	pb   *mrpb.MonitoredResource
	once sync.Once
}

func () *mrpb.MonitoredResource {
	detectedResource.once.Do(func() {
		if !metadata.OnGCE() {
			return
		}
		,  := metadata.ProjectID()
		if  != nil {
			return
		}
		,  := metadata.InstanceID()
		if  != nil {
			return
		}
		,  := metadata.Zone()
		if  != nil {
			return
		}
		,  := metadata.InstanceName()
		if  != nil {
			return
		}
		detectedResource.pb = &mrpb.MonitoredResource{
			Type: "gce_instance",
			Labels: map[string]string{
				"project_id":    ,
				"instance_id":   ,
				"instance_name": ,
				"zone":          ,
			},
		}
	})
	return detectedResource.pb
}

var resourceInfo = map[string]struct{ rtype, label string }{
	"organizations":   {"organization", "organization_id"},
	"folders":         {"folder", "folder_id"},
	"projects":        {"project", "project_id"},
	"billingAccounts": {"billing_account", "account_id"},
}

func ( string) *mrpb.MonitoredResource {
	 := strings.SplitN(, "/", 2)
	if len() != 2 {
		return globalResource()
	}
	,  := resourceInfo[[0]]
	if ! {
		return globalResource([1])
	}
	return &mrpb.MonitoredResource{
		Type:   .rtype,
		Labels: map[string]string{.label: [1]},
	}
}

func ( string) *mrpb.MonitoredResource {
	return &mrpb.MonitoredResource{
		Type: "global",
		Labels: map[string]string{
			"project_id": ,
		},
	}
}
CommonLabels are labels that apply to all log entries written from a Logger, so that you don't have to repeat them in each log entry's Labels field. If any of the log entries contains a (key, value) with the same key that is in CommonLabels, then the entry's (key, value) overrides the one in CommonLabels.
func ( map[string]string) LoggerOption { return commonLabels() }

type commonLabels map[string]string

func ( commonLabels) ( *Logger) { .commonLabels =  }
ConcurrentWriteLimit determines how many goroutines will send log entries to the underlying service. The default is 1. Set ConcurrentWriteLimit to a higher value to increase throughput.
DelayThreshold is the maximum amount of time that an entry should remain buffered in memory before a call to the logging service is triggered. Larger values of DelayThreshold will generally result in fewer calls to the logging service, while increasing the risk that log entries will be lost if the process crashes. The default is DefaultDelayThreshold.
EntryCountThreshold is the maximum number of entries that will be buffered in memory before a call to the logging service is triggered. Larger values will generally result in fewer calls to the logging service, while increasing both memory consumption and the risk that log entries will be lost if the process crashes. The default is DefaultEntryCountThreshold.
EntryByteThreshold is the maximum number of bytes of entries that will be buffered in memory before a call to the logging service is triggered. See EntryCountThreshold for a discussion of the tradeoffs involved in setting this option. The default is DefaultEntryByteThreshold.
EntryByteLimit is the maximum number of bytes of entries that will be sent in a single call to the logging service. ErrOversizedEntry is returned if an entry exceeds EntryByteLimit. This option limits the size of a single RPC payload, to account for network or service issues with large RPCs. If EntryByteLimit is smaller than EntryByteThreshold, the latter has no effect. The default is zero, meaning there is no limit.
BufferedByteLimit is the maximum number of bytes that the Logger will keep in memory before returning ErrOverflow. This option limits the total memory consumption of the Logger (but note that each Logger has its own, separate limit). It is possible to reach BufferedByteLimit even if it is larger than EntryByteThreshold or EntryByteLimit, because calls triggered by the latter two options may be enqueued (and hence occupying memory) while new log entries are being added. The default is DefaultBufferedByteLimit.
ContextFunc is a function that will be called to obtain a context.Context for the WriteLogEntries RPC executed in the background for calls to Logger.Log. The default is a function that always returns context.Background. The second return value of the function is a function to call after the RPC completes. The function is not used for calls to Logger.LogSync, since the caller can pass in the context directly. This option is EXPERIMENTAL. It may be changed or removed.
func ( func() ( context.Context,  func())) LoggerOption {
	return contextFunc()
}

type contextFunc func() (ctx context.Context, afterCall func())

func ( contextFunc) ( *Logger) { .ctxFunc =  }
Logger returns a Logger that will write entries with the given log ID, such as "syslog". A log ID must be less than 512 characters long and can only include the following characters: upper and lower case alphanumeric characters: [A-Za-z0-9]; and punctuation characters: forward-slash, underscore, hyphen, and period.
Start a goroutine that cleans up the bundler, its channel and the writer goroutines when the client is closed.
	go func() {
		defer .loggers.Done()
		<-.donec
		.bundler.Flush()
	}()
	return 
}

type severityWriter struct {
	l *Logger
	s Severity
}

func ( severityWriter) ( []byte) ( int,  error) {
	.l.Log(Entry{
		Severity: .s,
		Payload:  string(),
	})
	return len(), nil
}
Close waits for all opened loggers to be flushed and closes the client.
func ( *Client) () error {
	if .closed {
		return nil
	}
	close(.donec)   // close Logger bundlers
Now there can be no more errors.
Prefer errors arising from logging to the error returned from Close.
	 := .extractErrorInfo()
	 := .client.Close()
	if  == nil {
		 = 
	}
	.closed = true
	return 
}
Severity is 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.
Default means the log entry has no assigned severity level.
Debug means debug or trace information.
Info means routine information, such as ongoing status or performance.
Notice means normal but significant events, such as start up, shut down, or configuration.
Warning means events that might cause problems.
Error means events that are likely to cause problems.
Critical means events that cause more severe problems or brief outages.
Alert means a person must take an action immediately.
Emergency means one or more systems are unusable.
	Emergency = Severity(logtypepb.LogSeverity_EMERGENCY)
)

var severityName = map[Severity]string{
	Default:   "Default",
	Debug:     "Debug",
	Info:      "Info",
	Notice:    "Notice",
	Warning:   "Warning",
	Error:     "Error",
	Critical:  "Critical",
	Alert:     "Alert",
	Emergency: "Emergency",
}
String converts a severity level to a string.
same as proto.EnumName
	,  := severityName[]
	if  {
		return 
	}
	return strconv.Itoa(int())
}
ParseSeverity returns the Severity whose name equals s, ignoring case. It returns Default if no Severity matches.
func ( string) Severity {
	 := strings.ToLower()
	for ,  := range severityName {
		if strings.ToLower() ==  {
			return 
		}
	}
	return Default
}
Entry is a log entry. See https://cloud.google.com/logging/docs/view/logs_index for more about entries.
Timestamp is the time of the entry. If zero, the current time is used.
Severity is the entry's severity level. The zero value is Default.
Payload must be either a string, or something that marshals via the encoding/json package to a JSON object (and not any other type of JSON value).
	Payload interface{}
Labels optionally specifies key/value labels for the log entry. The Logger.Log method takes ownership of this map. See Logger.CommonLabels for more about labels.
InsertID is a unique ID for the log entry. If you provide this field, the logging service considers other log entries in the same log with the same ID as duplicates which can be removed. If omitted, the logging service will generate a unique ID for this log entry. Note that because this client retries RPCs automatically, it is possible (though unlikely) that an Entry without an InsertID will be written more than once.
HTTPRequest optionally specifies metadata about the HTTP request associated with this log entry, if applicable. It is optional.
Operation optionally provides information about an operation associated with the log entry, if applicable.
LogName is the full log name, in the form "projects/{ProjectID}/logs/{LogID}". It is set by the client when reading entries. It is an error to set it when writing entries.
Resource is the monitored resource associated with the entry.
Trace is the resource name of the trace associated with the log entry, if any. If it contains a relative resource name, the name is assumed to be relative to //tracing.googleapis.com.
ID of the span within the trace associated with the log entry. The ID is a 16-character hexadecimal encoding of an 8-byte array.
If set, symbolizes that this request was sampled.
Optional. Source code location information associated with the log entry, if any.
HTTPRequest contains an http.Request as well as additional information about the request and its response.
Request is the http.Request passed to the handler.
RequestSize is the size of the HTTP request message in bytes, including the request headers and the request body.
Status is the response code indicating the status of the response. Examples: 200, 404.
ResponseSize is the size of the HTTP response message sent back to the client, in bytes, including the response headers and the response body.
Latency is the request processing latency on the server, from the time the request was received until the response was sent.
LocalIP is the IP address (IPv4 or IPv6) of the origin server that the request was sent to.
RemoteIP is the IP address (IPv4 or IPv6) of the client that issued the HTTP request. Examples: "192.168.1.1", "FE80::0202:B3FF:FE1E:8329".
CacheHit reports whether an entity was served from cache (with or without validation).
CacheValidatedWithOriginServer reports whether the response was validated with the origin server before being served from cache. This field is only meaningful if CacheHit is true.
	CacheValidatedWithOriginServer bool
}

func ( *HTTPRequest) *logtypepb.HttpRequest {
	if  == nil {
		return nil
	}
	if .Request == nil {
		panic("HTTPRequest must have a non-nil Request")
	}
	 := *.Request.URL
	.Fragment = ""
	 := &logtypepb.HttpRequest{
		RequestMethod:                  .Request.Method,
		RequestUrl:                     fixUTF8(.String()),
		RequestSize:                    .RequestSize,
		Status:                         int32(.Status),
		ResponseSize:                   .ResponseSize,
		UserAgent:                      .Request.UserAgent(),
		ServerIp:                       .LocalIP,
		RemoteIp:                       .RemoteIP, // TODO(jba): attempt to parse http.Request.RemoteAddr?
		Referer:                        .Request.Referer(),
		CacheHit:                       .CacheHit,
		CacheValidatedWithOriginServer: .CacheValidatedWithOriginServer,
	}
	if .Latency != 0 {
		.Latency = ptypes.DurationProto(.Latency)
	}
	return 
}
fixUTF8 is a helper that fixes an invalid UTF-8 string by replacing invalid UTF-8 runes with the Unicode replacement character (U+FFFD). See Issue https://github.com/googleapis/google-cloud-go/issues/1383.
func ( string) string {
	if utf8.ValidString() {
		return 
	}
Otherwise time to build the sequence.
	 := new(bytes.Buffer)
	.Grow(len())
	for ,  := range  {
		if utf8.ValidRune() {
			.WriteRune()
		} else {
			.WriteRune('\uFFFD')
		}
	}
	return .String()
}
toProtoStruct converts v, which must marshal into a JSON object, into a Google Struct proto.
Fast path: if v is already a *structpb.Struct, nothing to do.
	if ,  := .(*structpb.Struct);  {
		return , nil
v is a Go value that supports JSON marshalling. We want a Struct protobuf. Some day we may have a more direct way to get there, but right now the only way is to marshal the Go value to JSON, unmarshal into a map, and then build the Struct proto from the map.
	var  []byte
	var  error
	if ,  := .(json.RawMessage);  { // needed for Go 1.7 and below
		 = []byte()
	} else {
		,  = json.Marshal()
		if  != nil {
			return nil, fmt.Errorf("logging: json.Marshal: %v", )
		}
	}
	var  map[string]interface{}
	 = json.Unmarshal(, &)
	if  != nil {
		return nil, fmt.Errorf("logging: json.Unmarshal: %v", )
	}
	return jsonMapToProtoStruct(), nil
}

func ( map[string]interface{}) *structpb.Struct {
	 := map[string]*structpb.Value{}
	for ,  := range  {
		[] = jsonValueToStructValue()
	}
	return &structpb.Struct{Fields: }
}

func ( interface{}) *structpb.Value {
	switch x := .(type) {
	case bool:
		return &structpb.Value{Kind: &structpb.Value_BoolValue{BoolValue: }}
	case float64:
		return &structpb.Value{Kind: &structpb.Value_NumberValue{NumberValue: }}
	case string:
		return &structpb.Value{Kind: &structpb.Value_StringValue{StringValue: }}
	case nil:
		return &structpb.Value{Kind: &structpb.Value_NullValue{}}
	case map[string]interface{}:
		return &structpb.Value{Kind: &structpb.Value_StructValue{StructValue: jsonMapToProtoStruct()}}
	case []interface{}:
		var  []*structpb.Value
		for ,  := range  {
			 = append(, ())
		}
		return &structpb.Value{Kind: &structpb.Value_ListValue{ListValue: &structpb.ListValue{Values: }}}
	default:
		panic(fmt.Sprintf("bad type %T for JSON value", ))
	}
}
LogSync logs the Entry synchronously without any buffering. Because LogSync is slow and will block, it is intended primarily for debugging or critical errors. Prefer Log for most uses. TODO(jba): come up with a better name (LogNow?) or eliminate.
func ( *Logger) ( context.Context,  Entry) error {
	,  := .toLogEntry()
	if  != nil {
		return 
	}
	_,  = .client.client.WriteLogEntries(, &logpb.WriteLogEntriesRequest{
		LogName:  .logName,
		Resource: .commonResource,
		Labels:   .commonLabels,
		Entries:  []*logpb.LogEntry{},
	})
	return 
}
Log buffers the Entry for output to the logging service. It never blocks.
func ( *Logger) ( Entry) {
	,  := .toLogEntry()
	if  != nil {
		.client.error()
		return
	}
	if  := .bundler.Add(, proto.Size());  != nil {
		.client.error()
	}
}
Flush blocks until all currently buffered log entries are sent. If any errors occurred since the last call to Flush from any Logger, or the creation of the client if this is the first call, then Flush returns a non-nil error with summary information about the errors. This information is unlikely to be actionable. For more accurate error reporting, set Client.OnError.
func ( *Logger) () error {
	.bundler.Flush()
	return .client.extractErrorInfo()
}

func ( *Logger) ( []*logpb.LogEntry) {
	 := &logpb.WriteLogEntriesRequest{
		LogName:  .logName,
		Resource: .commonResource,
		Labels:   .commonLabels,
		Entries:  ,
	}
	,  := .ctxFunc()
	,  := context.WithTimeout(, defaultWriteTimeout)
	defer ()
	,  := .client.client.WriteLogEntries(, )
	if  != nil {
		.client.error()
	}
	if  != nil {
		()
	}
}
StandardLogger returns a *log.Logger for the provided severity. This method is cheap. A single log.Logger is pre-allocated for each severity level in each Logger. Callers may mutate the returned log.Logger (for example by calling SetFlags or SetPrefix).
func ( *Logger) ( Severity) *log.Logger { return .stdLoggers[] }

var reCloudTraceContext = regexp.MustCompile(`([a-f\d]+)/([a-f\d]+);o=(\d)`)

As per the format described at https://cloud.google.com/trace/docs/troubleshooting#force-trace "X-Cloud-Trace-Context: TRACE_ID/SPAN_ID;o=TRACE_TRUE" for example: "X-Cloud-Trace-Context: 105445aa7843bc8bf206b120001000/0;o=1" We expect: * traceID: "105445aa7843bc8bf206b120001000" * spanID: "" * traceSampled: true
	 := reCloudTraceContext.FindAllStringSubmatch(, -1)
	if len() != 1 {
		return
	}

	 := [0]
	if len() != 4 {
		return
	}

	,  = [1], [2]
	if  == "0" {
		 = ""
	}
	 = [3] == "1"

	return
}

func ( *Logger) ( Entry) (*logpb.LogEntry, error) {
	if .LogName != "" {
		return nil, errors.New("logging: Entry.LogName should be not be set when writing")
	}
	 := .Timestamp
	if .IsZero() {
		 = now()
	}
	,  := ptypes.TimestampProto()
	if  != nil {
		return nil, 
	}
	if .Trace == "" && .HTTPRequest != nil && .HTTPRequest.Request != nil {
		 := .HTTPRequest.Request.Header.Get("X-Cloud-Trace-Context")
Set to a relative resource name, as described at https://cloud.google.com/appengine/docs/flexible/go/writing-application-logs.
			, ,  := deconstructXCloudTraceContext()
			if  != "" {
				.Trace = fmt.Sprintf("%s/traces/%s", .client.parent, )
			}
			if .SpanID == "" {
				.SpanID = 
			}
If we previously hadn't set TraceSampled, let's retrieve it from the HTTP request's header, as per: https://cloud.google.com/trace/docs/troubleshooting#force-trace