zapio

package
Version: v1.19.1 Latest Latest
Warning

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

Go to latest
Published: Sep 8, 2021 License: MIT Imports: 4 Imported by: 0

Documentation

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Writer

type Writer struct {
	// Log specifies the logger to which the Writer will write messages.
	//
	// The Writer will panic if Log is unspecified.
	Log *zap.Logger

	// Log level for the messages written to the provided logger.
	//
	// If unspecified, defaults to Info.
	Level zapcore.Level
	// contains filtered or unexported fields
}

Writer is an io.Writer that writes to the provided Zap logger, splitting log messages on line boundaries. The Writer will buffer writes in memory until it encounters a newline, or the caller calls Sync or Close.

Use the Writer with packages like os/exec where an io.Writer is required, and you want to log the output using your existing logger configuration. For example,

writer := &zapio.Writer{Log: logger, Level: zap.DebugLevel}
defer writer.Close()

cmd := exec.CommandContext(ctx, ...)
cmd.Stdout = writer
cmd.Stderr = writer
if err := cmd.Run(); err != nil {
    return err
}

Writer must be closed when finished to flush buffered data to the logger.

Example
package main

import (
	"io"
	"log"

	"go.uber.org/zap"
	"go.uber.org/zap/zapio"
)

func main() {
	logger := zap.NewExample()
	w := &zapio.Writer{Log: logger}

	io.WriteString(w, "starting up\n")
	io.WriteString(w, "running\n")
	io.WriteString(w, "shutting down\n")

	if err := w.Close(); err != nil {
		log.Fatal(err)
	}

}
Output:

{"level":"info","msg":"starting up"}
{"level":"info","msg":"running"}
{"level":"info","msg":"shutting down"}

func (*Writer) Close

func (w *Writer) Close() error

Close closes the writer, flushing any buffered data in the process.

Always call Close once you're done with the Writer to ensure that it flushes all data.

func (*Writer) Sync

func (w *Writer) Sync() error

Sync flushes buffered data to the logger as a new log entry even if it doesn't contain a newline.

func (*Writer) Write

func (w *Writer) Write(bs []byte) (n int, err error)

Write writes the provided bytes to the underlying logger at the configured log level and returns the length of the bytes.

Write will split the input on newlines and post each line as a new log entry to the logger.

Source Files

Jump to

Keyboard shortcuts

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