utils

package
v0.10.0 Latest Latest
Warning

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

Go to latest
Published: Apr 8, 2025 License: MIT Imports: 20 Imported by: 0

Documentation

Index

Examples

Constants

View Source
const ExceptionFieldName = "exception"

ExceptionFieldName is the field name used for exception fields. In our case, it should be a sentry-formatted exception built from a panic.

Variables

View Source
var (
	// ErrInvalidPeriod is returned if the period is not valid.
	ErrInvalidPeriod = errors.New("invalid period")
	// ErrInvalidYearMonth is returned if the date is incorrectly formatted.
	ErrInvalidDate = fmt.Errorf("%w: Expects YYYY-MM", ErrInvalidPeriod)

	// ErrInvalidPeriod is returned if the date range is incorrectly formatted.
	ErrInvalidFromToPeriod = fmt.Errorf("%w: Expects YYYY-MM--YYYY-MM", ErrInvalidPeriod)

	// ErrForbiddenPeriod is returned if the date range is impossible.
	// Meaning the first date is after the last.
	ErrForbiddenPeriod = fmt.Errorf("%w: 'date_from' must be before 'date_to'", ErrInvalidPeriod)
)

Functions

func CtxWithSignal

func CtxWithSignal(ctx context.Context, sig ...os.Signal) (context.Context, func())

CtxWithSignal returns a context that will be canceled by the given signals.

func PrintFrame

func PrintFrame(frame sentry.Frame) string

PrintFrame prints a sentry frame in a go stack-like manner.

func RandomString

func RandomString(n int) string

RandomString returns a random string of length 'n'.

func StringSliceFilterOut added in v0.9.0

func StringSliceFilterOut(slice []string, values ...string) []string

Types

type ConsoleWriter

type ConsoleWriter struct {
	// Out is the output destination.
	Out io.Writer

	// NoColor disables the colorized output.
	NoColor bool

	// TimeFormat specifies the format for timestamp in output.
	TimeFormat string

	// PartsOrder defines the order of parts in output.
	PartsOrder []string

	FormatTimestamp     Formatter
	FormatLevel         Formatter
	FormatCaller        Formatter
	FormatMessage       Formatter
	FormatFieldName     Formatter
	FormatFieldValue    Formatter
	FormatErrFieldName  Formatter
	FormatErrFieldValue Formatter
	FormatExcFieldName  Formatter
	FormatExcFieldValue Formatter
}

ConsoleWriter parses the JSON input and writes it in an (optionally) colorized, human-friendly format to Out.

Example
package main

import (
	"os"

	"github.com/rs/zerolog"

	"orus.io/orus-io/rednerd/utils"
)

func main() {
	log := zerolog.New(utils.ConsoleWriter{Out: os.Stdout, NoColor: true})

	log.Info().Str("foo", "bar").Msg("Hello World")
}
Output:
<nil> INF Hello World foo=bar
Example (CustomFormatters)
package main

import (
	"fmt"
	"os"
	"strings"

	"github.com/rs/zerolog"

	"orus.io/orus-io/rednerd/utils"
)

func main() {
	out := utils.ConsoleWriter{Out: os.Stdout, NoColor: true}
	out.FormatLevel = func(i interface{}) string { return strings.ToUpper(fmt.Sprintf("%-6s|", i)) }
	out.FormatFieldName = func(i interface{}) string { return fmt.Sprintf("%s:", i) }
	out.FormatFieldValue = func(i interface{}) string { return strings.ToUpper(fmt.Sprintf("%s", i)) }
	log := zerolog.New(out)

	log.Info().Str("foo", "bar").Msg("Hello World")
}
Output:
<nil> INFO  | Hello World foo:BAR

func NewConsoleWriter

func NewConsoleWriter(options ...func(w *ConsoleWriter)) ConsoleWriter

NewConsoleWriter creates and initializes a new ConsoleWriter.

Example
package main

import (
	"github.com/rs/zerolog"
)

func main() {
	out := zerolog.NewConsoleWriter()
	out.NoColor = true // For testing purposes only
	log := zerolog.New(out)

	log.Debug().Str("foo", "bar").Msg("Hello World")
}
Output:
<nil> DBG Hello World foo=bar
Example (CustomFormatters)
package main

import (
	"fmt"
	"strings"
	"time"

	"github.com/rs/zerolog"

	"orus.io/orus-io/rednerd/utils"
)

func main() {
	out := utils.NewConsoleWriter(
		func(w *utils.ConsoleWriter) {
			// Customize time format
			w.TimeFormat = time.RFC822
			// Customize level formatting
			w.FormatLevel = func(i interface{}) string { return strings.ToUpper(fmt.Sprintf("[%-5s]", i)) }
		},
	)
	out.NoColor = true // For testing purposes only

	log := zerolog.New(out)

	log.Info().Str("foo", "bar").Msg("Hello World")
}
Output:
<nil> [INFO ] Hello World foo=bar

func (ConsoleWriter) Write

func (w ConsoleWriter) Write(p []byte) (int, error)

Write transforms the JSON input with formatters and appends to w.Out.

type Formatter

type Formatter func(interface{}) string

Formatter transforms the input into a formatted string.

type GroupedError added in v0.9.0

type GroupedError []error

func (GroupedError) Error added in v0.9.0

func (gerr GroupedError) Error() string

func (GroupedError) IsEmpty added in v0.9.0

func (gerr GroupedError) IsEmpty() bool

func (GroupedError) Unwrap added in v0.9.0

func (gerr GroupedError) Unwrap() []error

type HTTPError

type HTTPError struct {
	StatusCode int
	Err        error
}

HTTPError wraps a http status code and a regular error.

func HTTPBadRequest

func HTTPBadRequest(err error) HTTPError

HTTPBadRequest returns a StatusBadRequest error.

func HTTPInternalServerError

func HTTPInternalServerError(err error) HTTPError

HTTPInternalServerError returns a StatusBadRequest error.

func NewHTTPError

func NewHTTPError(statusCode int, err error) HTTPError

NewHTTPError creates a HTTPError.

func NewHTTPErrorf

func NewHTTPErrorf(statusCode int, err string, args ...interface{}) HTTPError

NewHTTPErrorf creates a HTTPError.

func (HTTPError) Error

func (e HTTPError) Error() string

type Period

type Period struct {
	From time.Time
	To   time.Time
}

func ParsePeriod

func ParsePeriod(s string) (*Period, error)

func (*Period) ToString

func (p *Period) ToString() string

type VecTimer

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

VecTimer is a helper type to time functions. Use NewVecTimer to create new instances.

func NewVecTimer

func NewVecTimer(v prometheus.ObserverVec) *VecTimer

NewVecTimer creates a new VecTimer.

func (VecTimer) GetBegin

func (t VecTimer) GetBegin() time.Time

func (*VecTimer) ObserveDurationWithLabelValues

func (t *VecTimer) ObserveDurationWithLabelValues(values ...string) time.Duration

ObserveDuration records the duration passed since the Timer was created with NewTimer. It calls the Observe method of the Observer provided during construction with the duration in seconds as an argument. The observed duration is also returned. ObserveDuration is usually called with a defer statement.

Note that this method is only guaranteed to never observe negative durations if used with Go1.9+.

Source Files

  • ctx_with_signal.go
  • errgroup.go
  • http.go
  • log-console-writer.go
  • parse_period.go
  • prometheus_vec_timer.go
  • randomstring.go
  • string_slice_filter_out.go

Jump to

Keyboard shortcuts

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