• Stars
    star
    134
  • Rank 270,967 (Top 6 %)
  • Language
    Go
  • License
    Other
  • Created over 10 years ago
  • Updated about 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A logging library for Go. Doesn't use the built in go log standard library, but instead offers a replacement.

loggo

import "github.com/juju/loggo/v2"

GoDoc

Module level logging for Go

This package provides an alternative to the standard library log package.

The actual logging functions never return errors. If you are logging something, you really don't want to be worried about the logging having trouble.

Modules have names that are defined by dotted strings.

"first.second.third"

There is a root module that has the name "". Each module (except the root module) has a parent, identified by the part of the name without the last dotted value.

  • the parent of "first.second.third" is "first.second"
  • the parent of "first.second" is "first"
  • the parent of "first" is "" (the root module)

Each module can specify its own severity level. Logging calls that are of a lower severity than the module's effective severity level are not written out.

Loggers are created through their Context. There is a default global context that is used if you just want simple use. Contexts are used where you may want different sets of writers for different loggers. Most use cases are fine with just using the default global context.

Loggers are created using the GetLogger function.

logger := loggo.GetLogger("foo.bar")

The default global context has one writer registered, which will write to Stderr, and the root module, which will only emit warnings and above. If you want to continue using the default logger, but have it emit all logging levels you need to do the following.

writer, err := loggo.RemoveWriter("default")
// err is non-nil if and only if the name isn't found.
loggo.RegisterWriter("default", writer)

To make loggo produce colored output, you can do the following, having imported github.com/juju/loggo/loggocolor:

loggo.ReplaceDefaultWriter(loggocolor.NewWriter(os.Stderr))

Constants

const DefaultWriterName = "default"

DefaultWriterName is the name of the default writer for a Context.

Variables

var TimeFormat = initTimeFormat()

TimeFormat is the time format used for the default writer. This can be set with the environment variable LOGGO_TIME_FORMAT.

func ConfigureLoggers

func ConfigureLoggers(specification string) error

ConfigureLoggers configures loggers according to the given string specification, which specifies a set of modules and their associated logging levels. Loggers are colon- or semicolon-separated; each module is specified as =. White space outside of module names and levels is ignored. The root module is specified with the name "".

An example specification:

`<root>=ERROR; foo.bar=WARNING`

func DefaultFormatter

func DefaultFormatter(entry Entry) string

DefaultFormatter returns the parameters separated by spaces except for filename and line which are separated by a colon. The timestamp is shown to second resolution in UTC. For example:

2016-07-02 15:04:05

func LoggerInfo

func LoggerInfo() string

LoggerInfo returns information about the configured loggers and their logging levels. The information is returned in the format expected by ConfigureLoggers. Loggers with UNSPECIFIED level will not be included.

func RegisterWriter

func RegisterWriter(name string, writer Writer) error

RegisterWriter adds the writer to the list of writers in the DefaultContext that get notified when logging. If there is already a registered writer with that name, an error is returned.

func ResetLogging

func ResetLogging()

ResetLogging iterates through the known modules and sets the levels of all to UNSPECIFIED, except for which is set to WARNING. The call also removes all writers in the DefaultContext and puts the original default writer back as the only writer.

func ResetWriters

func ResetWriters()

ResetWriters puts the list of writers back into the initial state.

type Config

type Config map[string]Level

Config is a mapping of logger module names to logging severity levels.

func ParseConfigString

func ParseConfigString(specification string) (Config, error)

ParseConfigString parses a logger configuration string into a map of logger names and their associated log level. This method is provided to allow other programs to pre-validate a configuration string rather than just calling ConfigureLoggers.

Logging modules are colon- or semicolon-separated; each module is specified as =. White space outside of module names and levels is ignored. The root module is specified with the name "".

As a special case, a log level may be specified on its own. This is equivalent to specifying the level of the root module, so "DEBUG" is equivalent to <root>=DEBUG

An example specification:

`<root>=ERROR; foo.bar=WARNING`

func (Config) String

func (c Config) String() string

String returns a logger configuration string that may be parsed using ParseConfigurationString.

type Context

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

Context produces loggers for a hierarchy of modules. The context holds a collection of hierarchical loggers and their writers.

