• Stars
    star
    286
  • Rank 139,338 (Top 3 %)
  • Language
    Go
  • License
    BSD 3-Clause "New...
  • Created over 9 years ago
  • Updated almost 5 years ago

Reviews

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

Repository Details

Simple logger for Go programs. Allows custom formats for messages.

go-logger

Build Status GoDoc

A simple go logger for easy logging in your programs. Allows setting custom format for messages.

Preview

Example Output

Install

go get github.com/apsdehal/go-logger

Use go get -u to update the package.

Example

Example program demonstrates how to use the logger. See below for formatting instructions.

package main

import (
	"github.com/apsdehal/go-logger"
	"os"
)

func main () {
	// Get the instance for logger class, "test" is the module name, 1 is used to
	// state if we want coloring
	// Third option is optional and is instance of type io.Writer, defaults to os.Stderr
	log, err := logger.New("test", 1, os.Stdout)
	if err != nil {
		panic(err) // Check for error
	}

	// Critically log critical
	log.Critical("This is Critical!")
	log.CriticalF("%+v", err)
	// You can also use fmt compliant naming scheme such as log.Criticalf, log.Panicf etc
	// with small 'f'
	
	// Debug
	// Since default logging level is Info this won't print anything
	log.Debug("This is Debug!")
	log.DebugF("Here are some numbers: %d %d %f", 10, -3, 3.14)
	// Give the Warning
	log.Warning("This is Warning!")
	log.WarningF("This is Warning!")
	// Show the error
	log.Error("This is Error!")
	log.ErrorF("This is Error!")
	// Notice
	log.Notice("This is Notice!")
	log.NoticeF("%s %s", "This", "is Notice!")
	// Show the info
	log.Info("This is Info!")
	log.InfoF("This is %s!", "Info")

	log.StackAsError("Message before printing stack");

	// Show warning with format
	log.SetFormat("[%{module}] [%{level}] %{message}")
	log.Warning("This is Warning!") // output: "[test] [WARNING] This is Warning!"
	// Also you can set your format as default format for all new loggers
	logger.SetDefaultFormat("%{message}")
	log2, _ := logger.New("pkg", 1, os.Stdout)
	log2.Error("This is Error!") // output: "This is Error!"

	// Use log levels to set your log priority
	log2.SetLogLevel(DebugLevel)
	// This will be printed
	log2.Debug("This is debug!")
	log2.SetLogLevel(WarningLevel)
	// This won't be printed
	log2.Info("This is an error!")
}

Formatting

By default all log messages have format that you can see above (on pic). But you can override the default format and set format that you want.

You can do it for Logger instance (after creating logger) ...

log, _ := logger.New("pkgname", 1)
log.SetFormat(format)

... or for package

logger.SetDefaultFormat(format)

If you do it for package, all existing loggers will print log messages with format that these used already. But all newest loggers (which will be created after changing format for package) will use your specified format.

But anyway after this, you can still set format of message for specific Logger instance.

Format of log message must contains verbs that represent some info about current log entry. Ofc, format can contain not only verbs but also something else (for example text, digits, symbols, etc)

Format verbs:

You can use the following verbs:

%{id}           - means number of current log message
%{module}       - means module name (that you passed to func New())
%{time}			- means current time in format "2006-01-02 15:04:05"
%{time:format}	- means current time in format that you want
					(supports all formats supported by go package "time")
%{level}		- means level name (upper case) of log message ("ERROR", "DEBUG", etc)
%{lvl}			- means first 3 letters of level name (upper case) of log message ("ERR", "DEB", etc)
%{file} 		- means name of file in what you wanna write log
%{filename}		- means the same as %{file}
%{line}			- means line number of file in what you wanna write log
%{message}		- means your log message

Non-existent verbs (like %{nonex-verb} or %{}) will be replaced by an empty string. Invalid verbs (like %{inv-verb) will be treated as plain text.

Tests

Run:

  • go test logger to run test on logger.
  • go test -bench=. for benchmarks.

Thanks

Thanks goes to all go-loggers out there which I used as reference.

Contributors

Following contributors have made major contributions to go-logger:

License

The BSD 3-Clause license, the same as the Go language.

More Repositories

1

awesome-ctf

A curated list of CTF frameworks, libraries, resources and softwares
JavaScript
8,899
star
2

Link

A PHP router that helps you create webapps and APIs effortlessly
PHP
280
star
3

gym-starcraft

StarCraft: BroodWars OpenAI Gym environment
Python
79
star
4

Konsoole

HTTP Monitoring Console written in Go
Go
65
star
5

Face-Recognition

Face Recognition project in PyTorch using CNNs
Python
38
star
6

HackPy

A collection of notes and script that will help you learn basics of hacking with Python
Python
34
star
7

Flappy-Bird-Servo-Automation

Flappy Bird Automation using RL and Servo
JavaScript
28
star
8

qunit-migrate

Migrate old QUnit tests to 2.x. Uses regex and ASTs to convert old QUnit code.
JavaScript
17
star
9

structured-query-engine

Elasticsearch like search engine supporting real time indexing and querying
Python
13
star
10

hm_example_mmf

The Hateful Memes Challenge example code using MMF
Python
13
star
11

ic3net-envs

Environments with IC3Net paper
Python
12
star
12

torrent-to-magnet

Takes a torrent file and returns it's magnet uri
JavaScript
9
star
13

flava-tutorials

Tutorials for FLAVA model https://arxiv.org/abs/2112.04482
Jupyter Notebook
9
star
14

Limelight

A light toned, justifying theme for Jekyll
CSS
8
star
15

movie-recommendations

Movie Recommendations Application based on Structured Query Engine
Python
7
star
16

Heuristics-Problem-Solving

Algorithms for Heuristics course at NYU Fall 2016
Python
6
star
17

Zap

Minimalistic python based Wikipedia article's PPT generator
Python
6
star
18

spaces-to-tabs

Convert spaces to tabs in your files
JavaScript
5
star
19

Crunch

A mobile app that lets you get most out of Muzi
JavaScript
4
star
20

nli-batch-optimizations

Better convergence speeds for NLI task
Python
4
star
21

Shortest-Adversarial-Path-Architecture

Architecture for Shortest Adversarial Path
JavaScript
3
star
22

SPOJ

SPOJ solutions
C++
3
star
23

Cluster

Repo for Mesosphere Challenge
JavaScript
3
star
24

WikidataAnnotationFeeder

A plugin based on Pundit that help you create annotations and feed them on Wikidata.
JavaScript
3
star
25

apsdehal.github.io

Personal Blog
CSS
2
star
26

mp3-length

NPM module for calculating length of a mp3 file
JavaScript
2
star
27

blackjack

A simple JS and HTMl Blackjack game.
JavaScript
2
star
28

Programming-Languages-Assignments

Programming Languages Assignments
TeX
2
star
29

string-constants

String definitions for easy use
JavaScript
2
star
30

alexa-skill-math-hero

An alexa skill for playing multiple choice mathematics questions trivia
JavaScript
2
star
31

lein-clj-service

Lein template for a clojure service.
Clojure
2
star
32

PyScripts

Python
1
star
33

ds-queue

Simple Queue Data Structure.
JavaScript
1
star
34

Laravel-test-app

Test app made to learn Laravel
PHP
1
star
35

Opti.js

Registry for tracking instantiated models
JavaScript
1
star
36

att.js

Helps in easy binding of events to dynamic html.
JavaScript
1
star
37

Project

1
star