logger

package
v2.0.0-beta2 Latest Latest
Warning

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

Go to latest
Published: Sep 18, 2024 License: Apache-2.0 Imports: 13 Imported by: 0

Documentation

Overview

Package logger provides the internal logging solution for the MongoDB Go Driver.

Index

Constants

View Source
const (
	CommandFailed                    = "Command failed"
	CommandStarted                   = "Command started"
	CommandSucceeded                 = "Command succeeded"
	ConnectionPoolCreated            = "Connection pool created"
	ConnectionPoolReady              = "Connection pool ready"
	ConnectionPoolCleared            = "Connection pool cleared"
	ConnectionPoolClosed             = "Connection pool closed"
	ConnectionCreated                = "Connection created"
	ConnectionReady                  = "Connection ready"
	ConnectionClosed                 = "Connection closed"
	ConnectionCheckoutStarted        = "Connection checkout started"
	ConnectionCheckoutFailed         = "Connection checkout failed"
	ConnectionCheckedOut             = "Connection checked out"
	ConnectionCheckedIn              = "Connection checked in"
	ServerSelectionFailed            = "Server selection failed"
	ServerSelectionStarted           = "Server selection started"
	ServerSelectionSucceeded         = "Server selection succeeded"
	ServerSelectionWaiting           = "Waiting for suitable server to become available"
	TopologyClosed                   = "Stopped topology monitoring"
	TopologyDescriptionChanged       = "Topology description changed"
	TopologyOpening                  = "Starting topology monitoring"
	TopologyServerClosed             = "Stopped server monitoring"
	TopologyServerHeartbeatFailed    = "Server heartbeat failed"
	TopologyServerHeartbeatStarted   = "Server heartbeat started"
	TopologyServerHeartbeatSucceeded = "Server heartbeat succeeded"
	TopologyServerOpening            = "Starting server monitoring"
)
View Source
const (
	KeyAwaited             = "awaited"
	KeyCommand             = "command"
	KeyCommandName         = "commandName"
	KeyDatabaseName        = "databaseName"
	KeyDriverConnectionID  = "driverConnectionId"
	KeyDurationMS          = "durationMS"
	KeyError               = "error"
	KeyFailure             = "failure"
	KeyMaxConnecting       = "maxConnecting"
	KeyMaxIdleTimeMS       = "maxIdleTimeMS"
	KeyMaxPoolSize         = "maxPoolSize"
	KeyMessage             = "message"
	KeyMinPoolSize         = "minPoolSize"
	KeyNewDescription      = "newDescription"
	KeyOperation           = "operation"
	KeyOperationID         = "operationId"
	KeyPreviousDescription = "previousDescription"
	KeyRemainingTimeMS     = "remainingTimeMS"
	KeyReason              = "reason"
	KeyReply               = "reply"
	KeyRequestID           = "requestId"
	KeySelector            = "selector"
	KeyServerConnectionID  = "serverConnectionId"
	KeyServerHost          = "serverHost"
	KeyServerPort          = "serverPort"
	KeyServiceID           = "serviceId"
	KeyTimestamp           = "timestamp"
	KeyTopologyDescription = "topologyDescription"
	KeyTopologyID          = "topologyId"
)
View Source
const (
	ReasonConnClosedStale              = "Connection became stale because the pool was cleared"
	ReasonConnClosedIdle               = "Connection has been available but unused for longer than the configured max idle time"
	ReasonConnClosedError              = "An error occurred while using the connection"
	ReasonConnClosedPoolClosed         = "Connection pool was closed"
	ReasonConnCheckoutFailedTimout     = "Wait queue timeout elapsed without a connection becoming available"
	ReasonConnCheckoutFailedError      = "An error occurred while trying to establish a new connection"
	ReasonConnCheckoutFailedPoolClosed = "Connection pool was closed"
)
View Source
const DefaultMaxDocumentLength = 1000

DefaultMaxDocumentLength is the default maximum number of bytes that can be logged for a stringified BSON document.

View Source
const DiffToInfo = 1

DiffToInfo is the number of levels in the Go Driver that come before the "Info" level. This should ensure that "Info" is the 0th level passed to the sink.

View Source
const TruncationSuffix = "..."

