Documentation ¶
Overview ¶
Package logger provides the internal logging solution for the MongoDB Go Driver.
Index ¶
- Constants
- Variables
- func EnvHasComponentVariables() bool
- func FormatDocument(msg bson.Raw, width uint) string
- func FormatString(str string, width uint) string
- func OperationID(ctx context.Context) (int32, bool)
- func OperationName(ctx context.Context) (string, bool)
- func WithOperationID(ctx context.Context, operationID int32) context.Context
- func WithOperationName(ctx context.Context, operation string) context.Context
- type Command
- type Component
- type Connection
- type IOSink
- type KeyValues
- func SerializeCommand(cmd Command, extraKeysAndValues ...interface{}) KeyValues
- func SerializeConnection(conn Connection, extraKeysAndValues ...interface{}) KeyValues
- func SerializeServer(srv Server, extraKV ...interface{}) KeyValues
- func SerializeServerSelection(srvSelection ServerSelection, extraKV ...interface{}) KeyValues
- func SerializeTopology(topo Topology, extraKV ...interface{}) KeyValues
- type Level
- type LogSink
- type Logger
- func (logger *Logger) Close() error
- func (logger *Logger) Error(err error, msg string, keysAndValues ...interface{})
- func (logger *Logger) LevelComponentEnabled(level Level, component Component) bool
- func (logger *Logger) Print(level Level, component Component, msg string, keysAndValues ...interface{})
- type Server
- type ServerSelection
- type Topology
Constants ¶
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" )
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" )
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" )
const DefaultMaxDocumentLength = 1000
DefaultMaxDocumentLength is the default maximum number of bytes that can be logged for a stringified BSON document.
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.
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 ¶
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 ¶
FormatDocument formats a BSON document or RawValue for logging. The document is truncated to the given width.
func FormatString ¶
FormatString formats a String for logging. The string is truncated to the given width.
func OperationID ¶
OperationID returns the operation ID from the context.
func OperationName ¶
OperationName returns the operation name from the context.
func WithOperationID ¶
WithOperationID adds the operation ID 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 ¶
NewIOSink will create an IOSink object that writes JSON messages to the provided io.Writer.
type KeyValues ¶
type KeyValues []interface{}
KeyValues is a list of key-value pairs.
func SerializeCommand ¶
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 ¶
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 ¶
SerializeTopology serializes a Topology message into a slice of keys and values that can be passed to a logger.
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 ¶
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 ¶
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) Error ¶
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 ¶
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.