1
0
mirror of https://github.com/golang/go synced 2024-09-29 02:14:29 -06:00

log: add available godoc link

Change-Id: I80f1377631163cc5843379c36ca10b82fccd5709
Reviewed-on: https://go-review.googlesource.com/c/go/+/535086
Reviewed-by: David Chase <drchase@google.com>
Reviewed-by: Jonathan Amsterdam <jba@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
This commit is contained in:
cui fliter 2023-10-14 20:11:42 +08:00 committed by Jonathan Amsterdam
parent f9c54f9cd4
commit f09db2bb93
11 changed files with 114 additions and 114 deletions

View File

@ -2,7 +2,7 @@
// Use of this source code is governed by a BSD-style // Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
// Package log implements a simple logging package. It defines a type, Logger, // Package log implements a simple logging package. It defines a type, [Logger],
// with methods for formatting output. It also has a predefined 'standard' // with methods for formatting output. It also has a predefined 'standard'
// Logger accessible through helper functions Print[f|ln], Fatal[f|ln], and // Logger accessible through helper functions Print[f|ln], Fatal[f|ln], and
// Panic[f|ln], which are easier to use than creating a Logger manually. // Panic[f|ln], which are easier to use than creating a Logger manually.
@ -10,7 +10,7 @@
// of each logged message. // of each logged message.
// Every log message is output on a separate line: if the message being // Every log message is output on a separate line: if the message being
// printed does not end in a newline, the logger will add one. // printed does not end in a newline, the logger will add one.
// The Fatal functions call os.Exit(1) after writing the log message. // The Fatal functions call [os.Exit](1) after writing the log message.
// The Panic functions call panic after writing the log message. // The Panic functions call panic after writing the log message.
package log package log
@ -25,7 +25,7 @@ import (
"time" "time"
) )
// These flags define which text to prefix to each log entry generated by the Logger. // These flags define which text to prefix to each log entry generated by the [Logger].
// Bits are or'ed together to control what's printed. // Bits are or'ed together to control what's printed.
// With the exception of the Lmsgprefix flag, there is no // With the exception of the Lmsgprefix flag, there is no
// control over the order they appear (the order listed here) // control over the order they appear (the order listed here)
@ -51,7 +51,7 @@ const (
) )
// A Logger represents an active logging object that generates lines of // A Logger represents an active logging object that generates lines of
// output to an io.Writer. Each logging operation makes a single call to // output to an [io.Writer]. Each logging operation makes a single call to
// the Writer's Write method. A Logger can be used simultaneously from // the Writer's Write method. A Logger can be used simultaneously from
// multiple goroutines; it guarantees to serialize access to the Writer. // multiple goroutines; it guarantees to serialize access to the Writer.
type Logger struct { type Logger struct {
@ -63,10 +63,10 @@ type Logger struct {
isDiscard atomic.Bool isDiscard atomic.Bool
} }
// New creates a new Logger. The out variable sets the // New creates a new [Logger]. The out variable sets the
// destination to which log data will be written. // destination to which log data will be written.
// The prefix appears at the beginning of each generated log line, or // The prefix appears at the beginning of each generated log line, or
// after the log header if the Lmsgprefix flag is provided. // after the log header if the [Lmsgprefix] flag is provided.
// The flag argument defines the logging properties. // The flag argument defines the logging properties.
func New(out io.Writer, prefix string, flag int) *Logger { func New(out io.Writer, prefix string, flag int) *Logger {
l := new(Logger) l := new(Logger)
@ -255,7 +255,7 @@ func init() {
} }
// Print calls l.Output to print to the logger. // Print calls l.Output to print to the logger.
// Arguments are handled in the manner of fmt.Print. // Arguments are handled in the manner of [fmt.Print].
func (l *Logger) Print(v ...any) { func (l *Logger) Print(v ...any) {
l.output(0, 2, func(b []byte) []byte { l.output(0, 2, func(b []byte) []byte {
return fmt.Append(b, v...) return fmt.Append(b, v...)
@ -263,7 +263,7 @@ func (l *Logger) Print(v ...any) {
} }
// Printf calls l.Output to print to the logger. // Printf calls l.Output to print to the logger.
// Arguments are handled in the manner of fmt.Printf. // Arguments are handled in the manner of [fmt.Printf].
func (l *Logger) Printf(format string, v ...any) { func (l *Logger) Printf(format string, v ...any) {
l.output(0, 2, func(b []byte) []byte { l.output(0, 2, func(b []byte) []byte {
return fmt.Appendf(b, format, v...) return fmt.Appendf(b, format, v...)
@ -271,26 +271,26 @@ func (l *Logger) Printf(format string, v ...any) {
} }
// Println calls l.Output to print to the logger. // Println calls l.Output to print to the logger.
// Arguments are handled in the manner of fmt.Println. // Arguments are handled in the manner of [fmt.Println].
func (l *Logger) Println(v ...any) { func (l *Logger) Println(v ...any) {
l.output(0, 2, func(b []byte) []byte { l.output(0, 2, func(b []byte) []byte {
return fmt.Appendln(b, v...) return fmt.Appendln(b, v...)
}) })
} }
// Fatal is equivalent to l.Print() followed by a call to os.Exit(1). // Fatal is equivalent to l.Print() followed by a call to [os.Exit](1).
func (l *Logger) Fatal(v ...any) { func (l *Logger) Fatal(v ...any) {
l.Output(2, fmt.Sprint(v...)) l.Output(2, fmt.Sprint(v...))
os.Exit(1) os.Exit(1)
} }
// Fatalf is equivalent to l.Printf() followed by a call to os.Exit(1). // Fatalf is equivalent to l.Printf() followed by a call to [os.Exit](1).
func (l *Logger) Fatalf(format string, v ...any) { func (l *Logger) Fatalf(format string, v ...any) {
l.Output(2, fmt.Sprintf(format, v...)) l.Output(2, fmt.Sprintf(format, v...))
os.Exit(1) os.Exit(1)
} }
// Fatalln is equivalent to l.Println() followed by a call to os.Exit(1). // Fatalln is equivalent to l.Println() followed by a call to [os.Exit](1).
func (l *Logger) Fatalln(v ...any) { func (l *Logger) Fatalln(v ...any) {
l.Output(2, fmt.Sprintln(v...)) l.Output(2, fmt.Sprintln(v...))
os.Exit(1) os.Exit(1)
@ -318,13 +318,13 @@ func (l *Logger) Panicln(v ...any) {
} }
// Flags returns the output flags for the logger. // Flags returns the output flags for the logger.
// The flag bits are Ldate, Ltime, and so on. // The flag bits are [Ldate], [Ltime], and so on.
func (l *Logger) Flags() int { func (l *Logger) Flags() int {
return int(l.flag.Load()) return int(l.flag.Load())
} }
// SetFlags sets the output flags for the logger. // SetFlags sets the output flags for the logger.
// The flag bits are Ldate, Ltime, and so on. // The flag bits are [Ldate], [Ltime], and so on.
func (l *Logger) SetFlags(flag int) { func (l *Logger) SetFlags(flag int) {
l.flag.Store(int32(flag)) l.flag.Store(int32(flag))
} }
@ -355,13 +355,13 @@ func SetOutput(w io.Writer) {
} }
// Flags returns the output flags for the standard logger. // Flags returns the output flags for the standard logger.
// The flag bits are Ldate, Ltime, and so on. // The flag bits are [Ldate], [Ltime], and so on.
func Flags() int { func Flags() int {
return std.Flags() return std.Flags()
} }
// SetFlags sets the output flags for the standard logger. // SetFlags sets the output flags for the standard logger.
// The flag bits are Ldate, Ltime, and so on. // The flag bits are [Ldate], [Ltime], and so on.
func SetFlags(flag int) { func SetFlags(flag int) {
std.SetFlags(flag) std.SetFlags(flag)
} }
@ -384,7 +384,7 @@ func Writer() io.Writer {
// These functions write to the standard logger. // These functions write to the standard logger.
// Print calls Output to print to the standard logger. // Print calls Output to print to the standard logger.
// Arguments are handled in the manner of fmt.Print. // Arguments are handled in the manner of [fmt.Print].
func Print(v ...any) { func Print(v ...any) {
std.output(0, 2, func(b []byte) []byte { std.output(0, 2, func(b []byte) []byte {
return fmt.Append(b, v...) return fmt.Append(b, v...)
@ -392,7 +392,7 @@ func Print(v ...any) {
} }
// Printf calls Output to print to the standard logger. // Printf calls Output to print to the standard logger.
// Arguments are handled in the manner of fmt.Printf. // Arguments are handled in the manner of [fmt.Printf].
func Printf(format string, v ...any) { func Printf(format string, v ...any) {
std.output(0, 2, func(b []byte) []byte { std.output(0, 2, func(b []byte) []byte {
return fmt.Appendf(b, format, v...) return fmt.Appendf(b, format, v...)
@ -400,46 +400,46 @@ func Printf(format string, v ...any) {
} }
// Println calls Output to print to the standard logger. // Println calls Output to print to the standard logger.
// Arguments are handled in the manner of fmt.Println. // Arguments are handled in the manner of [fmt.Println].
func Println(v ...any) { func Println(v ...any) {
std.output(0, 2, func(b []byte) []byte { std.output(0, 2, func(b []byte) []byte {
return fmt.Appendln(b, v...) return fmt.Appendln(b, v...)
}) })
} }
// Fatal is equivalent to Print() followed by a call to os.Exit(1). // Fatal is equivalent to [Print] followed by a call to [os.Exit](1).
func Fatal(v ...any) { func Fatal(v ...any) {
std.Output(2, fmt.Sprint(v...)) std.Output(2, fmt.Sprint(v...))
os.Exit(1) os.Exit(1)
} }
// Fatalf is equivalent to Printf() followed by a call to os.Exit(1). // Fatalf is equivalent to [Printf] followed by a call to [os.Exit](1).
func Fatalf(format string, v ...any) { func Fatalf(format string, v ...any) {
std.Output(2, fmt.Sprintf(format, v...)) std.Output(2, fmt.Sprintf(format, v...))
os.Exit(1) os.Exit(1)
} }
// Fatalln is equivalent to Println() followed by a call to os.Exit(1). // Fatalln is equivalent to [Println] followed by a call to [os.Exit](1).
func Fatalln(v ...any) { func Fatalln(v ...any) {
std.Output(2, fmt.Sprintln(v...)) std.Output(2, fmt.Sprintln(v...))
os.Exit(1) os.Exit(1)
} }
// Panic is equivalent to Print() followed by a call to panic(). // Panic is equivalent to [Print] followed by a call to panic().
func Panic(v ...any) { func Panic(v ...any) {
s := fmt.Sprint(v...) s := fmt.Sprint(v...)
std.Output(2, s) std.Output(2, s)
panic(s) panic(s)
} }
// Panicf is equivalent to Printf() followed by a call to panic(). // Panicf is equivalent to [Printf] followed by a call to panic().
func Panicf(format string, v ...any) { func Panicf(format string, v ...any) {
s := fmt.Sprintf(format, v...) s := fmt.Sprintf(format, v...)
std.Output(2, s) std.Output(2, s)
panic(s) panic(s)
} }
// Panicln is equivalent to Println() followed by a call to panic(). // Panicln is equivalent to [Println] followed by a call to panic().
func Panicln(v ...any) { func Panicln(v ...any) {
s := fmt.Sprintln(v...) s := fmt.Sprintln(v...)
std.Output(2, s) std.Output(2, s)
@ -451,7 +451,7 @@ func Panicln(v ...any) {
// Logger. A newline is appended if the last character of s is not // Logger. A newline is appended if the last character of s is not
// already a newline. Calldepth is the count of the number of // already a newline. Calldepth is the count of the number of
// frames to skip when computing the file name and line number // frames to skip when computing the file name and line number
// if Llongfile or Lshortfile is set; a value of 1 will print the details // if [Llongfile] or [Lshortfile] is set; a value of 1 will print the details
// for the caller of Output. // for the caller of Output.
func Output(calldepth int, s string) error { func Output(calldepth int, s string) error {
return std.Output(calldepth+1, s) // +1 for this frame. return std.Output(calldepth+1, s) // +1 for this frame.

View File

@ -46,18 +46,18 @@ func Bool(key string, v bool) Attr {
return Attr{key, BoolValue(v)} return Attr{key, BoolValue(v)}
} }
// Time returns an Attr for a time.Time. // Time returns an Attr for a [time.Time].
// It discards the monotonic portion. // It discards the monotonic portion.
func Time(key string, v time.Time) Attr { func Time(key string, v time.Time) Attr {
return Attr{key, TimeValue(v)} return Attr{key, TimeValue(v)}
} }
// Duration returns an Attr for a time.Duration. // Duration returns an Attr for a [time.Duration].
func Duration(key string, v time.Duration) Attr { func Duration(key string, v time.Duration) Attr {
return Attr{key, DurationValue(v)} return Attr{key, DurationValue(v)}
} }
// Group returns an Attr for a Group Value. // Group returns an Attr for a Group [Value].
// The first argument is the key; the remaining arguments // The first argument is the key; the remaining arguments
// are converted to Attrs as in [Logger.Log]. // are converted to Attrs as in [Logger.Log].
// //

View File

@ -222,7 +222,7 @@ details.
A LogValue method may return a Value that itself implements [LogValuer]. The [Value.Resolve] A LogValue method may return a Value that itself implements [LogValuer]. The [Value.Resolve]
method handles these cases carefully, avoiding infinite loops and unbounded recursion. method handles these cases carefully, avoiding infinite loops and unbounded recursion.
Handler authors and others may wish to use Value.Resolve instead of calling LogValue directly. Handler authors and others may wish to use [Value.Resolve] instead of calling LogValue directly.
# Wrapping output methods # Wrapping output methods

View File

@ -125,7 +125,7 @@ func (h *defaultHandler) WithGroup(name string) Handler {
return &defaultHandler{h.ch.withGroup(name), h.output} return &defaultHandler{h.ch.withGroup(name), h.output}
} }
// HandlerOptions are options for a TextHandler or JSONHandler. // HandlerOptions are options for a [TextHandler] or [JSONHandler].
// A zero HandlerOptions consists entirely of default values. // A zero HandlerOptions consists entirely of default values.
type HandlerOptions struct { type HandlerOptions struct {
// AddSource causes the handler to compute the source code position // AddSource causes the handler to compute the source code position

View File

@ -18,13 +18,13 @@ import (
"unicode/utf8" "unicode/utf8"
) )
// JSONHandler is a Handler that writes Records to an io.Writer as // JSONHandler is a [Handler] that writes Records to an [io.Writer] as
// line-delimited JSON objects. // line-delimited JSON objects.
type JSONHandler struct { type JSONHandler struct {
*commonHandler *commonHandler
} }
// NewJSONHandler creates a JSONHandler that writes to w, // NewJSONHandler creates a [JSONHandler] that writes to w,
// using the given options. // using the given options.
// If opts is nil, the default options are used. // If opts is nil, the default options are used.
func NewJSONHandler(w io.Writer, opts *HandlerOptions) *JSONHandler { func NewJSONHandler(w io.Writer, opts *HandlerOptions) *JSONHandler {
@ -47,7 +47,7 @@ func (h *JSONHandler) Enabled(_ context.Context, level Level) bool {
return h.commonHandler.enabled(level) return h.commonHandler.enabled(level)
} }
// WithAttrs returns a new JSONHandler whose attributes consists // WithAttrs returns a new [JSONHandler] whose attributes consists
// of h's attributes followed by attrs. // of h's attributes followed by attrs.
func (h *JSONHandler) WithAttrs(attrs []Attr) Handler { func (h *JSONHandler) WithAttrs(attrs []Attr) Handler {
return &JSONHandler{commonHandler: h.commonHandler.withAttrs(attrs)} return &JSONHandler{commonHandler: h.commonHandler.withAttrs(attrs)}
@ -57,7 +57,7 @@ func (h *JSONHandler) WithGroup(name string) Handler {
return &JSONHandler{commonHandler: h.commonHandler.withGroup(name)} return &JSONHandler{commonHandler: h.commonHandler.withGroup(name)}
} }
// Handle formats its argument Record as a JSON object on a single line. // Handle formats its argument [Record] as a JSON object on a single line.
// //
// If the Record's time is zero, the time is omitted. // If the Record's time is zero, the time is omitted.
// Otherwise, the key is "time" // Otherwise, the key is "time"
@ -81,7 +81,7 @@ func (h *JSONHandler) WithGroup(name string) Handler {
// First, an Attr whose Value is of type error is formatted as a string, by // First, an Attr whose Value is of type error is formatted as a string, by
// calling its Error method. Only errors in Attrs receive this special treatment, // calling its Error method. Only errors in Attrs receive this special treatment,
// not errors embedded in structs, slices, maps or other data structures that // not errors embedded in structs, slices, maps or other data structures that
// are processed by the encoding/json package. // are processed by the [encoding/json] package.
// //
// Second, an encoding failure does not cause Handle to return an error. // Second, an encoding failure does not cause Handle to return an error.
// Instead, the error message is formatted as a string. // Instead, the error message is formatted as a string.

View File

@ -146,14 +146,14 @@ func (l *Level) parse(s string) (err error) {
} }
// Level returns the receiver. // Level returns the receiver.
// It implements Leveler. // It implements [Leveler].
func (l Level) Level() Level { return l } func (l Level) Level() Level { return l }
// A LevelVar is a Level variable, to allow a Handler level to change // A LevelVar is a [Level] variable, to allow a [Handler] level to change
// dynamically. // dynamically.
// It implements Leveler as well as a Set method, // It implements [Leveler] as well as a Set method,
// and it is safe for use by multiple goroutines. // and it is safe for use by multiple goroutines.
// The zero LevelVar corresponds to LevelInfo. // The zero LevelVar corresponds to [LevelInfo].
type LevelVar struct { type LevelVar struct {
val atomic.Int64 val atomic.Int64
} }
@ -189,12 +189,12 @@ func (v *LevelVar) UnmarshalText(data []byte) error {
return nil return nil
} }
// A Leveler provides a Level value. // A Leveler provides a [Level] value.
// //
// As Level itself implements Leveler, clients typically supply // As Level itself implements Leveler, clients typically supply
// a Level value wherever a Leveler is needed, such as in HandlerOptions. // a Level value wherever a Leveler is needed, such as in [HandlerOptions].
// Clients who need to vary the level dynamically can provide a more complex // Clients who need to vary the level dynamically can provide a more complex
// Leveler implementation such as *LevelVar. // Leveler implementation such as *[LevelVar].
type Leveler interface { type Leveler interface {
Level() Level Level() Level
} }

View File

@ -20,12 +20,12 @@ func init() {
defaultLogger.Store(New(newDefaultHandler(loginternal.DefaultOutput))) defaultLogger.Store(New(newDefaultHandler(loginternal.DefaultOutput)))
} }
// Default returns the default Logger. // Default returns the default [Logger].
func Default() *Logger { return defaultLogger.Load() } func Default() *Logger { return defaultLogger.Load() }
// SetDefault makes l the default Logger. // SetDefault makes l the default [Logger].
// After this call, output from the log package's default Logger // After this call, output from the log package's default Logger
// (as with [log.Print], etc.) will be logged at LevelInfo using l's Handler. // (as with [log.Print], etc.) will be logged at [LevelInfo] using l's Handler.
func SetDefault(l *Logger) { func SetDefault(l *Logger) {
defaultLogger.Store(l) defaultLogger.Store(l)
// If the default's handler is a defaultHandler, then don't use a handleWriter, // If the default's handler is a defaultHandler, then don't use a handleWriter,
@ -72,7 +72,7 @@ func (w *handlerWriter) Write(buf []byte) (int, error) {
// A Logger records structured information about each call to its // A Logger records structured information about each call to its
// Log, Debug, Info, Warn, and Error methods. // Log, Debug, Info, Warn, and Error methods.
// For each call, it creates a Record and passes it to a Handler. // For each call, it creates a [Record] and passes it to a [Handler].
// //
// To create a new Logger, call [New] or a Logger method // To create a new Logger, call [New] or a Logger method
// that begins "With". // that begins "With".
@ -124,7 +124,7 @@ func New(h Handler) *Logger {
return &Logger{handler: h} return &Logger{handler: h}
} }
// With calls Logger.With on the default logger. // With calls [Logger.With] on the default logger.
func With(args ...any) *Logger { func With(args ...any) *Logger {
return Default().With(args...) return Default().With(args...)
} }
@ -137,7 +137,7 @@ func (l *Logger) Enabled(ctx context.Context, level Level) bool {
return l.Handler().Enabled(ctx, level) return l.Handler().Enabled(ctx, level)
} }
// NewLogLogger returns a new log.Logger such that each call to its Output method // NewLogLogger returns a new [log.Logger] such that each call to its Output method
// dispatches a Record to the specified handler. The logger acts as a bridge from // dispatches a Record to the specified handler. The logger acts as a bridge from
// the older log API to newer structured logging handlers. // the older log API to newer structured logging handlers.
func NewLogLogger(h Handler, level Level) *log.Logger { func NewLogLogger(h Handler, level Level) *log.Logger {
@ -163,42 +163,42 @@ func (l *Logger) LogAttrs(ctx context.Context, level Level, msg string, attrs ..
l.logAttrs(ctx, level, msg, attrs...) l.logAttrs(ctx, level, msg, attrs...)
} }
// Debug logs at LevelDebug. // Debug logs at [LevelDebug].
func (l *Logger) Debug(msg string, args ...any) { func (l *Logger) Debug(msg string, args ...any) {
l.log(context.Background(), LevelDebug, msg, args...) l.log(context.Background(), LevelDebug, msg, args...)
} }
// DebugContext logs at LevelDebug with the given context. // DebugContext logs at [LevelDebug] with the given context.
func (l *Logger) DebugContext(ctx context.Context, msg string, args ...any) { func (l *Logger) DebugContext(ctx context.Context, msg string, args ...any) {
l.log(ctx, LevelDebug, msg, args...) l.log(ctx, LevelDebug, msg, args...)
} }
// Info logs at LevelInfo. // Info logs at [LevelInfo].
func (l *Logger) Info(msg string, args ...any) { func (l *Logger) Info(msg string, args ...any) {
l.log(context.Background(), LevelInfo, msg, args...) l.log(context.Background(), LevelInfo, msg, args...)
} }
// InfoContext logs at LevelInfo with the given context. // InfoContext logs at [LevelInfo] with the given context.
func (l *Logger) InfoContext(ctx context.Context, msg string, args ...any) { func (l *Logger) InfoContext(ctx context.Context, msg string, args ...any) {
l.log(ctx, LevelInfo, msg, args...) l.log(ctx, LevelInfo, msg, args...)
} }
// Warn logs at LevelWarn. // Warn logs at [LevelWarn].
func (l *Logger) Warn(msg string, args ...any) { func (l *Logger) Warn(msg string, args ...any) {
l.log(context.Background(), LevelWarn, msg, args...) l.log(context.Background(), LevelWarn, msg, args...)
} }
// WarnContext logs at LevelWarn with the given context. // WarnContext logs at [LevelWarn] with the given context.
func (l *Logger) WarnContext(ctx context.Context, msg string, args ...any) { func (l *Logger) WarnContext(ctx context.Context, msg string, args ...any) {
l.log(ctx, LevelWarn, msg, args...) l.log(ctx, LevelWarn, msg, args...)
} }
// Error logs at LevelError. // Error logs at [LevelError].
func (l *Logger) Error(msg string, args ...any) { func (l *Logger) Error(msg string, args ...any) {
l.log(context.Background(), LevelError, msg, args...) l.log(context.Background(), LevelError, msg, args...)
} }
// ErrorContext logs at LevelError with the given context. // ErrorContext logs at [LevelError] with the given context.
func (l *Logger) ErrorContext(ctx context.Context, msg string, args ...any) { func (l *Logger) ErrorContext(ctx context.Context, msg string, args ...any) {
l.log(ctx, LevelError, msg, args...) l.log(ctx, LevelError, msg, args...)
} }
@ -245,52 +245,52 @@ func (l *Logger) logAttrs(ctx context.Context, level Level, msg string, attrs ..
_ = l.Handler().Handle(ctx, r) _ = l.Handler().Handle(ctx, r)
} }
// Debug calls Logger.Debug on the default logger. // Debug calls [Logger.Debug] on the default logger.
func Debug(msg string, args ...any) { func Debug(msg string, args ...any) {
Default().log(context.Background(), LevelDebug, msg, args...) Default().log(context.Background(), LevelDebug, msg, args...)
} }
// DebugContext calls Logger.DebugContext on the default logger. // DebugContext calls [Logger.DebugContext] on the default logger.
func DebugContext(ctx context.Context, msg string, args ...any) { func DebugContext(ctx context.Context, msg string, args ...any) {
Default().log(ctx, LevelDebug, msg, args...) Default().log(ctx, LevelDebug, msg, args...)
} }
// Info calls Logger.Info on the default logger. // Info calls [Logger.Info] on the default logger.
func Info(msg string, args ...any) { func Info(msg string, args ...any) {
Default().log(context.Background(), LevelInfo, msg, args...) Default().log(context.Background(), LevelInfo, msg, args...)
} }
// InfoContext calls Logger.InfoContext on the default logger. // InfoContext calls [Logger.InfoContext] on the default logger.
func InfoContext(ctx context.Context, msg string, args ...any) { func InfoContext(ctx context.Context, msg string, args ...any) {
Default().log(ctx, LevelInfo, msg, args...) Default().log(ctx, LevelInfo, msg, args...)
} }
// Warn calls Logger.Warn on the default logger. // Warn calls [Logger.Warn] on the default logger.
func Warn(msg string, args ...any) { func Warn(msg string, args ...any) {
Default().log(context.Background(), LevelWarn, msg, args...) Default().log(context.Background(), LevelWarn, msg, args...)
} }
// WarnContext calls Logger.WarnContext on the default logger. // WarnContext calls [Logger.WarnContext] on the default logger.
func WarnContext(ctx context.Context, msg string, args ...any) { func WarnContext(ctx context.Context, msg string, args ...any) {
Default().log(ctx, LevelWarn, msg, args...) Default().log(ctx, LevelWarn, msg, args...)
} }
// Error calls Logger.Error on the default logger. // Error calls [Logger.Error] on the default logger.
func Error(msg string, args ...any) { func Error(msg string, args ...any) {
Default().log(context.Background(), LevelError, msg, args...) Default().log(context.Background(), LevelError, msg, args...)
} }
// ErrorContext calls Logger.ErrorContext on the default logger. // ErrorContext calls [Logger.ErrorContext] on the default logger.
func ErrorContext(ctx context.Context, msg string, args ...any) { func ErrorContext(ctx context.Context, msg string, args ...any) {
Default().log(ctx, LevelError, msg, args...) Default().log(ctx, LevelError, msg, args...)
} }
// Log calls Logger.Log on the default logger. // Log calls [Logger.Log] on the default logger.
func Log(ctx context.Context, level Level, msg string, args ...any) { func Log(ctx context.Context, level Level, msg string, args ...any) {
Default().log(ctx, level, msg, args...) Default().log(ctx, level, msg, args...)
} }
// LogAttrs calls Logger.LogAttrs on the default logger. // LogAttrs calls [Logger.LogAttrs] on the default logger.
func LogAttrs(ctx context.Context, level Level, msg string, attrs ...Attr) { func LogAttrs(ctx context.Context, level Level, msg string, attrs ...Attr) {
Default().logAttrs(ctx, level, msg, attrs...) Default().logAttrs(ctx, level, msg, attrs...)
} }

View File

@ -50,7 +50,7 @@ type Record struct {
back []Attr back []Attr
} }
// NewRecord creates a Record from the given arguments. // NewRecord creates a [Record] from the given arguments.
// Use [Record.AddAttrs] to add attributes to the Record. // Use [Record.AddAttrs] to add attributes to the Record.
// //
// NewRecord is intended for logging APIs that want to support a [Handler] as // NewRecord is intended for logging APIs that want to support a [Handler] as
@ -72,12 +72,12 @@ func (r Record) Clone() Record {
return r return r
} }
// NumAttrs returns the number of attributes in the Record. // NumAttrs returns the number of attributes in the [Record].
func (r Record) NumAttrs() int { func (r Record) NumAttrs() int {
return r.nFront + len(r.back) return r.nFront + len(r.back)
} }
// Attrs calls f on each Attr in the Record. // Attrs calls f on each Attr in the [Record].
// Iteration stops if f returns false. // Iteration stops if f returns false.
func (r Record) Attrs(f func(Attr) bool) { func (r Record) Attrs(f func(Attr) bool) {
for i := 0; i < r.nFront; i++ { for i := 0; i < r.nFront; i++ {
@ -92,7 +92,7 @@ func (r Record) Attrs(f func(Attr) bool) {
} }
} }
// AddAttrs appends the given Attrs to the Record's list of Attrs. // AddAttrs appends the given Attrs to the [Record]'s list of Attrs.
// It omits empty groups. // It omits empty groups.
func (r *Record) AddAttrs(attrs ...Attr) { func (r *Record) AddAttrs(attrs ...Attr) {
var i int var i int
@ -124,7 +124,7 @@ func (r *Record) AddAttrs(attrs ...Attr) {
} }
// Add converts the args to Attrs as described in [Logger.Log], // Add converts the args to Attrs as described in [Logger.Log],
// then appends the Attrs to the Record's list of Attrs. // then appends the Attrs to the [Record]'s list of Attrs.
// It omits empty groups. // It omits empty groups.
func (r *Record) Add(args ...any) { func (r *Record) Add(args ...any) {
var a Attr var a Attr

View File

@ -16,13 +16,13 @@ import (
"unicode/utf8" "unicode/utf8"
) )
// TextHandler is a Handler that writes Records to an io.Writer as a // TextHandler is a [Handler] that writes Records to an [io.Writer] as a
// sequence of key=value pairs separated by spaces and followed by a newline. // sequence of key=value pairs separated by spaces and followed by a newline.
type TextHandler struct { type TextHandler struct {
*commonHandler *commonHandler
} }
// NewTextHandler creates a TextHandler that writes to w, // NewTextHandler creates a [TextHandler] that writes to w,
// using the given options. // using the given options.
// If opts is nil, the default options are used. // If opts is nil, the default options are used.
func NewTextHandler(w io.Writer, opts *HandlerOptions) *TextHandler { func NewTextHandler(w io.Writer, opts *HandlerOptions) *TextHandler {
@ -45,7 +45,7 @@ func (h *TextHandler) Enabled(_ context.Context, level Level) bool {
return h.commonHandler.enabled(level) return h.commonHandler.enabled(level)
} }
// WithAttrs returns a new TextHandler whose attributes consists // WithAttrs returns a new [TextHandler] whose attributes consists
// of h's attributes followed by attrs. // of h's attributes followed by attrs.
func (h *TextHandler) WithAttrs(attrs []Attr) Handler { func (h *TextHandler) WithAttrs(attrs []Attr) Handler {
return &TextHandler{commonHandler: h.commonHandler.withAttrs(attrs)} return &TextHandler{commonHandler: h.commonHandler.withAttrs(attrs)}
@ -55,7 +55,7 @@ func (h *TextHandler) WithGroup(name string) Handler {
return &TextHandler{commonHandler: h.commonHandler.withGroup(name)} return &TextHandler{commonHandler: h.commonHandler.withGroup(name)}
} }
// Handle formats its argument Record as a single line of space-separated // Handle formats its argument [Record] as a single line of space-separated
// key=value items. // key=value items.
// //
// If the Record's time is zero, the time is omitted. // If the Record's time is zero, the time is omitted.
@ -75,7 +75,7 @@ func (h *TextHandler) WithGroup(name string) Handler {
// [HandlerOptions.ReplaceAttr]. // [HandlerOptions.ReplaceAttr].
// //
// If a value implements [encoding.TextMarshaler], the result of MarshalText is // If a value implements [encoding.TextMarshaler], the result of MarshalText is
// written. Otherwise, the result of fmt.Sprint is written. // written. Otherwise, the result of [fmt.Sprint] is written.
// //
// Keys and values are quoted with [strconv.Quote] if they contain Unicode space // Keys and values are quoted with [strconv.Quote] if they contain Unicode space
// characters, non-printing characters, '"' or '='. // characters, non-printing characters, '"' or '='.

View File

@ -40,7 +40,7 @@ type (
groupptr *Attr // used in Value.any when the Value is a []Attr groupptr *Attr // used in Value.any when the Value is a []Attr
) )
// Kind is the kind of a Value. // Kind is the kind of a [Value].
type Kind int type Kind int
// The following list is sorted alphabetically, but it's also important that // The following list is sorted alphabetically, but it's also important that
@ -105,32 +105,32 @@ func (v Value) Kind() Kind {
//////////////// Constructors //////////////// Constructors
// StringValue returns a new Value for a string. // StringValue returns a new [Value] for a string.
func StringValue(value string) Value { func StringValue(value string) Value {
return Value{num: uint64(len(value)), any: stringptr(unsafe.StringData(value))} return Value{num: uint64(len(value)), any: stringptr(unsafe.StringData(value))}
} }
// IntValue returns a Value for an int. // IntValue returns a [Value] for an int.
func IntValue(v int) Value { func IntValue(v int) Value {
return Int64Value(int64(v)) return Int64Value(int64(v))
} }
// Int64Value returns a Value for an int64. // Int64Value returns a [Value] for an int64.
func Int64Value(v int64) Value { func Int64Value(v int64) Value {
return Value{num: uint64(v), any: KindInt64} return Value{num: uint64(v), any: KindInt64}
} }
// Uint64Value returns a Value for a uint64. // Uint64Value returns a [Value] for a uint64.
func Uint64Value(v uint64) Value { func Uint64Value(v uint64) Value {
return Value{num: v, any: KindUint64} return Value{num: v, any: KindUint64}
} }
// Float64Value returns a Value for a floating-point number. // Float64Value returns a [Value] for a floating-point number.
func Float64Value(v float64) Value { func Float64Value(v float64) Value {
return Value{num: math.Float64bits(v), any: KindFloat64} return Value{num: math.Float64bits(v), any: KindFloat64}
} }
// BoolValue returns a Value for a bool. // BoolValue returns a [Value] for a bool.
func BoolValue(v bool) Value { func BoolValue(v bool) Value {
u := uint64(0) u := uint64(0)
if v { if v {
@ -143,7 +143,7 @@ func BoolValue(v bool) Value {
// Values. (No user-provided value has this type.) // Values. (No user-provided value has this type.)
type timeLocation *time.Location type timeLocation *time.Location
// TimeValue returns a Value for a time.Time. // TimeValue returns a [Value] for a [time.Time].
// It discards the monotonic portion. // It discards the monotonic portion.
func TimeValue(v time.Time) Value { func TimeValue(v time.Time) Value {
if v.IsZero() { if v.IsZero() {
@ -156,12 +156,12 @@ func TimeValue(v time.Time) Value {
return Value{num: uint64(v.UnixNano()), any: timeLocation(v.Location())} return Value{num: uint64(v.UnixNano()), any: timeLocation(v.Location())}
} }
// DurationValue returns a Value for a time.Duration. // DurationValue returns a [Value] for a [time.Duration].
func DurationValue(v time.Duration) Value { func DurationValue(v time.Duration) Value {
return Value{num: uint64(v.Nanoseconds()), any: KindDuration} return Value{num: uint64(v.Nanoseconds()), any: KindDuration}
} }
// GroupValue returns a new Value for a list of Attrs. // GroupValue returns a new [Value] for a list of Attrs.
// The caller must not subsequently mutate the argument slice. // The caller must not subsequently mutate the argument slice.
func GroupValue(as ...Attr) Value { func GroupValue(as ...Attr) Value {
// Remove empty groups. // Remove empty groups.
@ -190,21 +190,21 @@ func countEmptyGroups(as []Attr) int {
return n return n
} }
// AnyValue returns a Value for the supplied value. // AnyValue returns a [Value] for the supplied value.
// //
// If the supplied value is of type Value, it is returned // If the supplied value is of type Value, it is returned
// unmodified. // unmodified.
// //
// Given a value of one of Go's predeclared string, bool, or // Given a value of one of Go's predeclared string, bool, or
// (non-complex) numeric types, AnyValue returns a Value of kind // (non-complex) numeric types, AnyValue returns a Value of kind
// String, Bool, Uint64, Int64, or Float64. The width of the // [KindString], [KindBool], [KindUint64], [KindInt64], or [KindFloat64].
// original numeric type is not preserved. // The width of the original numeric type is not preserved.
// //
// Given a time.Time or time.Duration value, AnyValue returns a Value of kind // Given a [time.Time] or [time.Duration] value, AnyValue returns a Value of kind
// KindTime or KindDuration. The monotonic time is not preserved. // [KindTime] or [KindDuration]. The monotonic time is not preserved.
// //
// For nil, or values of all other types, including named types whose // For nil, or values of all other types, including named types whose
// underlying type is numeric, AnyValue returns a value of kind KindAny. // underlying type is numeric, AnyValue returns a value of kind [KindAny].
func AnyValue(v any) Value { func AnyValue(v any) Value {
switch v := v.(type) { switch v := v.(type) {
case string: case string:
@ -285,7 +285,7 @@ func (v Value) Any() any {
} }
} }
// String returns Value's value as a string, formatted like fmt.Sprint. Unlike // String returns Value's value as a string, formatted like [fmt.Sprint]. Unlike
// the methods Int64, Float64, and so on, which panic if v is of the // the methods Int64, Float64, and so on, which panic if v is of the
// wrong kind, String never panics. // wrong kind, String never panics.
func (v Value) String() string { func (v Value) String() string {
@ -331,7 +331,7 @@ func (v Value) bool() bool {
return v.num == 1 return v.num == 1
} }
// Duration returns v's value as a time.Duration. It panics // Duration returns v's value as a [time.Duration]. It panics
// if v is not a time.Duration. // if v is not a time.Duration.
func (v Value) Duration() time.Duration { func (v Value) Duration() time.Duration {
if g, w := v.Kind(), KindDuration; g != w { if g, w := v.Kind(), KindDuration; g != w {
@ -359,7 +359,7 @@ func (v Value) float() float64 {
return math.Float64frombits(v.num) return math.Float64frombits(v.num)
} }
// Time returns v's value as a time.Time. It panics // Time returns v's value as a [time.Time]. It panics
// if v is not a time.Time. // if v is not a time.Time.
func (v Value) Time() time.Time { func (v Value) Time() time.Time {
if g, w := v.Kind(), KindTime; g != w { if g, w := v.Kind(), KindTime; g != w {
@ -383,7 +383,7 @@ func (v Value) LogValuer() LogValuer {
} }
// Group returns v's value as a []Attr. // Group returns v's value as a []Attr.
// It panics if v's Kind is not KindGroup. // It panics if v's [Kind] is not [KindGroup].
func (v Value) Group() []Attr { func (v Value) Group() []Attr {
if sp, ok := v.any.(groupptr); ok { if sp, ok := v.any.(groupptr); ok {
return unsafe.Slice((*Attr)(sp), v.num) return unsafe.Slice((*Attr)(sp), v.num)
@ -470,13 +470,13 @@ type LogValuer interface {
const maxLogValues = 100 const maxLogValues = 100
// Resolve repeatedly calls LogValue on v while it implements LogValuer, // Resolve repeatedly calls LogValue on v while it implements [LogValuer],
// and returns the result. // and returns the result.
// If v resolves to a group, the group's attributes' values are not recursively // If v resolves to a group, the group's attributes' values are not recursively
// resolved. // resolved.
// If the number of LogValue calls exceeds a threshold, a Value containing an // If the number of LogValue calls exceeds a threshold, a Value containing an
// error is returned. // error is returned.
// Resolve's return value is guaranteed not to be of Kind KindLogValuer. // Resolve's return value is guaranteed not to be of Kind [KindLogValuer].
func (v Value) Resolve() (rv Value) { func (v Value) Resolve() (rv Value) {
orig := v orig := v
defer func() { defer func() {

View File

@ -18,9 +18,9 @@ import (
) )
// The Priority is a combination of the syslog facility and // The Priority is a combination of the syslog facility and
// severity. For example, LOG_ALERT | LOG_FTP sends an alert severity // severity. For example, [LOG_ALERT] | [LOG_FTP] sends an alert severity
// message from the FTP facility. The default severity is LOG_EMERG; // message from the FTP facility. The default severity is [LOG_EMERG];
// the default facility is LOG_KERN. // the default facility is [LOG_KERN].
type Priority int type Priority int
const severityMask = 0x07 const severityMask = 0x07
@ -103,7 +103,7 @@ type netConn struct {
// New establishes a new connection to the system log daemon. Each // New establishes a new connection to the system log daemon. Each
// write to the returned writer sends a log message with the given // write to the returned writer sends a log message with the given
// priority (a combination of the syslog facility and severity) and // priority (a combination of the syslog facility and severity) and
// prefix tag. If tag is empty, the os.Args[0] is used. // prefix tag. If tag is empty, the [os.Args][0] is used.
func New(priority Priority, tag string) (*Writer, error) { func New(priority Priority, tag string) (*Writer, error) {
return Dial("", "", priority, tag) return Dial("", "", priority, tag)
} }
@ -111,7 +111,7 @@ func New(priority Priority, tag string) (*Writer, error) {
// Dial establishes a connection to a log daemon by connecting to // Dial establishes a connection to a log daemon by connecting to
// address raddr on the specified network. Each write to the returned // address raddr on the specified network. Each write to the returned
// writer sends a log message with the facility and severity // writer sends a log message with the facility and severity
// (from priority) and tag. If tag is empty, the os.Args[0] is used. // (from priority) and tag. If tag is empty, the [os.Args][0] is used.
// If network is empty, Dial will connect to the local syslog server. // If network is empty, Dial will connect to the local syslog server.
// Otherwise, see the documentation for net.Dial for valid values // Otherwise, see the documentation for net.Dial for valid values
// of network and raddr. // of network and raddr.
@ -191,56 +191,56 @@ func (w *Writer) Close() error {
return nil return nil
} }
// Emerg logs a message with severity LOG_EMERG, ignoring the severity // Emerg logs a message with severity [LOG_EMERG], ignoring the severity
// passed to New. // passed to New.
func (w *Writer) Emerg(m string) error { func (w *Writer) Emerg(m string) error {
_, err := w.writeAndRetry(LOG_EMERG, m) _, err := w.writeAndRetry(LOG_EMERG, m)
return err return err
} }
// Alert logs a message with severity LOG_ALERT, ignoring the severity // Alert logs a message with severity [LOG_ALERT], ignoring the severity
// passed to New. // passed to New.
func (w *Writer) Alert(m string) error { func (w *Writer) Alert(m string) error {
_, err := w.writeAndRetry(LOG_ALERT, m) _, err := w.writeAndRetry(LOG_ALERT, m)
return err return err
} }
// Crit logs a message with severity LOG_CRIT, ignoring the severity // Crit logs a message with severity [LOG_CRIT], ignoring the severity
// passed to New. // passed to New.
func (w *Writer) Crit(m string) error { func (w *Writer) Crit(m string) error {
_, err := w.writeAndRetry(LOG_CRIT, m) _, err := w.writeAndRetry(LOG_CRIT, m)
return err return err
} }
// Err logs a message with severity LOG_ERR, ignoring the severity // Err logs a message with severity [LOG_ERR], ignoring the severity
// passed to New. // passed to New.
func (w *Writer) Err(m string) error { func (w *Writer) Err(m string) error {
_, err := w.writeAndRetry(LOG_ERR, m) _, err := w.writeAndRetry(LOG_ERR, m)
return err return err
} }
// Warning logs a message with severity LOG_WARNING, ignoring the // Warning logs a message with severity [LOG_WARNING], ignoring the
// severity passed to New. // severity passed to New.
func (w *Writer) Warning(m string) error { func (w *Writer) Warning(m string) error {
_, err := w.writeAndRetry(LOG_WARNING, m) _, err := w.writeAndRetry(LOG_WARNING, m)
return err return err
} }
// Notice logs a message with severity LOG_NOTICE, ignoring the // Notice logs a message with severity [LOG_NOTICE], ignoring the
// severity passed to New. // severity passed to New.
func (w *Writer) Notice(m string) error { func (w *Writer) Notice(m string) error {
_, err := w.writeAndRetry(LOG_NOTICE, m) _, err := w.writeAndRetry(LOG_NOTICE, m)
return err return err
} }
// Info logs a message with severity LOG_INFO, ignoring the severity // Info logs a message with severity [LOG_INFO], ignoring the severity
// passed to New. // passed to New.
func (w *Writer) Info(m string) error { func (w *Writer) Info(m string) error {
_, err := w.writeAndRetry(LOG_INFO, m) _, err := w.writeAndRetry(LOG_INFO, m)
return err return err
} }
// Debug logs a message with severity LOG_DEBUG, ignoring the severity // Debug logs a message with severity [LOG_DEBUG], ignoring the severity
// passed to New. // passed to New.
func (w *Writer) Debug(m string) error { func (w *Writer) Debug(m string) error {
_, err := w.writeAndRetry(LOG_DEBUG, m) _, err := w.writeAndRetry(LOG_DEBUG, m)
@ -305,10 +305,10 @@ func (n *netConn) close() error {
return n.conn.Close() return n.conn.Close()
} }
// NewLogger creates a log.Logger whose output is written to the // NewLogger creates a [log.Logger] whose output is written to the
// system log service with the specified priority, a combination of // system log service with the specified priority, a combination of
// the syslog facility and severity. The logFlag argument is the flag // the syslog facility and severity. The logFlag argument is the flag
// set passed through to log.New to create the Logger. // set passed through to [log.New] to create the Logger.
func NewLogger(p Priority, logFlag int) (*log.Logger, error) { func NewLogger(p Priority, logFlag int) (*log.Logger, error) {
s, err := New(p, "") s, err := New(p, "")
if err != nil { if err != nil {