TruncationSuffix are trailing ellipsis "..." appended to a message to indicate to the user that truncation occurred. This constant does not count toward the max document length.

Variables

View Source
var LevelLiteralMap = map[string]Level{
	// contains filtered or unexported fields
}

Functions

func EnvHasComponentVariables

func EnvHasComponentVariables() bool

EnvHasComponentVariables returns true if the environment contains any of the component environment variables.

func FormatDocument

func FormatDocument(msg bson.Raw, width uint) string

FormatDocument formats a BSON document or RawValue for logging. The document is truncated to the given width.

func FormatString

func FormatString(str string, width uint) string

FormatString formats a String for logging. The string is truncated to the given width.

func OperationID

func OperationID(ctx context.Context) (int32, bool)

OperationID returns the operation ID from the context.

func OperationName

func OperationName(ctx context.Context) (string, bool)

OperationName returns the operation name from the context.

func WithOperationID

func WithOperationID(ctx context.Context, operationID int32) context.Context

WithOperationID adds the operation ID to the context.

func WithOperationName

func WithOperationName(ctx context.Context, operation string) context.Context

WithOperationName adds the operation name to the context.

Types

type Command

type Command struct {
	DriverConnectionID int64          // Driver's ID for the connection
	Name               string         // Command name
	DatabaseName       string         // Database name
	Message            string         // Message associated with the command
	OperationID        int32          // Driver-generated operation ID
	RequestID          int64          // Driver-generated request ID
	ServerConnectionID *int64         // Server's ID for the connection used for the command
	ServerHost         string         // Hostname or IP address for the server
	ServerPort         string         // Port for the server
	ServiceID          *bson.ObjectID // ID for the command  in load balancer mode
}

Command is a struct defining common fields that must be included in all commands.

type Component

type Component int

Component is an enumeration representing the "components" which can be logged against. A LogLevel can be configured on a per-component basis.

const (
	// ComponentAll enables logging for all components.
	ComponentAll Component = iota

	// ComponentCommand enables command monitor logging.
	ComponentCommand

	// ComponentTopology enables topology logging.
	ComponentTopology

	// ComponentServerSelection enables server selection logging.
	ComponentServerSelection

	// ComponentConnection enables connection services logging.
	ComponentConnection
)

type Connection

type Connection struct {
	Message    string // Message associated with the connection
	ServerHost string // Hostname or IP address for the server
	ServerPort string // Port for the server
}

Connection contains data that all connection log messages MUST contain.

type IOSink

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

IOSink writes a JSON-encoded message to the io.Writer.

func NewIOSink

func NewIOSink(out io.Writer) *IOSink

NewIOSink will create an IOSink object that writes JSON messages to the provided io.Writer.

func (*IOSink) Error

func (sink *IOSink) Error(err error, msg string, kv ...interface{})

Error will write a JSON-encoded error message to the io.Writer.

func (*IOSink) Info

func (sink *IOSink) Info(_ int, msg string, keysAndValues ...interface{})

Info will write a JSON-encoded message to the io.Writer.

type KeyValues

type KeyValues []interface{}

KeyValues is a list of key-value pairs.

func SerializeCommand

func SerializeCommand(cmd Command, extraKeysAndValues ...interface{}) KeyValues

SerializeCommand takes a command and a variable number of key-value pairs and returns a slice of interface{} that can be passed to the logger for structured logging.

func SerializeConnection

func SerializeConnection(conn Connection, extraKeysAndValues ...interface{}) KeyValues

SerializeConnection serializes a Connection message into a slice of keys and values that can be passed to a logger.

func SerializeServer

func SerializeServer(srv Server, extraKV ...interface{}) KeyValues

SerializeServer serializes a Server message into a slice of keys and values that can be passed to a logger.

func SerializeServerSelection

func SerializeServerSelection(srvSelection ServerSelection, extraKV ...interface{}) KeyValues

SerializeServerSelection serializes a Topology message into a slice of keys and values that can be passed to a logger.

func SerializeTopology

func SerializeTopology(topo Topology, extraKV ...interface{}) KeyValues

SerializeTopology serializes a Topology message into a slice of keys and values that can be passed to a logger.

func (*KeyValues) Add

func (kvs *KeyValues) Add(key string, value interface{})

