clog

package module
v0.0.0-...-02cb1ad Latest Latest
Warning

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

Go to latest
Published: Feb 8, 2024 License: Apache-2.0 Imports: 15 Imported by: 4

README

go.nownabe.dev/clog

PkgGoDev License Go Report Card codecov

clog is a structured logger optimized for Cloud Logging based on log/slog.

clog supports following special fields in JSON log entries:

  • severity
  • message
  • httpRequest
  • time
  • logging.googleapis.com/insertId
  • logging.googleapis.com/labels
  • logging.googleapis.com/operation
  • logging.googleapis.com/sourceLocation
  • logging.googleapis.com/spanId
  • logging.googleapis.com/trace
  • logging.googleapis.com/trace_sampled
  • logging.googleapis.com/stack_trace

See Cloud Logging documentation and Cloud Error Reporting documentation for more details.

Severity

clog uses Severity in the severity field instead of log levels. 8 severities are supported:

  • DEBUG
  • INFO
  • NOTICE
  • WARNING
  • ERROR
  • CRITICAL
  • ALERT
  • EMERGENCY

Usage

Each severity has three methods like Info, Infof, and InfoErr.

clog.Info(ctx, "simple logging with args", "key", "value")
// {"severity":"INFO", "message":"simple logging with args", "key":"value",
//  "time": "...", "logging.googleapis.com/sourceLocation": {...}}

clog.Noticef(ctx, "formatted message %s %s", "like", "fmt.Printf")
// {"severity":"NOTICE", "message":"formatted message like fmt.Printf",
//  "time": "...", "logging.googleapis.com/sourceLocation": {...}}

clog.CriticalErr(ctx, errors.New("critical error!!"), "key", "value")
// {"severity":"CRITICAL", "message":"critical error!!", "key":"value",
//  "time": "...", "logging.googleapis.com/sourceLocation": {...}}

// clog.ErrorErr has a shorthand clog.Err.
clog.Err(ctx, errors.New("error!"))
// {"severity":"ERROR", "message":"error!",
//  "time": "...", "logging.googleapis.com/sourceLocation": {...}}

See Examples for more details.

Documentation

Overview

Package clog is a structured logger optimized for Cloud Logging based on log/slog.

clog supports following special fields in JSON log entries:

  • severity
  • message
  • httpRequest
  • time
  • logging.googleapis.com/insertId
  • logging.googleapis.com/labels
  • logging.googleapis.com/operation
  • logging.googleapis.com/sourceLocation
  • logging.googleapis.com/spanId
  • logging.googleapis.com/trace
  • logging.googleapis.com/trace_sampled
  • logging.googleapis.com/stack_trace

See Cloud Logging documentation and Cloud Error Reporting documentation for more details.

Severity

clod uses Severity in the "severity" field instead of log levels. 8 severities are supported:

  • DEBUG
  • INFO
  • NOTICE
  • WARNING
  • ERROR
  • CRITICAL
  • ALERT
  • EMERGENCY

Usage

Each severity has three methods like Info, Infof, and InfoErr.

clog.Info(ctx, "simple logging with args", "key", "value")
// {"severity":"INFO", "message":"simple logging with args", "key":"value",
//  "time": "...", "logging.googleapis.com/sourceLocation": {...}}

clog.Noticef(ctx, "formatted message %s %s", "like", "fmt.Printf")
// {"severity":"NOTICE", "message":"formatted message like fmt.Printf",
//  "time": "...", "logging.googleapis.com/sourceLocation": {...}}

clog.CriticalErr(ctx, errors.New("critical error!!"), "key", "value")
// {"severity":"CRITICAL", "message":"critical error!!", "key":"value",
//  "time": "...", "logging.googleapis.com/sourceLocation": {...}}

// clog.ErrorErr has a shorthand clog.Err.
clog.Err(ctx, errors.New("error!"))
// {"severity":"ERROR", "message":"error!",
//  "time": "...", "logging.googleapis.com/sourceLocation": {...}}