func DefaultContext

func DefaultContext() *Context

DefaultContext returns the global default logging context.

func NewContext

func NewContext(rootLevel Level) *Context

NewLoggers returns a new Context with no writers set. If the root level is UNSPECIFIED, WARNING is used.

func (*Context) AddWriter

func (c *Context) AddWriter(name string, writer Writer) error

AddWriter adds a writer to the list to be called for each logging call. The name cannot be empty, and the writer cannot be nil. If an existing writer exists with the specified name, an error is returned.

func (*Context) ApplyConfig

func (c *Context) ApplyConfig(config Config)

ApplyConfig configures the logging modules according to the provided config.

func (*Context) CompleteConfig

func (c *Context) CompleteConfig() Config

CompleteConfig returns all the loggers and their defined levels, even if that level is UNSPECIFIED.

func (*Context) Config

func (c *Context) Config() Config

Config returns the current configuration of the Loggers. Loggers with UNSPECIFIED level will not be included.

func (*Context) GetLogger

func (c *Context) GetLogger(name string) Logger

GetLogger returns a Logger for the given module name, creating it and its parents if necessary.

func (*Context) RemoveWriter

func (c *Context) RemoveWriter(name string) (Writer, error)

RemoveWriter remotes the specified writer. If a writer is not found with the specified name an error is returned. The writer that was removed is also returned.

func (*Context) ReplaceWriter

func (c *Context) ReplaceWriter(name string, writer Writer) (Writer, error)

ReplaceWriter is a convenience method that does the equivalent of RemoveWriter followed by AddWriter with the same name. The replaced writer is returned.

func (*Context) ResetLoggerLevels

func (c *Context) ResetLoggerLevels()

ResetLoggerLevels iterates through the known logging modules and sets the levels of all to UNSPECIFIED, except for which is set to WARNING.

func (*Context) ResetWriters

func (c *Context) ResetWriters()

ResetWriters is generally only used in testing and removes all the writers.

func (*Context) Writer

func (c *Context) Writer(name string) Writer

Writer returns the named writer if one exists. If there is not a writer with the specified name, nil is returned.

type Entry

type Entry struct {
    // Level is the severity of the log message.
    Level Level
    // Module is the dotted module name from the logger.
    Module string
    // Filename is the full path the file that logged the message.
    Filename string
    // Line is the line number of the Filename.
    Line int
    // Timestamp is when the log message was created
    Timestamp time.Time
    // Message is the formatted string from teh log call.
    Message string
}

Entry represents a single log message.

type Level

type Level uint32

Level holds a severity level.

const (
    UNSPECIFIED Level = iota
    TRACE
    DEBUG
    INFO
    WARNING
    ERROR
    CRITICAL
)

The severity levels. Higher values are more considered more important.

func ParseLevel

func ParseLevel(level string) (Level, bool)

ParseLevel converts a string representation of a logging level to a Level. It returns the level and whether it was valid or not.

func (Level) Short

func (level Level) Short() string

Short returns a five character string to use in aligned logging output.

func (Level) String

func (level Level) String() string

String implements Stringer.

type Logger

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

A Logger represents a logging module. It has an associated logging level which can be changed; messages of lesser severity will be dropped. Loggers have a hierarchical relationship - see the package documentation.

The zero Logger value is usable - any messages logged to it will be sent to the root Logger.

func GetLogger

func GetLogger(name string) Logger

GetLogger returns a Logger for the given module name, creating it and its parents if necessary.

func (Logger) Child

func (logger Logger) Child(name string) Logger

Child returns the Logger whose module name is the composed of this Logger's name and the specified name.

func (Logger) Criticalf

func (logger Logger) Criticalf(message string, args ...interface{})

Criticalf logs the printf-formatted message at critical level.

func (Logger) Debugf

func (logger Logger) Debugf(message string, args ...interface{})

Debugf logs the printf-formatted message at debug level.

func (Logger) EffectiveLogLevel

func (logger Logger) EffectiveLogLevel() Level

EffectiveLogLevel returns the effective min log level of the receiver - that is, messages with a lesser severity level will be discarded.

If the log level of the receiver is unspecified, it will be taken from the effective log level of its parent.

func (Logger) Errorf

func (logger Logger) Errorf(message string, args ...interface{})

Errorf logs the printf-formatted message at error level.

func (Logger) Infof

func (logger Logger) Infof(message string, args ...interface{})

Infof logs the printf-formatted message at info level.

func (Logger) IsDebugEnabled

func (logger Logger) IsDebugEnabled() bool

IsDebugEnabled returns whether debugging is enabled at debug level.

func (Logger) IsErrorEnabled

func (logger Logger) IsErrorEnabled() bool

IsErrorEnabled returns whether debugging is enabled at error level.

func (Logger) IsInfoEnabled

func (logger Logger) IsInfoEnabled() bool

IsInfoEnabled returns whether debugging is enabled at info level.

func (Logger) IsLevelEnabled

func (logger Logger) IsLevelEnabled(level Level) bool

IsLevelEnabled returns whether debugging is enabled for the given log level.

func (Logger) IsTraceEnabled

func (logger Logger) IsTraceEnabled() bool

IsTraceEnabled returns whether debugging is enabled at trace level.

func (Logger) IsWarningEnabled

func (logger Logger) IsWarningEnabled() bool

IsWarningEnabled returns whether debugging is enabled at warning level.

func (Logger) LogCallf

func (logger Logger) LogCallf(calldepth int, level Level, message string, args ...interface{})

LogCallf logs a printf-formatted message at the given level. The location of the call is indicated by the calldepth argument. A calldepth of 1 means the function that called this function. A message will be discarded if level is less than the the effective log level of the logger. Note that the writers may also filter out messages that are less than their registered minimum severity level.

func (Logger) LogLevel

func (logger Logger) LogLevel() Level

LogLevel returns the configured min log level of the logger.

func (Logger) Logf

func (logger Logger) Logf(level Level, message string, args ...interface{})

Logf logs a printf-formatted message at the given level. A message will be discarded if level is less than the the effective log level of the logger. Note that the writers may also filter out messages that are less than their registered minimum severity level.

func (Logger) Name

func (logger Logger) Name() string

Name returns the logger's module name.

func (Logger) Parent

func (logger Logger) Parent() Logger

Parent returns the Logger whose module name is the same as this logger without the last period and suffix. For example the parent of the logger that has the module "a.b.c" is "a.b". The Parent of the root logger is still the root logger.

func (Logger) SetLogLevel

func (logger Logger) SetLogLevel(level Level)

SetLogLevel sets the severity level of the given logger. The root logger cannot be set to UNSPECIFIED level. See EffectiveLogLevel for how this affects the actual messages logged.

func (Logger) Tracef

func (logger Logger) Tracef(message string, args ...interface{})

Tracef logs the printf-formatted message at trace level.

func (Logger) Warningf

func (logger Logger) Warningf(message string, args ...interface{})

Warningf logs the printf-formatted message at warning level.

type TestWriter

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

TestWriter is a useful Writer for testing purposes. Each component of the logging message is stored in the Log array.

func (*TestWriter) Clear

func (writer *TestWriter) Clear()

Clear removes any saved log messages.

func (*TestWriter) Log

func (writer *TestWriter) Log() []Entry

Log returns a copy of the current logged values.

func (*TestWriter) Write

func (writer *TestWriter) Write(entry Entry)

Write saves the params as members in the TestLogValues struct appended to the Log array.

type Writer

type Writer interface {
    // Write writes a message to the Writer with the given level and module
    // name. The filename and line hold the file name and line number of the
    // code that is generating the log message; the time stamp holds the time
    // the log message was generated, and message holds the log message
    // itself.
    Write(entry Entry)
}

Writer is implemented by any recipient of log messages.

func NewMinimumLevelWriter

func NewMinimumLevelWriter(writer Writer, minLevel Level) Writer

NewMinLevelWriter returns a Writer that will only pass on the Write calls to the provided writer if the log level is at or above the specified minimum level.

func NewSimpleWriter

func NewSimpleWriter(writer io.Writer, formatter func(entry Entry) string) Writer

NewSimpleWriter returns a new writer that writes log messages to the given io.Writer formatting the messages with the given formatter.

func RemoveWriter

func RemoveWriter(name string) (Writer, error)

RemoveWriter removes the Writer identified by 'name' and returns it. If the Writer is not found, an error is returned.

func ReplaceDefaultWriter

func ReplaceDefaultWriter(writer Writer) (Writer, error)

ReplaceDefaultWriter is a convenience method that does the equivalent of RemoveWriter and then RegisterWriter with the name "default". The previous default writer, if any is returned.


Generated by godoc2md

More Repositories

1

ratelimit

Efficient token-bucket-based rate limiter package.
Go
2,679
star
2

juju

Orchestration engine that enables the deployment, integration and lifecycle management of applications at any scale, on any infrastructure (Kubernetes or otherwise).
Go
2,288
star
3

errors

Common juju errors and functions to annotate errors. Based on juju/errgo
Go
1,382
star
4

errgo

Error tracing and annotation.
Go
228
star
5

utils

General utility functions
Go
213
star
6

juju-gui

Juju-GUI is a web-based GUI for Juju <https://jujucharms.com/>.
JavaScript
182
star
7

fslock

Go
129
star
8

persistent-cookiejar

cookiejar is a fork of net/http/cookiejar that allows serialisation of the stored cookies
Go
113
star
9

python-libjuju

Python library for the Juju API
Python
59
star
10

cheatsheet

A Juju Quicksheet with some common usage examples
58
star
11

charm-championship

Submissions for the Juju Charm Championship
43
star
12

charm-tools

Tools for charm authors and maintainers
Python
42
star
13

httprequest

JSON-oriented HTTP server and client helpers
Go
38
star
14

mutex

Provides a named machine level mutex shareable between processes.
Go
28
star
15

cmd

A command line implementation framework
Go
27
star
16

plugins

Basic collection of the first few plugins for Juju
Python
27
star
17

gomaasapi

Go bindings for talking to MAAS
Go
27
star
18

pubsub

Publish and subscribe functionality within a single process in Go.
Go
25
star
19

gnuflag

GNU-compatible flag handling with a stdlib-like API for Go
Go
25
star
20

docs

Juju documentation, edited on https://discourse.charmhub.io/, and published on https://juju.is/docs
Python
23
star
21

ansiterm

Colored writers and tabwriters.
Go
22
star
22

terraform-provider-juju

A Terraform provider for Juju
Go
21
star
23

gocharm

Write your charms in Go!
Go
21
star
24

layer-index

Index of layers for building charms
Python
21
star
25

testing

Testing gocheck suites and checkers used across juju projects
Go
19
star
26

retry

The retry package encapsulates the mechanism around retrying commands.
Go
19
star
27

charm-helpers

Python
18
star
28

amulet

Testing harness and tools for Juju Charms
Python
17
star
29

zaputil

Utility functions related to the zap logging package
Go
16
star
30

charmstore

The charm store server.
Go
15
star
31

clock

Clock definition and a testing clock.
Go
13
star
32

charm

Parsing and testing Juju charms
Go
13
star
33

xml

A fork of the Go xml package with fixed marshaling
Go
11
star
34

worker

Utilities for handling long lived Go workers
Go
10
star
35

juju-academy

Learn to use Juju
JavaScript
10
star
36

mgosession

Session pooling for the mgo package
Go
10
star
37

juju-crashdump

Script to assist in gathering logs and other debugging info from a Juju model
Python
10
star
38

charmstore-client

Client for charmstore.
Go
9
star
39

juju-talks

Presentations about Juju, pull requests welcome!
HTML
9
star
40

js-libjuju

JavaScript API client for Juju
TypeScript
9
star
41

replicaset

Create and manage mongodb replicasets.
Go
8
star
42

firestealer

A command line tool for parsing Prometheus metrics
Python
8
star
43

zip

Fork of Go's zip package with append feature.
Go
8
star
44

httpgovernor

HTTP request concurrency limiter
Go
7
star
45

packaging

An abstraction of different linux packaging systems.
Go
6
star
46

chaos-monkey

A tool to instrument chaos into a Juju environment.
Python
6
star
47

names

A package to deal with juju names (services, units, machines, etc)
Go
6
star
48

schema

coerce dynamically typed data structures into known forms.
Go
6
star
49

hello-juju-charm

The charm for the hello-juju application.
Python
5
star
50

jujusvg

Generate svgs from Juju bundles and environment.
Go
5
star
51

theblues

Python library for the juju charmstore (v4)
Python
5
star
52

1.25-upgrade

Tools to upgrade and move a 1.25 environment to a 2.2.4+ controller
Go
4
star
53

jenkins-github-lander

Web service to aid in landing approved branches automatically with a final test run through jenkins.
Python
4
star
54

juju-tosca

Juju Tosca Translator
Python
4
star
55

go-oracle-cloud

Go client interfacing with the oracle IAAS cloud API.
Go
4
star
56

mgo

The MongoDB driver for Go
Go
3
star
57

aclstore

A simple persistent store for ACLs, with HTTP API
Go
3
star
58

txjuju

A Twisted-based Juju client
Python
3
star
59

bakeryjs

Javascript implementation of the Macaroon Bakery
TypeScript
3
star
60

qthttptest

Check that JSON HTTP endpoints respond appropriately; compatible with quicktest.
Go
3
star
61

juju-restore

Restore script for Juju controllers
Go
3
star
62

version

Go
3
star
63

collections

Deque and set implementations
Go
3
star
64

bundlechanges

A Go library to generate the list of changes required to deploy a bundle
Go
3
star
65

postgrestest

Go support for testing against a live Postgres database
Go
2
star
66

concurrency-limiter

Limit the number of asynchronous concurrent tasks running
JavaScript
2
star
67

juju-gui-charm

Charm for Juju GUI.
Python
2
star
68

autopilot-log-collector

Python
2
star
69

mgopurge

A tool to repair broken mgo/txn transaction references in a Juju MongoDB instance.
Go
2
star
70

httpprof

httpprof is a fork of net/http/pprof which works correctly when not at the server's root
Go
2
star
71

hello-juju

A simple application used to demonstrate juju relations.
HTML
2
star
72

blobstore

This package provides a Mongo GridFS-backed blob storage engine.
Go
2
star
73

mgoutil

A Go package holding utilities related to the mgo package
Go
2
star
74

lru

A Go implementation of a least-recently-used cache
Go
2
star
75

description

Describes the Juju 2.x and 3.x serialization format of a model
Go
2
star
76

charmrepo

Charm repositories and charmstore client packages
Go
2
star
77

webbrowser

Go helpers for interacting with Web browsers.
Go
2
star
78

fake-juju

A juju binary using the dummy provider for integration test purposes.
Go
2
star
79

juju-qa-jenkins

Jenkins configuration for Juju CI
Python
2
star
80

termserver

LXD image builder for the jujushell service
Makefile
1
star
81

rfc

Go implementations of various standards, particularly IETF RFCs.
Go
1
star
82

juju-bundlelib

A Python library for working with Juju bundles.
Python
1
star
83

idmclient

client for USSO to macaroons bridge server
Go
1
star
84

mgomonitor

prometheus stats for gopkg.in/mgo.v2
Go
1
star
85

jknife

jknife are juju db surgery tools - this should only be used with direction of a Juju engineer
Go
1
star
86

jasp

CSS
1
star
87

jujuapidoc

Generate information on the Juju API
Go
1
star
88

juju-controller

A Juju controller charm
Python
1
star
89

jaaslibjs

JavaScript library for interacting with the JAAS services
JavaScript
1
star
90

http

Juju wrapper for the standard go HTTP library.
Go
1
star
91

naturalsort

Sort strings according to natural sort order.
Go
1
star
92

charm-developer-docs

Documenting how to write a Juju charm
Shell
1
star
93

lxc

Fork of lxd/lxc to add Juju specific tweaks
Go
1
star
94

romulus

Go
1
star
95

usso

Go
1
star
96

juju-process-docker

a plugin to allow juju to interface with docker
Go
1
star
97

charm-base-images

Shell
1
star
98

proxy

A golang type for grouping information about proxy variables.
Go
1
star
99

jaas-monitor

Monitor all your jaas models (prototype)
Shell
1
star
100

os

Host OS and series abstractions for Go.
Go
1
star