Add adds a key-value pair to an instance of a KeyValues list.

type Level

type Level int

Level is an enumeration representing the log severity levels supported by the driver. The order of the logging levels is important. The driver expects that a user will likely use the "logr" package to create a LogSink, which defaults InfoLevel as 0. Any additions to the Level enumeration before the InfoLevel will need to also update the "diffToInfo" constant.

const (
	// LevelOff suppresses logging.
	LevelOff Level = iota

	// LevelInfo enables logging of informational messages. These logs are
	// high-level information about normal driver behavior.
	LevelInfo

	// LevelDebug enables logging of debug messages. These logs can be
	// voluminous and are intended for detailed information that may be
	// helpful when debugging an application.
	LevelDebug
)

func ParseLevel

func ParseLevel(str string) Level

ParseLevel will check if the given string is a valid environment variable for a logging severity level. If it is, then it will return the associated driver's Level. The default Level is “LevelOff”.

type LogSink

type LogSink interface {
	// Info logs a non-error message with the given key/value pairs. The
	// level argument is provided for optional logging.
	Info(level int, msg string, keysAndValues ...interface{})

	// Error logs an error, with the given message and key/value pairs.
	Error(err error, msg string, keysAndValues ...interface{})
}

LogSink represents a logging implementation, this interface should be 1-1 with the exported "LogSink" interface in the mongo/options package.

type Logger

type Logger struct {
	ComponentLevels   map[Component]Level // Log levels for each component.
	Sink              LogSink             // LogSink for log printing.
	MaxDocumentLength uint                // Command truncation width.
	// contains filtered or unexported fields
}

Logger represents the configuration for the internal logger.

func New

func New(sink LogSink, maxDocLen uint, compLevels map[Component]Level) (*Logger, error)

New will construct a new logger. If any of the given options are the zero-value of the argument type, then the constructor will attempt to source the data from the environment. If the environment has not been set, then the constructor will the respective default values.

func (*Logger) Close

func (logger *Logger) Close() error

Close will close the logger's log file, if it exists.

func (*Logger) Error

func (logger *Logger) Error(err error, msg string, keysAndValues ...interface{})

Error logs an error, with the given message and key/value pairs. It functions similarly to Print, but may have unique behavior, and should be preferred for logging errors.

func (*Logger) LevelComponentEnabled

func (logger *Logger) LevelComponentEnabled(level Level, component Component) bool

LevelComponentEnabled will return true if the given LogLevel is enabled for the given LogComponent. If the ComponentLevels on the logger are enabled for "ComponentAll", then this function will return true for any level bound by the level assigned to "ComponentAll".

If the level is not enabled (i.e. LevelOff), then false is returned. This is to avoid false positives, such as returning "true" for a component that is not enabled. For example, without this condition, an empty LevelComponent would be considered "enabled" for "LevelOff".

func (*Logger) Print

func (logger *Logger) Print(level Level, component Component, msg string, keysAndValues ...interface{})

Print will synchronously print the given message to the configured LogSink. If the LogSink is nil, then this method will do nothing. Future work could be done to make this method asynchronous, see buffer management in libraries such as log4j.

It's worth noting that many structured logs defined by DBX-wide specifications include a "message" field, which is often shared with the message arguments passed to this print function. The "Info" method used by this function is implemented based on the go-logr/logr LogSink interface, which is why "Print" has a message parameter. Any duplication in code is intentional to adhere to the logr pattern.

type Server

type Server struct {
	DriverConnectionID int64         // Driver's ID for the connection
	TopologyID         bson.ObjectID // Driver's unique ID for this topology
	Message            string        // Message associated with the topology
	ServerConnectionID *int64        // Server's ID for the connection
	ServerHost         string        // Hostname or IP address for the server
	ServerPort         string        // Port for the server
}

Server contains data that all server messages MAY contain.

type ServerSelection

type ServerSelection struct {
	Selector            string
	OperationID         *int32
	Operation           string
	TopologyDescription string
}

ServerSelection contains data that all server selection messages MUST contain.

type Topology

type Topology struct {
	ID      bson.ObjectID // Driver's unique ID for this topology
	Message string        // Message associated with the topology
}

Topology contains data that all topology messages MAY contain.

Jump to

Keyboard shortcuts

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