See [Examples] for more details.

Example
package main

import (
	"context"
	"log/slog"
	"net/http"
	"net/http/httptest"
	"os"

	"go.opentelemetry.io/otel"
	"go.opentelemetry.io/otel/trace"

	"go.nownabe.dev/clog"
	"go.nownabe.dev/clog/errors"
)

type ctxUserIDKey struct{}

func InitializeClog() {
	// You can add labels to classify logs.
	appLabels := map[string]string{
		"app":     "myapp",
		"version": "1.0.0",
	}
	// Your Google Cloud Project ID.
	projectID := "my-gcp-project"

	// Custome handler to add user ID to logs.
	customHandler := func(next clog.HandleFunc) clog.HandleFunc {
		return func(ctx context.Context, r slog.Record) error {
			if ctx == nil {
				return next(ctx, r)
			}

			if userID, ok := ctx.Value(ctxUserIDKey{}).(string); ok {
				r.AddAttrs(slog.String("user_id", userID))
			}

			return next(ctx, r)
		}
	}

	// Create a custom logger.
	logger := clog.New(os.Stdout, clog.SeverityInfo, true,
		clog.WithLabels(appLabels),         // Add logger-level labels to classify logs.
		clog.WithTrace(projectID),          // Add trace and span ID to logs.
		clog.WithHandleFunc(customHandler), // Add custom log handler.
	)

	// You can add custome fields to logs.
	logger = logger.With("key1", "value1", "key2", "value2")

	clog.SetDefault(logger)
}

func RequestHandler(w http.ResponseWriter, r *http.Request) {
	ctx := r.Context()

	tracer := otel.Tracer("tracer")
	ctx, span := tracer.Start(ctx, "RequestHandler")
	defer span.End()

	ctx, removeLabel := clog.ContextWithLabel(ctx, "handler", "RequestHandler")
	defer removeLabel()

	clog.Info(ctx, "request received")
	/*
	   {
	     "time": "2023-09-18T20:46:03.448753224+09:00",
	     "severity": "INFO",
	     "message": "request received",
	     "logging.googleapis.com/sourceLocation": {
	       "file": "go.nownabe.dev/clog/example_test.go",
	       "line": "66",
	       "function": "main.RequestHandler"
	     },
	     "user_id": "user1",
	     "logging.googleapis.com/trace": "projects/my-gcp-project/traces/abcdabcdabcdabcdabcdabcdabcdabcd",
	     "logging.googleapis.com/spanId": "1234123412341234",
	     "logging.googleapis.com/trace_sampled": false,
	     "logging.googleapis.com/labels": {
	       "handler": "RequestHandler",
	       "app": "myapp",
	       "version": "1.0.0"
	     }
	   }
	*/
	defer clog.Info(ctx, "request processed")

	err := errors.New("something went wrong")
	if err != nil {
		clog.Err(ctx, err)
		/*
		   {
		     "time": "2023-09-18T21:14:02.980412394+09:00",
		     "severity": "ERROR",
		     "message": "something went wrong",
		     "stack_trace": "something went wrong\n\ngoroutine 0 [running]:\nmain.RequestHandler(...)\n\tgo.nownabe.dev/clog/example_test.go:90\nnet/http.HandlerFunc.ServeHTTP(...)\n\tnet/http/server.go:2136\nmain.Example(...)\n\tgo.nownabe.dev/clog/example_test.go:135\nmain.main(...)\n\tgo.nownabe.dev/clog/main.go:20\nruntime.main(...)\n\truntime/proc.go:267\n",
		     "logging.googleapis.com/sourceLocation": {
		       "file": "go.nownabe.dev/clog/example_test.go",
		       "line": "92",
		       "function": "main.RequestHandler"
		     },
		     "user_id": "user1",
		     "logging.googleapis.com/trace": "projects/my-gcp-project/traces/abcdabcdabcdabcdabcdabcdabcdabcd",
		     "logging.googleapis.com/spanId": "1234123412341234",
		     "logging.googleapis.com/trace_sampled": false,
		     "logging.googleapis.com/labels": {
		       "handler": "RequestHandler",
		       "app": "myapp",
		       "version": "1.0.0"
		     }
		   }
		*/
		http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
		return
		/*
		   {
		     "time": "2023-09-18T21:14:02.980418868+09:00",
		     "severity": "INFO",
		     "message": "request processed",
		     "logging.googleapis.com/sourceLocation": {
		       "file": "go.nownabe.dev/clog/example_test.go",
		       "line": "116",
		       "function": "main.RequestHandler"
		     },
		     "user_id": "user1",
		     "logging.googleapis.com/trace": "projects/my-gcp-project/traces/abcdabcdabcdabcdabcdabcdabcdabcd",
		     "logging.googleapis.com/spanId": "1234123412341234",
		     "logging.googleapis.com/trace_sampled": false,
		     "logging.googleapis.com/labels": {
		       "handler": "RequestHandler",
		       "app": "myapp",
		       "version": "1.0.0"
		     }
		   }
		*/
	}

	w.Write([]byte("Hello, World!"))
}

func main() {
	ctx := context.Background()
	ctx = withTraceSpan(ctx)
	ctx = context.WithValue(ctx, ctxUserIDKey{}, "user1")

	req, err := http.NewRequestWithContext(ctx, http.MethodGet, "", nil)
	if err != nil {
		panic(err)
	}
	InitializeClog()

	clog.Notice(ctx, "app started")
	/*
	   {
	     "time": "2023-09-18T20:46:03.448702881+09:00",
	     "severity": "NOTICE",
	     "message": "app started",
	     "logging.googleapis.com/sourceLocation": {
	       "file": "go.nownabe.dev/clog/example_test.go",
	       "line": "92",
	       "function": "main.Example"
	     },
	     "user_id": "user1",
	     "logging.googleapis.com/trace": "projects/my-gcp-project/traces/abcdabcdabcdabcdabcdabcdabcdabcd",
	     "logging.googleapis.com/spanId": "1234123412341234",
	     "logging.googleapis.com/trace_sampled": false,
	     "logging.googleapis.com/labels": {
	       "app": "myapp",
	       "version": "1.0.0"
	     }
	   }
	*/

	(http.HandlerFunc(RequestHandler)).ServeHTTP(httptest.NewRecorder(), req)

	clog.Notice(ctx, "app finished")
	/*
	   {
	     "time": "2023-09-18T21:14:02.980422814+09:00",
	     "severity": "NOTICE",
	     "message": "app finished",
	     "logging.googleapis.com/sourceLocation": {
	       "file": "go.nownabe.dev/clog/tmp/example.go",
	       "line": "178",
	       "function": "main.Example"
	     },
	     "user_id": "user1",
	     "logging.googleapis.com/trace": "projects/my-gcp-project/traces/abcdabcdabcdabcdabcdabcdabcdabcd",
	     "logging.googleapis.com/spanId": "1234123412341234",
	     "logging.googleapis.com/trace_sampled": false,
	     "logging.googleapis.com/labels": {
	       "app": "myapp",
	       "version": "1.0.0"
	     }
	   }
	*/
}

func withTraceSpan(ctx context.Context) context.Context {
	traceID, err := trace.TraceIDFromHex("abcdabcdabcdabcdabcdabcdabcdabcd")
	if err != nil {
		panic(err)
	}
	spanID, err := trace.SpanIDFromHex("1234123412341234")
	if err != nil {
		panic(err)
	}
	cfg := trace.SpanContextConfig{
		TraceID: traceID,
		SpanID:  spanID,
	}
	sc := trace.NewSpanContext(cfg)

	return trace.ContextWithSpanContext(ctx, sc)
}
Output:

Index

Examples

Constants

View Source
const (
	// SeverityDefault indicates that the log entry has no assigned severity level.
	SeverityDefault = Severity(0)
	// SeverityDebug indicates debug or trace information.
	SeverityDebug = Severity(100)
	// SeverityInfo indicates routine information, such as ongoing status or performance.
	SeverityInfo = Severity(200)
	// SeverityNotice indicates normal but significant events, such as start up, shut down, or a configuration change.
	SeverityNotice = Severity(300)
	// SeverityWarning indicates warning events that might cause problems.
	SeverityWarning = Severity(400)
	// SeverityError indicates error events that are likely to cause problems.
	SeverityError = Severity(500)
	// SeverityCritical indicates critical events that cause more severe problems or outages.
	SeverityCritical = Severity(600)
	// SeverityAlert indicates that a person must take an action immediately.
	SeverityAlert = Severity(700)
	// SeverityEmergency indicates that one or more systems are unusable.
	SeverityEmergency = Severity(800)
)

Variables

This section is empty.

Functions

func Alert

func Alert(ctx context.Context, msg string, args ...any)

Alert logs at SeverityAlert.

func AlertErr

func AlertErr(ctx context.Context, err error, args ...any)

AlertErr logs an error at SeverityAlert.

func Alertf

func Alertf(ctx context.Context, format string, a ...any)

Alertf logs formatted in the manner of fmt.Printf at SeverityAlert.

func ContextWithLabel

func ContextWithLabel(ctx context.Context, key string, value string) (context.Context, func())

ContextWithLabel returns a new context with the label that consists of given key and value. See https://cloud.google.com/logging/docs/reference/v2/rest/v2/LogEntry

func Critical

func Critical(ctx context.Context, msg string, args ...any)

Critical logs at SeverityCriticaDefault().

func CriticalErr

func CriticalErr(ctx context.Context, err error, args ...any)

CriticalErr logs an error at SeverityCriticaDefault().

func Criticalf

func Criticalf(ctx context.Context, format string, a ...any)

Criticalf logs formatted in the manner of fmt.Printf at SeverityCriticaDefault().

func Debug

func Debug(ctx context.Context, msg string, args ...any)

Debug logs at SeverityDebug.

func DebugErr

func DebugErr(ctx context.Context, err error, args ...any)

DebugErr logs an error at SeverityDebug.

func Debugf

func Debugf(ctx context.Context, format string, a ...any)

Debugf logs formatted in the manner of fmt.Printf at SeverityDebug.

func Emergency

func Emergency(ctx context.Context, msg string, args ...any)

Emergency logs at SeverityEmergency.

func EmergencyErr

func EmergencyErr(ctx context.Context, err error, args ...any)

EmergencyErr logs an error at SeverityEmergency.

func Emergencyf

func Emergencyf(ctx context.Context, format string, a ...any)

Emergencyf logs formatted in the manner of fmt.Printf at SeverityEmergency.

func Enabled

func Enabled(ctx context.Context, s Severity) bool

Enabled reports whether the Logger emits log records at the given context and leveDefault().

func Err

func Err(ctx context.Context, err error, args ...any)

Err is a shorthand for ErrorErr.

func Error

func Error(ctx context.Context, msg string, args ...any)

Error logs at SeverityError.

func ErrorErr

func ErrorErr(ctx context.Context, err error, args ...any)

ErrorErr logs an error at SeverityError.

func Errorf

func Errorf(ctx context.Context, format string, a ...any)

Errorf logs formatted in the manner of fmt.Printf at SeverityError.

func HTTPReq

func HTTPReq(ctx context.Context, req *HTTPRequest, args ...any)

HTTPReq emits a log with the given HTTPRequest. The value of message field will be like "GET /foo HTTP/1.1". If status >= 500, the log is at SeverityError. Otherwise, the log is at SeverityInfo.

Example
package main

import (
	"context"
	"time"

	"go.nownabe.dev/clog"
)

func main() {
	req := &clog.HTTPRequest{
		RequestMethod:                  "GET",
		RequestURL:                     "https://example.com/foo",
		RequestSize:                    123,
		Status:                         200,
		ResponseSize:                   456,
		UserAgent:                      "clog",
		RemoteIP:                       "203.0.113.1",
		ServerIP:                       "203.0.113.2",
		Referer:                        "https://example.com/referer",
		Latency:                        123*time.Second + 456*time.Nanosecond,
		CacheLookup:                    true,
		CacheHit:                       true,
		CacheValidatedWithOriginServer: true,
		CacheFillBytes:                 789,
		Protocol:                       "HTTP/1.1",
	}
	clog.HTTPReq(context.Background(), req, "GET /foo")
}
Output:

func Info

func Info(ctx context.Context, msg string, args ...any)

Info logs at SeverityInfo.

func InfoErr

func InfoErr(ctx context.Context, err error, args ...any)

InfoErr logs an error at SeverityInfo.

func Infof

func Infof(ctx context.Context, format string, a ...any)

Infof logs formatted in the manner of fmt.Printf at SeverityInfo.

func Log

func Log(ctx context.Context, s Severity, msg string, args ...any)

Log emits a log record with the current time and the given level and message.

func Notice

func Notice(ctx context.Context, msg string, args ...any)

Notice logs at SeverityNotice.

func NoticeErr

func NoticeErr(ctx context.Context, err error, args ...any)

NoticeErr logs an error at SeverityNotice.

func Noticef

func Noticef(ctx context.Context, format string, a ...any)

Noticef logs formatted in the manner of fmt.Printf at SeverityNotice.

func SetDefault

func SetDefault(l *Logger)

SetDefault makes l the default Logger.

func SetOptions

func SetOptions(opts ...Option)

SetOptions sets options to the default Logger.

func StartOperation

func StartOperation(ctx context.Context, s Severity, msg, id, producer string) (context.Context, func(msg string))

StartOperation returns a new context and a function to end the opration, starting the operation. See https://cloud.google.com/logging/docs/reference/v2/rest/v2/LogEntry#LogEntryOperation

Example
package main

import (
	"context"

	"go.nownabe.dev/clog"
)

func DoLongRunningOperation(ctx context.Context) {
	ctx, end := clog.StartOperation(ctx, clog.SeverityInfo, "long-running operation started", "long-running", "my-app")
	defer end("long-running operation ended")

	clog.Info(ctx, "long-running operation is running")
}

func main() {
	DoLongRunningOperation(context.Background())
	// Logs are like:
	// {"severity":"INFO", "message":"long-running operation started",
	//  "logging.googleapis.com/operation":{"id":"long-running","producer":"my-app","first":true}, ...}
	// {"severity":"INFO", "message":"long-running operation is running",
	//  "logging.googleapis.com/operation":{"id":"long-running","producer":"my-app"}, ...}
	// {"severity":"INFO", "message":"long-running operation ended",
	//  "logging.googleapis.com/operation":{"id":"long-running","producer":"my-app","last":true}, ...}
}
Output:

func Warning

func Warning(ctx context.Context, msg string, args ...any)

Warning logs at SeverityWarning.

func WarningErr

func WarningErr(ctx context.Context, err error, args ...any)

WarningErr logs an error at SeverityWarning.

func Warningf

func Warningf(ctx context.Context, format string, a ...any)

Warningf logs formatted in the manner of fmt.Printf at SeverityWarning.

Types

type HTTPRequest

type HTTPRequest struct {
	RequestMethod                  string
	RequestURL                     string
	RequestSize                    int64
	Status                         int
	ResponseSize                   int64
	UserAgent                      string
	RemoteIP                       string
	ServerIP                       string
	Referer                        string
	Latency                        time.Duration
	CacheLookup                    bool
	CacheHit                       bool
	CacheValidatedWithOriginServer bool
	CacheFillBytes                 int64
	Protocol                       string
}

HTTPRequest represents HttpRequest. See these links: https://cloud.google.com/logging/docs/reference/v2/rest/v2/LogEntry#HttpRequest, https://github.com/googleapis/googleapis/blob/master/google/logging/type/http_request.proto.

If HTTPRequest is empty, it will be omitted. cf. https://cs.opensource.google/go/go/+/refs/tags/go1.21.1:src/log/slog/record.go;l=118

func (*HTTPRequest) LogValue

func (r *HTTPRequest) LogValue() slog.Value

LogValue returns slog.Value.

type HandleFunc

type HandleFunc func(context.Context, slog.Record) error

type Logger

type Logger struct {
	// contains filtered or unexported fields
}

func Default

func Default() *Logger

Default returns the default Logger.

func New

func New(w io.Writer, s Severity, json bool, opts ...Option) *Logger

func With

func With(args ...any) *Logger

With returns a Logger that includes the given attributes in each output operation.

func WithInsertID

func WithInsertID(id string) *Logger

WithInsertID returns a Logger that includes the given insertId in each output operation. See https://cloud.google.com/logging/docs/reference/v2/rest/v2/LogEntry

func (*Logger) Alert

func (l *Logger) Alert(ctx context.Context, msg string, args ...any)

Alert logs at SeverityAlert.

func (*Logger) AlertErr

func (l *Logger) AlertErr(ctx context.Context, err error, args ...any)

AlertErr logs an error at SeverityAlert.

func (*Logger) Alertf

func (l *Logger) Alertf(ctx context.Context, format string, a ...any)

Alertf logs formatted in the manner of fmt.Printf at SeverityAlert.

func (*Logger) Critical

func (l *Logger) Critical(ctx context.Context, msg string, args ...any)

Critical logs at SeverityCritical.

func (*Logger) CriticalErr

func (l *Logger) CriticalErr(ctx context.Context, err error, args ...any)

CriticalErr logs an error at SeverityCritical.

func (*Logger) Criticalf

func (l *Logger) Criticalf(ctx context.Context, format string, a ...any)

Criticalf logs formatted in the manner of fmt.Printf at SeverityCritical.

func (*Logger) Debug

func (l *Logger) Debug(ctx context.Context, msg string, args ...any)

Debug logs at SeverityDebug.

func (*Logger) DebugErr

func (l *Logger) DebugErr(ctx context.Context, err error, args ...any)

DebugErr logs an error at SeverityDebug.

func (*Logger) Debugf

func (l *Logger) Debugf(ctx context.Context, format string, a ...any)

Debugf logs formatted in the manner of fmt.Printf at SeverityDebug.

func (*Logger) Emergency

func (l *Logger) Emergency(ctx context.Context, msg string, args ...any)

Emergency logs at SeverityEmergency.

func (*Logger) EmergencyErr

func (l *Logger) EmergencyErr(ctx context.Context, err error, args ...any)

EmergencyErr logs an error at SeverityEmergency.

func (*Logger) Emergencyf

func (l *Logger) Emergencyf(ctx context.Context, format string, a ...any)

Emergencyf logs formatted in the manner of fmt.Printf at SeverityEmergency.

func (*Logger) Enabled

func (l *Logger) Enabled(ctx context.Context, s Severity) bool

Enabled reports whether the Logger emits log records at the given context and level.

func (*Logger) Err

func (l *Logger) Err(ctx context.Context, err error, args ...any)

Err is a shorthand for ErrorErr.

func (*Logger) Error

func (l *Logger) Error(ctx context.Context, msg string, args ...any)

Error logs at SeverityError.

func (*Logger) ErrorErr

func (l *Logger) ErrorErr(ctx context.Context, err error, args ...any)

ErrorErr logs an error at SeverityError.

func (*Logger) Errorf

func (l *Logger) Errorf(ctx context.Context, format string, a ...any)

