zerodriver

package module
v0.1.4 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 8, 2023 License: MIT Imports: 9 Imported by: 12

README

zerodriver

Go Reference Go Report Card Coverage Status Apache-2.0

Zerolog based logging libary optimized for Cloud Logging (formerly Stackdriver Logging). This package is inspired by Zapdriver.

What is this package?

This package provides simple structured logger optimized for Cloud Logging based on zerolog.

Key features of zerodriver are:

Usage

First of all, initialize a logger.

logger := zerodriver.NewProductionLogger() // production mode (global log level set to `info`)
logger := zerodriver.NewDevelopmentLogger() // development mode (global log level set to `debug`)

Then, write logs by using zerolog based fluent API!

logger.Info().Str("key", "value").Msg("Hello World!")
// output: {"severity":"INFO","key":"value","time":"2009-11-10T23:00:00Z","message":"hello world"}

Here's complete example:

package main

import (
    "github.com/hirosassa/zerodriver"
)

func main() {
    logger := zerodriver.NewProductionLogger()
    logger.Info().Str("key", "value").Msg("hello world")
}

// output: {"severity":"INFO","key":"value","time":"2009-11-10T23:00:00Z","message":"hello world"}
GCP specific fields

If your log follows LogEntry format, you can query logs or create metrics alert easier and efficiently on GCP Cloud Logging console.

HTTP request

To log HTTP related metrics and information, you can use following function

func (e *Event) HTTP(req *HTTPPayload) *zerolog.Event

This feature is forked from zapdriver. You can generate zerodriver.HTTPPayload from http.Request and http.Response using NewHTTP function. Same as zapdriver.NewHTTP, following fields needs to be set manually:

  • ServerIP
  • Latency
  • CacheLookup
  • CacheHit
  • CacheValidatedWithOriginServer
  • CacheFillBytes

Using these feature, you can log HTTP related information as follows,

p := NewHTTP(req, res)
p.Latency = time.Since(start) // add some fields manually
logger.Info().HTTP(p).Msg("request received")
Trace context

To add trace information to your log, you can use TraceContext. The signature of the function is as follows:

func (e *Event) TraceContext(trace string, spanId string, sampled bool, projectID string) *zerolog.Event

You can use this feature as follows:

import	"go.opencensus.io/trace"

span := trace.FromContext(r.Context()).SpanContext()
logger.Info().TraceContext(span.TraceID.String(), span.SpanID.String(), true, "my-project").Msg("trace contexts")

// {"severity":"INFO","logging.googleapis.com/trace":"projects/my-project/traces/00000000000000000000000000000000","logging.googleapis.com/spanId":"0000000000000000","logging.googleapis.com/trace_sampled":true,"message":"trace contexts"}
Labels

You can add any "labels" to your log by following:

logger.Info().Labels(zerodriver.Label("foo", "var")).Msg("labeled log")

// {"severity":"INFO","logging.googleapis.com/labels":{"foo":"var"},"message":"labeled log"}
Operations

You can add additional information about a potentially long-running operation with which a log entry is associated by following function:

func (e *Event) Operation(id, producer string, first, last bool) *zerolog.Event

Log entries with the same id are assumed to be part of the same operation. The producer is an arbitrary identifier that should be globally unique amongst all the logs of all your applications (meaning it should probably be the unique name of the current application). You should set first to true for the first log in the operation, and last to true for the final log of the operation.

Also see, https://cloud.google.com/logging/docs/reference/v2/rest/v2/LogEntry#LogEntryOperation

For readable implementation of operation log, you can use following functions:

func (e *Event) OperationStart(id, producer string) *zerolog.Event
func (e *Event) OperationContinue(id, producer string) *zerolog.Event
func (e *Event) OperationEnd(id, producer string) *zerolog.Event

A concrete example of operation log is as follows:

logger.Info().OperationStart("foo", "bar").Msg("started")
logger.Debug().OperationContinue("foo", "bar").Msg("processing")
logger.Info().OperationEnd("foo", "bar").Msg("done")

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Event added in v0.0.2

type Event struct {
	*zerolog.Event
}

func (*Event) HTTP added in v0.0.2

func (e *Event) HTTP(req *HTTPPayload) *zerolog.Event

HTTP adds the httpRequest field to the *zerolog.Event context

func (*Event) Labels added in v0.1.0

func (e *Event) Labels(labels ...*LabelSource) *zerolog.Event

Labels takes LabelSource structs, filters the ones that have their key start with the string `labels.` and their value type set to string type. It then wraps those key/value pairs in a top-level `labels` namespace.

func (*Event) Operation added in v0.1.0

func (e *Event) Operation(id, producer string, first, last bool) *zerolog.Event

Operation adds the correct Cloud Logging "operation" field.

Additional information about a potentially long-running operation with which a log entry is associated.

