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

Overview

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.

Issues
  • Format of log message and printf-like methods (not ~F)

    Format of log message and printf-like methods (not ~F)

    Thanks for that simple and wonderful logger! But I seen that module name isn't used and I decided to do it. I implemented this by adding ability to control of log messages format. Also, I think that printf-like methods should have 'f' suffix, not 'F'. I added methods with these names. These methods are aliases to methods with suffix 'F'.

    opened by qioalice 9
  • logger line

    logger line

    hi,

    #1 2018-01-18 00:07:37 log.go:25 ▶ WAR TransactionID=opcli InstancesID=main Message=This is test []

    it seems the line is not correct,the line should be the line the number when i use log.DebugF 、log.WarningF .. and so on ?

    opened by XieWeiXie 4
  • Add log level filter

    Add log level filter

    Adds the possibility to define the log level from which log messages should be outputted. e.g. if the log level is set to ErrorLevel only critical and error log messages are processed.

    Closes issues #14 and #4

    opened by mathiasjakob 2
  • Use lowercase f in formatting function names

    Use lowercase f in formatting function names

    Your project looks really nice!

    When reading the examples, I propose to streamline function names to correspond to the naming scheme of fmt, log and testing: fmt.Printf(), log.Printf(), t.Errorf() are all using lowercase f, whereas your package uses WarningF() DebugF() with capital Fs.

    Proposal: Use lowercase f in your package as well, e.g. Warningf()

    opened by chr4 1
  • Understanding the outcomes of Google Summer of Code

    Understanding the outcomes of Google Summer of Code

    Dear Amanpreet Singh,

    I am a Ph.D. student at the University of São Paulo (Brazil). We would like to understand how and how much Open Source Communities benefit from participating in Google Summer of Code (GSoC). We believe that your experience in GSoC is valuable and could help us achieve that. In a 1-minute questionnaire, we would like to know:

    Concerning the project entitled "Annotation Tool that extracts information and feed them on Wikidata" developed in GSoC 2014.

    1. Do you have a GitHub repository for the GSoC project? If so, could you provide us with the link to the project?

    2. Have you continued committing code or opening issues to the GSoC project after GSoC? (Yes / No) If so, code, issues or both?

    3. Have you continued committing code or opening issues to other OSS projects after GSoC? (Yes / No) If so, code, issues or both?

    4. Could we use aggregate data from your participation in GSoC and other OSS projects in our research?

    The following link contains a sample of our work and how we would use your data: https://ieeexplore.ieee.org/document/8094410/

    Regards,

    Jefferson

    opened by j3ffsilva 1
  • Enable Sourcegraph

    Enable Sourcegraph

    I want to use Sourcegraph for go-logger code search, browsing, and usage examples. Can an admin enable Sourcegraph for this repository? Just go to https://sourcegraph.com/github.com/apsdehal/go-logger. (It should only take 30 seconds.)

    Thank you!

    opened by tigerclawn82 1
  • [Feature request] Add support silencing priority levels

    [Feature request] Add support silencing priority levels

    It would be nice to be able to silence certain priority level logs. For example: error, notice, and info level logs could be silenced while critical, debug, and warning logs are still outputted.

    opened by danobi 1
  • %{time} formatting not working

    %{time} formatting not working

    The format option %{time} does not work without format description as you can see in this MWE:

    package main
    import (
        "os"
        "github.com/apsdehal/go-logger"
    )
    func main() {
        log, err := logger.New("test", 1, os.Stdout)
    	if err != nil {
    		panic(err) // Check for error
    	}
        log.SetFormat("%{time} [%{level}] %{message}")
        log.Debug("not working test")
        log.SetFormat("%{time:2006-01-02 15:04:05} [%{level}] %{message}")
        log.Debug("working test")
    }
    

    output is

     [DEBUG] not working test
    2018-07-04 00:52:12 [DEBUG] working test
    
    opened by lnxbil 0
  • Windows color

    Windows color

    Using this file:

    package main
    import "github.com/apsdehal/go-logger"
    func main () {
       aa, _ := logger.New(1, 1)
       aa.Warning("bbbbb")
    }
    

    I get this result:

    [33m#1 2019-06-14 06:39:31 log.go:8 ▶ WAR bbbbb [0m
    
    opened by ghost 1
Releases(1.3.0)
  • 1.3.0(May 15, 2019)

    It is possible to set log level filters now. See the main example in README to understand how it works. The default log level has been fixed as INFO so anything below INFO won't be printed now unless you fix the logging level. Please fix your code accordingly to not miss any debug information with this breaking change.

    Source code(tar.gz)
    Source code(zip)
Owner
Amanpreet Singh
Research Engineer @facebookresearch. Working on intersection of NLP, Vision and RL.
Amanpreet Singh
Golog is a logger which support tracing and other custom behaviors out of the box. Blazing fast and simple to use.

GOLOG Golog is an opinionated Go logger with simple APIs and configurable behavior. Why another logger? Golog is designed to address mainly two issues

Damiano Petrungaro 34 Jul 26, 2022
Convenient Logger interface and std logger wrapper

Convenient logger interface and wrapper around std logger Interface type Logger interface { Error(err error) Debugf(format string, args ...interface

Denis Mitrofanov 1 Nov 28, 2021
Logger - A thin wrapper of uber-go/zap logger for personal project

a thin wraper of uber-go/zap logger for personal project 0. thanks uber-go/zap B

tsingson 1 Jun 16, 2022
Very simple charts with some debug data for Go programs

debugcharts Go memory debug charts. This package uses Plotly chart library. It is open source and free for use. Installation go get -v -u github.com/m

Marko Kevac 477 Jul 25, 2022
Dead simple, super fast, zero allocation and modular logger for Golang

Onelog Onelog is a dead simple but very efficient JSON logger. It is one of the fastest JSON logger out there. Also, it is one of the logger with the

Francois Parquet 399 Jun 16, 2022
Simple Yet Powerful Logger

sypl sypl provides a Simple Yet Powerful Logger built on top of the Golang sypl. A sypl logger can have many Outputs, and each Output is responsible f

Sauce Labs 9 Apr 28, 2022
simple concurrent logger

XMUS-LOGGER pure golang logger compatible with golang io standards. USAGE : logOptions := logger.LoggerOptions{ LogLevel: 6, // read more about lo

amupxm [amir hossein mokarrami far] 5 Sep 19, 2021
🪵 A dead simple, pretty, and feature-rich logger for golang

?? lumber ?? A dead simple, pretty, and feature-rich logger for golang ?? Install ?? Logging Functions lumber.Success() lumber.Info() lumber.Debug() l

Matt Gleich 50 Jul 20, 2022
A simple logger API.

flog a simple logger API for Go program that save logs into a file. NOTE: This package is provided "as is" with no guarantee. Use it at your own risk

Iss Meftah 3 May 14, 2022
A simple Go JSON logger.

logger A simple JSON logger for Go. It uses a context.Context to store values which will then be logged along with each message. It is possible to rec

Shawn Milochik 2 Jul 25, 2022
A simple and super power logger for golang

The most powerfull and faster logger for golang powered by DC ?? What is this? W

Teo 6 Jun 26, 2022
A Simple logger for golang

go-logger Installation go get github.com/mo-taufiq/go-logger Quickstart package main import ( gologger "github.com/mo-taufiq/go-logger" ) func main

Moh Taufiqur Rohman 1 Jan 15, 2022
Simple Proof of Concept REST event logger.

REST Event Logger PoC I am working on this project intermittently. I have set myself a time limit of ~3hrs which includes the time to acquire and adap

Saad Ur Rahman 0 Feb 10, 2022
A simple to use log system, minimalist but with features for debugging and differentiation of messages

A simple to use log system, minimalist but with features for debugging and differentiation of messages

structy 4 Jan 27, 2022
A logger, for Go

Go-Log A logger, for Go! It's sort of log and code.google.com/p/log4go compatible, so in most cases can be used without any code changes. Breaking cha

Ian Kent 38 May 12, 2022
Loggly Hooks for GO Logrus logger

Loggly Hooks for Logrus Usage package main import ( "github.com/sirupsen/logrus" "github.com/sebest/logrusly" ) var logglyToken string = "YOUR_LOG

Sebest 27 Jul 27, 2021
A 12-factor app logger built for performance and happy development

logxi log XI is a structured 12-factor app logger built for speed and happy development. Simpler. Sane no-configuration defaults out of the box. Faste

Mario Gutierrez 348 Jun 25, 2022
A logger for Go SQL database driver without modify existing *sql.DB stdlib usage.

SQLDB-Logger A logger for Go SQL database driver without modify existing *sql.DB stdlib usage. Colored console writer output above only for sample/dev

Sarjono Mukti Aji 230 Aug 2, 2022
xlog is a logger for net/context aware HTTP applications

⚠️ Check zerolog, the successor of xlog. HTTP Handler Logger xlog is a logger for net/context aware HTTP applications. Unlike most loggers, xlog will

Olivier Poitrey 135 Nov 22, 2021