• This repository has been archived on 21/Feb/2023
  • Stars
    star
    19
  • Rank 1,163,249 (Top 23 %)
  • Language
    Go
  • License
    MIT License
  • Created about 9 years ago
  • Updated over 5 years ago

Reviews

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

Repository Details

Gomol is a library for structured, multiple-output logging for Go with extensible logging outputs

gomol

GoDoc Build Status Code Coverage Go Report Card

Gomol (Go Multi-Output Logger) is an MIT-licensed structured logging library for Go. Gomol grew from a desire to have a structured logging library that could write to any number of outputs while also keeping a small in-band footprint.

Features

  • Attach meta-data to each log message with attributes
  • Multiple outputs at the same time
  • Pluggable Logger interface
  • Asynchronous logging so slow loggers won't slow down your application

Installation

Gomol can also be installed the standard way for Go:

go get github.com/aphistic/gomol
...
import "github.com/aphistic/gomol"

Vendoring is recommended!

Loggers

Gomol has a growing list of supported logging formats. The known loggers are listed below. If you have a logger you've written to support gomol and you'd like to add it to this list please either submit a pull request with the updated document or let me know and I can add it!

Other Usages

In addition to the loggers listed above, gomol can be used with other projects as well.

Examples

For brevity a lot of error checking has been omitted, be sure you do your checks!

This is a super basic example of adding a number of loggers and then logging a few messages:

package main

import (
	"github.com/aphistic/gomol"
	gc "github.com/aphistic/gomol-console"
	gg "github.com/aphistic/gomol-gelf"
)

func main() {
	// Add a console logger
	consoleCfg := gc.NewConsoleLoggerConfig()
	consoleLogger, _ := gc.NewConsoleLogger(consoleCfg)
	// Set the template to display the full message, including
	// attributes.
	consoleLogger.SetTemplate(gc.NewTemplateFull())
	gomol.AddLogger(consoleLogger)

	// Add a GELF logger
	gelfCfg := gg.NewGelfLoggerConfig()
	gelfCfg.Hostname = "localhost"
	gelfCfg.Port = 12201
	gelfLogger, _ := gg.NewGelfLogger(gelfCfg)
	gomol.AddLogger(gelfLogger)

	// Set some global attrs that will be added to all
	// messages automatically
	gomol.SetAttr("facility", "gomol.example")
	gomol.SetAttr("another_attr", 1234)

	// Configure gomol to add the filename and line number that the
	// log was generated from, the internal sequence number to help
	// with ordering events if your log system doesn't support a
	// small enough sub-second resolution, and set the size of the
	// internal queue (default is 10k messages).
	cfg := gomol.NewConfig()
	cfg.FilenameAttr = "filename"
	cfg.LineNumberAttr = "line"
	cfg.SequenceAttr = "sequence"
	cfg.MaxQueueSize = 50000
	gomol.SetConfig(cfg)

	// Initialize the loggers
	gomol.InitLoggers()
	defer gomol.ShutdownLoggers()

	// Create a channel on which to receive internal (asynchronous)
	// logger errors. This is optional, but recommended in order to
	// determine when logging may be dropping messages.
	ch := make(chan error)

	go func() {
		// This consumer is expected to be efficient as writes to 
		// the channel are blocking. If this handler is slow, the
		// user should add a buffer to the channel, or manually
		// queue and batch errors for processing.

		for err := range ch {
			fmt.Printf("[Internal Error] %s\n", err.Error())
		}
	}()

	gomol.SetErrorChan(ch)

	// Log some debug messages with message-level attrs
	// that will be sent only with that message
	for idx := 1; idx <= 10; idx++ {
		gomol.Dbgm(gomol.NewAttrsFromMap(map[string]interface{}{
			"msg_attr1": 4321,
		}), "Test message %v", idx)
	}
}

Fallback Logger

One feature gomol supports is the concept of a fallback logger. In some cases a logger may go unhealthy (a logger to a remote server, for example) and you want to log to a different logger to ensure log messages are not lost. The SetFallbackLogger method is available for these such instances.

A fallback logger will be triggered if any of the primary loggers goes unhealthy even if all others are fine. It's recommended the fallback logger not be added to the primary loggers or you may see duplicate messages. This does mean if multiple loggers are added as primary loggers and just one is unhealthy the fallback logger logger will be triggered.

To add a fallback logger there are two options. One is to use the default gomol instance (gomol.SetFallbackLogger()) and the other is to use the method on a Base instance:

import (
	"github.com/aphistic/gomol"
	"github.com/aphistic/gomol-console"
	"github.com/aphistic/gomol-json"
)

func main() {
	// Create a logger that logs over TCP using JSON
	jsonCfg := gomoljson.NewJSONLoggerConfig("tcp://192.0.2.125:4321")
	// Continue startup even if we can't connect initially
	jsonCfg.AllowDisconnectedInit = true
	jsonLogger, _ := gomoljson.NewJSONLogger(jsonCfg)
	gomol.AddLogger(jsonLogger)

	// Create a logger that logs to the console
	consoleCfg := gomolconsole.NewConsoleLoggerConfig()
	consoleLogger, _ := gomolconsole.NewConsoleLogger(consoleCfg)

	// Set the fallback logger to the console so if the
	// TCP JSON logger is unhealthy we still get logs
	// to stdout.
	_ = gomol.SetFallbackLogger(consoleLogger)

	gomol.InitLoggers()
	defer gomol.ShutdownLoggers()

	gomol.Debug("This is my message!")
}

More Repositories

1

cef3barebones

This is a bare-bones implementation of Chromium Embedded Framework 3. It's meant to help developers get off the ground with CEF3 and nothing more.
C++
35
star
2

libnbt

Please take a look at github.com/fragmer/fNbt as a continuation of this project, it's been rewritten for improved performance, reliability and ease of use. Original Description: A C# library for reading and writing Named Binary Tag (NBT) format files.
C#
20
star
3

golf

Client library written in Go for sending messages to Graylog Extended Log Format (GELF) servers. Allows per-message and global attributes to be attached to messages.
Go
9
star
4

go.Zamara

Go library for reading Starcraft II replay files.
Go
6
star
5

screeps-deployer

A GitHub action for deploying to the game Screeps
Go
6
star
6

softcopy

A document management server designed for families focused on ease of use and setup
Go
5
star
7

libminecraft

A C# library created to read and write Minecraft level files. It employs LibNbt to read the files and provides a type safe way to work with the files. NOTE: Currently halted until the Minecraft level format has stabilized.
C#
4
star
8

sweet

Sweet is a pluggable test runner capable of hooking into standard Go tests.
Go
4
star
9

hlbot

An old HL Server to IRC bot I wrote that has been rescued from SourceForge.
C++
2
star
10

boom

Boom is a Go library for easily handling tasks and the results of those tasks.
Go
2
star
11

matrix-synapse-docker

The Synapse Matrix homeserver Docker image with some extras installed
Dockerfile
2
star
12

docfs

A filesystem designed to make it easier to organize documents.
Go
2
star
13

consync

consync is a tool to help with managing Consul key/value data across multiple datacenters
Go
1
star
14

falconos

A toy operating system used to follow tutorials I find online and learn how things work.
Makefile
1
star
15

aoc2020

Advent of Code 2020!
Rust
1
star
16

why-i-like-rust

Materials from a presentation I did titled "Why I Like Rust"
CSS
1
star
17

aphos

A hobby operating system.
Assembly
1
star
18

negroni-requestid

Negroni middleware to add a randomly generated request ID to the request context and optionally add it as an X-Request-ID header.
Go
1
star
19

ServiceExample

An example Windows service written in C# laid out how I like in order to ease development and debugging. I created it for a friend but I figured I might as well put it online in case it helps anyone else.
C#
1
star
20

mciso

A utility to create isometric and top-down overview images of Minecraft levels in the mclevel format.
C#
1
star