func (*Event) OperationContinue added in v0.1.0

func (e *Event) OperationContinue(id, producer string) *zerolog.Event

OperationContinue is a function for logging `Operation`. It should be called for any non-start/end operation log.

func (*Event) OperationEnd added in v0.1.0

func (e *Event) OperationEnd(id, producer string) *zerolog.Event

OperationEnd is a function for logging `Operation`. It should be called for the last operation log.

func (*Event) OperationStart added in v0.1.0

func (e *Event) OperationStart(id, producer string) *zerolog.Event

OperationStart is a function for logging `Operation`. It should be called for the first operation log.

func (*Event) TraceContext added in v0.1.0

func (e *Event) TraceContext(trace string, spanId string, sampled bool, projectID string) *zerolog.Event

TraceContext adds the "trace", "span", "trace_sampled" fields to the *zerolog.Event context.

see: https://cloud.google.com/logging/docs/reference/v2/rest/v2/LogEntry

type GAELatency added in v0.0.3

type GAELatency struct {
	Seconds int64 `json:"seconds"`
	Nanos   int32 `json:"nanos"`
}

GAELatency is the Latency for GAE and Cloud Run.

type HTTPPayload added in v0.0.3

type HTTPPayload struct {
	RequestMethod                  string  `json:"requestMethod"`
	RequestURL                     string  `json:"requestUrl"`
	RequestSize                    string  `json:"requestSize"`
	Status                         int     `json:"status"`
	ResponseSize                   string  `json:"responseSize"`
	UserAgent                      string  `json:"userAgent"`
	RemoteIP                       string  `json:"remoteIp"`
	ServerIP                       string  `json:"serverIp"`
	Referer                        string  `json:"referer"`
	Latency                        Latency `json:"latency"`
	CacheLookup                    bool    `json:"cacheLookup"`
	CacheHit                       bool    `json:"cacheHit"`
	CacheValidatedWithOriginServer bool    `json:"cacheValidatedWithOriginServer"`
	CacheFillBytes                 string  `json:"cacheFillBytes"`
	Protocol                       string  `json:"protocol"`
}

HTTPPayload is the struct consists of http request related components. Details are in following link. https://cloud.google.com/logging/docs/reference/v2/rest/v2/LogEntry#HttpRequest

func NewHTTP

func NewHTTP(req *http.Request, res *http.Response) *HTTPPayload

NewHTTP returns a HTTPPayload struct.

type LabelSource added in v0.1.2

type LabelSource struct {
	Key   string
	Value string
}

func Label added in v0.1.0

func Label(key, value string) *LabelSource

Label adds an optional label to the payload in the format of `key: value`. Key of label must start with `labels.`

type Latency added in v0.0.3

type Latency interface{}

Latency is the interface of the request processing latency on the server. The format of the Latency should differ for GKE and for GAE, Cloud Run.

func MakeLatency added in v0.0.3

func MakeLatency(d time.Duration, isGKE bool) Latency

MakeLatency returns Latency based on passed time.Duration object.

type Logger

type Logger struct {
	*zerolog.Logger
}

func NewDevelopmentLogger added in v0.0.3

func NewDevelopmentLogger() *Logger

NewDevelopmentLogger returns a configured logger for development. It outputs debug level and above logs, and sampling is disabled.

func NewProductionLogger added in v0.0.3

func NewProductionLogger() *Logger

NewProductionLogger returns a configured logger for production. It outputs info level and above logs with sampling.

func (*Logger) Debug added in v0.0.2

func (l *Logger) Debug() *Event

func (*Logger) Err added in v0.0.2

func (l *Logger) Err(err error) *Event

func (*Logger) Error added in v0.0.2

func (l *Logger) Error() *Event

func (*Logger) Fatal added in v0.0.2

func (l *Logger) Fatal() *Event

func (*Logger) Info added in v0.0.2

func (l *Logger) Info() *Event

func (*Logger) Log added in v0.0.2

func (l *Logger) Log() *Event

func (Logger) Output added in v0.1.2

func (l Logger) Output(w io.Writer) Logger

func (*Logger) Panic added in v0.0.2

func (l *Logger) Panic() *Event

func (*Logger) Print added in v0.0.2

func (l *Logger) Print(v ...interface{})

func (*Logger) Printf added in v0.0.2

func (l *Logger) Printf(format string, v ...interface{})

func (*Logger) Trace added in v0.0.2

func (l *Logger) Trace() *Event

func (*Logger) Warn added in v0.0.2

func (l *Logger) Warn() *Event

func (*Logger) WithLevel added in v0.0.2

func (l *Logger) WithLevel(level zerolog.Level) *Event

func (Logger) Write added in v0.0.2

func (l Logger) Write(p []byte) (n int, err error)

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL