slogemail

package module
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Oct 9, 2023 License: MIT Imports: 8 Imported by: 0

README

slogemail

Go's log/slog email handler. Wraps slog's JSONHandler or TextHander. There are three ways to create a handler.

Synchronous handler

Behaves as a regular handler but also send an email. By default, email subject is log level and body is log message rendered by base handler. This can be customized by setting GetSubject and GetBody in slogemail.EmailHandlerOpts.

h, err := slogemail.NewHandler(
	os.Stdout, 
	&slog.HandlerOptions{AddSource: true, Level: slog.LevelDebug}, 
	slogemail.EmailHandlerOpts{
                FromAddr:       "from@example.com",
                ToAddrs:        []string{"one@example.com", "two@example.com"},
                JSON:           true,
                // Level can be different from base handler options
                Level:          slog.LevelError, 
                ConnectionInfo: slogemail.SMTPConnectionInfo{
                        Host:     "example.com",
                        Port:     587,
                        Username: "user",
                        Password: "pwd",
                },
        })
if err != nil {
		panic(err)
}

logger := slog.New(h)
// will printed to stdout and sent to email
logger.Error("database error", "detail", "database has gone away")
// will only be printed
logger.Info("login", "user", os.Getenv("USER"))
Asynchronous handler

The same as synchronous, but sending email is performed in a separate goroutine, so that log handling takes less time for the calling goroutine. The handler should be explicitly stopped by calling a provided function, otherwise some log records may be lost.

h, stop, err := slogemail.NewAsyncHandler(
	os.Stdout, 
	&slog.HandlerOptions{AddSource: true, Level: slog.LevelDebug}, 
	slogemail.EmailHandlerOpts{				
				// how many log records can be sent to handler before it starts to process them synchronously
				AsyncQueueSize: 10,
                FromAddr:       "from@example.com",
                ToAddrs:        []string{"one@example.com", "two@example.com"},
                JSON:           true,
                Level:          slog.LevelError, 
                ConnectionInfo: slogemail.SMTPConnectionInfo{
                        Host:     "example.com",
                        Port:     587,
                        Username: "user",
                        Password: "pwd",
                },
        })
if err != nil {
		panic(err)
}

// Needs to be called before application exits so that handler can process remaining logs
defer stop()

logger := slog.New(h)
// will printed to stdout and sent to email
logger.Error("just awful", "err", "database error")
// will only be printed
logger.Info("hello, world", "user", os.Getenv("USER"))
Custom synchronous handler

User defines a function that will handle log record.

h := slogemail.NewCustomHandler(
		os.Stdout,
		&slog.HandlerOptions{Level: slog.LevelDebug},
		func(ctx context.Context, r slog.Record, logOutput string) error {
				doSomething(ctx, logOutput)
		},
		true)

logger := slog.New(h)

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type EmailHandler

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

EmailHandler is a log/slog compatible handler that writes log records in text or json to user-provided io.Writer and also emails records with defined levels to specified addresses.

func NewAsyncHandler

func NewAsyncHandler(w io.Writer, opts *slog.HandlerOptions, emailOpts EmailHandlerOpts) (*EmailHandler, func(), error)

NewAsyncAsyncHandler creates a new handler than prints log to supplied io.Writer and also asynchronously sends them to a simple SMTP server as an email NewAsyncHandler returns a stopper function that should be called before the application exits, otherwise some log records may be dropped.

func NewCustomHandler

func NewCustomHandler(w io.Writer, opts *slog.HandlerOptions, f SendEmailFunc, json bool) *EmailHandler

NewCustomHandler creates a new handler that prints logs to supplied io.Writer and also passes them to user-defined function

func NewHandler

func NewHandler(w io.Writer, opts *slog.HandlerOptions, emailOpts EmailHandlerOpts) (*EmailHandler, error)

NewHandler creates a new handler than prints log to supplied io.Writer and also sends them to a simple SMTP server as an email

func (*EmailHandler) Enabled

func (h *EmailHandler) Enabled(ctx context.Context, level slog.Level) bool

func (*EmailHandler) Handle

func (h *EmailHandler) Handle(ctx context.Context, r slog.Record) error

func (*EmailHandler) WithAttrs

func (h *EmailHandler) WithAttrs(attrs []slog.Attr) slog.Handler

func (*EmailHandler) WithGroup

func (h *EmailHandler) WithGroup(name string) slog.Handler

type EmailHandlerOpts

type EmailHandlerOpts struct {
	// FromAddr is a from email address
	FromAddr string
	// ToAddrs is a slice of emails that log records will be sent to
	ToAddrs []string
	// JSON sets log record format (true = pretty JSON, false = text)
	JSON bool
	// Level determines the minimum log level at which emails will be sent. Can be different from level in `opts` parameter in NewHandler
	Level slog.Level
	// GetSubject is a user-defined function for making custom email subject. By default log record level name is used.
	GetSubject GetSubjectFunc
	// GetBody is a user-defined function for making custom email body. By default log record text is used.
	GetBody GetBodyFunc
	// ConnectionInfo contains information about SMTP server.
	ConnectionInfo SMTPConnectionInfo

	// AsyncQueueSize specifies how many records can be queued before logger will have to actually wait for them to be sent
	// Ignored if handler is not asynchronous
	// Default: 1
	AsyncQueueSize int
	// contains filtered or unexported fields
}

EmailHandlerOpts contains options specific to EmailHandler If SendEmail is not provided, ConnectionInfo will be used

type GetBodyFunc

type GetBodyFunc func(ctx context.Context, r slog.Record, logOutput string) string

GetBodyFunc is a function that accepts an slog record and rendered output from slog's standard text or json handler and returns a body for a letter

type GetSubjectFunc

type GetSubjectFunc func(ctx context.Context, r slog.Record, logOutput string) string

GetSubjectFunc is a function that accepts an slog record and rendered output from slog's standard text or json handler and returns a subject for a letter

type Mailer

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

func NewMailer

func NewMailer(smtpHost string, smtpPort int, username string, password string) (*Mailer, error)

func (*Mailer) SendPlaintextMessage

func (m *Mailer) SendPlaintextMessage(ctx context.Context, from string, to []string, subject string, body string) error

type SMTPConnectionInfo

type SMTPConnectionInfo struct {
	// Host
	Host string
	// Port
	Port int
	// Username
	Username string
	// Password
	Password string
}

SMTPConnectionInfo cotains information sufficient to connect to a generic SMTP server

type SendEmailFunc

type SendEmailFunc func(ctx context.Context, r slog.Record, logOutput string) error

SendEmailFunc describes function that user has to implement to fully control mailing process

Jump to

Keyboard shortcuts

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