Errorf logs formatted in the manner of fmt.Printf at SeverityError.

func (*Logger) HTTPReq

func (l *Logger) HTTPReq(ctx context.Context, req *HTTPRequest, args ...any)

HTTPReq emits a log with the given HTTPRequest. The value of message field will be like "GET /foo HTTP/1.1". If status >= 500, the log is at SeverityError. Otherwise, the log is at SeverityInfo.

func (*Logger) Info

func (l *Logger) Info(ctx context.Context, msg string, args ...any)

Info logs at SeverityInfo.

func (*Logger) InfoErr

func (l *Logger) InfoErr(ctx context.Context, err error, args ...any)

InfoErr logs an error at SeverityInfo.

func (*Logger) Infof

func (l *Logger) Infof(ctx context.Context, format string, a ...any)

Infof logs formatted in the manner of fmt.Printf at SeverityInfo.

func (*Logger) Log

func (l *Logger) Log(ctx context.Context, s Severity, msg string, args ...any)

Log emits a log record with the current time and the given level and message.

func (*Logger) Notice

func (l *Logger) Notice(ctx context.Context, msg string, args ...any)

Notice logs at SeverityNotice.

func (*Logger) NoticeErr

func (l *Logger) NoticeErr(ctx context.Context, err error, args ...any)

NoticeErr logs an error at SeverityNotice.

func (*Logger) Noticef

func (l *Logger) Noticef(ctx context.Context, format string, a ...any)

Noticef logs formatted in the manner of fmt.Printf at SeverityNotice.

func (*Logger) StartOperation

func (l *Logger) StartOperation(
	ctx context.Context, s Severity, msg, id, producer string,
) (context.Context, func(msg string))

StartOperation returns a new context and a function to end the opration, starting the operation. See https://cloud.google.com/logging/docs/reference/v2/rest/v2/LogEntry#LogEntryOperation

func (*Logger) Warning

func (l *Logger) Warning(ctx context.Context, msg string, args ...any)

Warning logs at SeverityWarning.

func (*Logger) WarningErr

func (l *Logger) WarningErr(ctx context.Context, err error, args ...any)

WarningErr logs an error at SeverityWarning.

func (*Logger) Warningf

func (l *Logger) Warningf(ctx context.Context, format string, a ...any)

Warningf logs formatted in the manner of fmt.Printf at SeverityWarning.

func (*Logger) With

func (l *Logger) With(args ...any) *Logger

With returns a Logger that includes the given attributes in each output operation.

func (*Logger) WithInsertID

func (l *Logger) WithInsertID(id string) *Logger

WithInsertID returns a Logger that includes the given insertId in each output operation. See https://cloud.google.com/logging/docs/reference/v2/rest/v2/LogEntry

type Option

type Option interface {
	// contains filtered or unexported methods
}

func WithHandleFunc

func WithHandleFunc(f func(next HandleFunc) HandleFunc) Option

func WithLabels

func WithLabels(labels map[string]string) Option

WithLabels returns an Option that sets the default labels. See https://cloud.google.com/logging/docs/reference/v2/rest/v2/LogEntry

func WithTrace

func WithTrace(projectID string) Option

WithTrace returns an Option that sets the trace attributes to the log record.

type Severity

type Severity = slog.Level

Severity is the severity of the log event. These severities are defined in the Cloud Logging API v2 as an enum.

See following links. https://github.com/googleapis/googleapis/blob/master/google/logging/type/log_severity.proto https://cloud.google.com/logging/docs/reference/v2/rest/v2/LogEntry#LogSeverity

Though these packages provide predefined severity constants, we don't use them not to depend on external package just for it. https://pkg.go.dev/google.golang.org/genproto/googleapis/logging/type#LogSeverity https://pkg.go.dev/cloud.google.com/go/logging#Severity

Directories

Path Synopsis
Package errors provides errors with stack trace.
Package errors provides errors with stack trace.
internal

Jump to

Keyboard shortcuts

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