So you always leave a note

Overview

jWalterWeatherman

Seamless printing to the terminal (stdout) and logging to a io.Writer (file) that’s as easy to use as fmt.Println.

and_that__s_why_you_always_leave_a_note_by_jonnyetc-d57q7um Graphic by JonnyEtc

JWW is primarily a wrapper around the excellent standard log library. It provides a few advantages over using the standard log library alone.

  1. Ready to go out of the box.
  2. One library for both printing to the terminal and logging (to files).
  3. Really easy to log to either a temp file or a file you specify.

I really wanted a very straightforward library that could seamlessly do the following things.

  1. Replace all the println, printf, etc statements thoughout my code with something more useful
  2. Allow the user to easily control what levels are printed to stdout
  3. Allow the user to easily control what levels are logged
  4. Provide an easy mechanism (like fmt.Println) to print info to the user which can be easily logged as well
  5. Due to 2 & 3 provide easy verbose mode for output and logs
  6. Not have any unnecessary initialization cruft. Just use it.

Usage

Step 1. Use it

Put calls throughout your source based on type of feedback. No initialization or setup needs to happen. Just start calling things.

Available Loggers are:

  • TRACE
  • DEBUG
  • INFO
  • WARN
  • ERROR
  • CRITICAL
  • FATAL

These each are loggers based on the log standard library and follow the standard usage. Eg.

    import (
        jww "github.com/spf13/jwalterweatherman"
    )

    ...

    if err != nil {

        // This is a pretty serious error and the user should know about
        // it. It will be printed to the terminal as well as logged under the
        // default thresholds.

        jww.ERROR.Println(err)
    }

    if err2 != nil {
        // This error isn’t going to materially change the behavior of the
        // application, but it’s something that may not be what the user
        // expects. Under the default thresholds, Warn will be logged, but
        // not printed to the terminal. 

        jww.WARN.Println(err2)
    }

    // Information that’s relevant to what’s happening, but not very
    // important for the user. Under the default thresholds this will be
    // discarded.

    jww.INFO.Printf("information %q", response)

NOTE: You can also use the library in a non-global setting by creating an instance of a Notebook:

notepad = jww.NewNotepad(jww.LevelInfo, jww.LevelTrace, os.Stdout, ioutil.Discard, "", log.Ldate|log.Ltime)
notepad.WARN.Println("Some warning"")

Why 7 levels?

Maybe you think that 7 levels are too much for any application... and you are probably correct. Just because there are seven levels doesn’t mean that you should be using all 7 levels. Pick the right set for your needs. Remember they only have to mean something to your project.

Step 2. Optionally configure JWW

Under the default thresholds :

  • Debug, Trace & Info goto /dev/null
  • Warn and above is logged (when a log file/io.Writer is provided)
  • Error and above is printed to the terminal (stdout)

Changing the thresholds

The threshold can be changed at any time, but will only affect calls that execute after the change was made.

This is very useful if your application has a verbose mode. Of course you can decide what verbose means to you or even have multiple levels of verbosity.

    import (
        jww "github.com/spf13/jwalterweatherman"
    )

    if Verbose {
        jww.SetLogThreshold(jww.LevelTrace)
        jww.SetStdoutThreshold(jww.LevelInfo)
    }

Note that JWW's own internal output uses log levels as well, so set the log level before making any other calls if you want to see what it's up to.

Setting a log file

JWW can log to any io.Writer:

    jww.SetLogOutput(customWriter) 

More information

This is an early release. I’ve been using it for a while and this is the third interface I’ve tried. I like this one pretty well, but no guarantees that it won’t change a bit.

I wrote this for use in hugo. If you are looking for a static website engine that’s super fast please checkout Hugo.

Comments
  • Reworked to enable instantiation

    Reworked to enable instantiation

    I reworked JWW into a simple Notepad structure that more or less handle all the job by itself.

    The old interface of JWW is almost conserved, using a Notepad created in the init() and whose loggers are linked to exported vars, and relinked when changes occurs. I'm not really satisfied by this solution, but it's simple and efficient, and leave the external API clean.

    There is one API break, that is to take a io.Writer instead of a path for the log output. I feel it simpler and it evacuate the need to check for errors in the lib, and enable the end-user to do some really cool things quite simply (like logging to a database, etc).

    I also enabled the user to choose flags and an optional prefix, like the original log.Logger struct… it is useful to distinguish two Notepad's outputs.

    opened by elwinar 8
  • Unusual camelCase repository name breaks vgo

    Unusual camelCase repository name breaks vgo

    The x/vgo prototype enforces strict casing on imports. spf13/viper imports spf13/jwalterweatherman, which is not the same casing as the github repo. This breaks importing the library.

    Arguably vgo should not be enforcing case. However, even you, the author, don't use the correct case, which suggests to me maybe in this case the github repo should just be renamed to what people actually import it as. WDYT?

    opened by danderson 7
  • Return filename from UseTempLogFile()

    Return filename from UseTempLogFile()

    This is related to a comment that @owenwaller left in his updated hugo/utils_test.go: https://github.com/spf13/hugo/pull/818

    Is modifying UseTempLogFile() so that it returns the temp filename a change you would support? If so I can make a pull request.

    opened by mohae 5
  • Default value for nested key

    Default value for nested key

    The default settings do not work correctly for nested key. My patch (viper.go):

    // Test for nested config parameter
        if strings.Contains(key, v.keyDelim) {
            path := strings.Split(key, v.keyDelim)
            source := v.find(path[0])
            if source != nil {
                if reflect.TypeOf(source).Kind() == reflect.Map {
                    val := v.searchMap(cast.ToStringMap(source), path[1:])
                    if val != nil {
                        jww.TRACE.Println(key, "found in nested config:", val)
                        return val
                    }
                }
            }
        }
    
    opened by seniorGolang 2
  • Fix function comments based on best practices from Effective Go

    Fix function comments based on best practices from Effective Go

    Hi, we updated some exported function comments based on best practices from Effective Go. It’s admittedly a relatively minor fix up. Does this help you?

    opened by CodeLingoTeam 1
  • What happened to SetLogFile?

    What happened to SetLogFile?

        switch config.GetInt("LogLevel") {
    

    25 case 0: 26 jww.SetLogThreshold(jww.LevelError) 27 jww.SetStdoutThreshold(jww.LevelWarn) 28 case 1: 29 jww.SetLogThreshold(jww.LevelWarn) 30 jww.SetStdoutThreshold(jww.LevelInfo) 31 case 2: 32 jww.SetLogThreshold(jww.LevelInfo) 33 jww.SetStdoutThreshold(jww.LevelInfo) 34 case 3: 35 jww.SetLogThreshold(jww.LevelDebug) 36 jww.SetStdoutThreshold(jww.LevelDebug) 37 default: 38 jww.FATAL.Println("Invalid debug level specified:", config.GetInt("LogLevel")) 39 } 40 jww.SetLogFile(config.GetString("LogFile"))

    Results in a ./archit.go:40: undefined: jwalterweatherman.SetLogFile compilation error. All the other functions appear to compile fine.

    opened by goarchit 1
  • Output caller's file name and line at FEEDBACK

    Output caller's file name and line at FEEDBACK

    FEEDBACK logger always outputs this logger's file name and line e.g.

    thatswhyyoualwaysleaveanote.go:175 (FEEDBACK.Println) thatswhyyoualwaysleaveanote.go:183 (FEEDBACK.Printf)

    to a log file.

    Instead of it, this makes FEEDBACK logger output its caller's file name and line to a log file to provide more useful information.

    opened by tatsushid 1
  • Move internal output to INFO level

    Move internal output to INFO level

    Prevent client applications from having to deal with text being forced to their stdout by using INFO rather than fmt for output.

    I wanted to prevent JWW from output text in my application, this seemed like the easiest way. The other idea I had was a SilenceInternalOutput() method which would disable any fmt.Println() calls, while not breaking any existing applications which might enjoy the fact that they were getting "Logging to file ..." messages in their stdout. Would be happy to rework to that if preferred.

    opened by joshproehl 1
  • Added Log Flag set API

    Added Log Flag set API

    The logging flag was fixed. Set it as default

    (log.Ldate|log.Ltime|log.Lshortfile)
    

    So I have added an API to set the Flag as per requirement.

    func SetLogFlag(flags int)
    

    And added a abstraction over log flags:

    DATE     = log.Ldate
    TIME     = log.Ltime
    SFILE    = log.Lshortfile
    LFILE    = log.Llongfile
    MSEC     = log.Lmicroseconds
    
    opened by s8sg 1
  • Level LOG and FEEDBACK

    Level LOG and FEEDBACK

    Hello! Looking at source code for the jww library I've seen 2 more levels ( LOG and FEEDBACK ) available ( aparte from the 7 explained in readme ).

    Is is possible to set log threshold to one of these?

    Thanks for the feedback ( and your work )!

    opened by endorama 1
  • Add a LogListener option to Notepad

    Add a LogListener option to Notepad

    For clients using the "log counting" feature, this will be slightly breaking. But it adds lots of flexibility which should make it worth while.

    Now you can supply one or more LogListener funcs when creating a new Notepad. Typical use cases would be to capture ERROR logs in unit tests, and to count log statements. A listener for log counting is provided, see the LogCounter func.

    If you want to add listeners to the global logger, see SetLogListeners.

    opened by bep 0
  • add colored output

    add colored output

    Adds colored output to stdout. Doesn't support file-loggers atm (you'll get this [DEBUG] debug.go:16: DEBUG, I don't know how to use the old prefixes when writing to a file)

    Exposes a method notepad.UseColor(), UseColor() and a parameter in NewNotepad.

    With colors:

    Screen Shot 2021-05-04 at 23 55 41

    Also exposes the colors so people can use them in their messages, if they wish. (jww.DebugColor.Println("color"))

    opened by stingalleman 2
  • Overwrite level/threshold strings

    Overwrite level/threshold strings

    I'd like to align my console log by making all log levels four characters wide. It would be nice to make the prefixes map public API, preferably per notepad.

    opened by andig 0
  • Fix function comments based on best practices from Effective Go

    Fix function comments based on best practices from Effective Go

    Hi, we updated some exported function comments based on best practices from Effective Go. It’s admittedly a relatively minor fix up. Does this help you?

    opened by CodeLingoTeam 1
Releases(v1.1.0)
Owner
Steve Francia
@golang product lead at @google • Author, Speaker, Developer • Creator of @gohugoio, Cobra, Viper & spf13-vim • former @docker & @mongodb
Steve Francia
With this package you can create your own syslog server with your own handlers for different kind of syslog messages

Using this library you can easy implement your own syslog server that: Can listen on multiple UDP ports and unix domain sockets. Can pass parsed syslo

Michał Derkacz 67 Nov 9, 2022
Parametrized JSON logging library in Golang which lets you obfuscate sensitive data and marshal any kind of content.

Noodlog Summary Noodlog is a Golang JSON parametrized and highly configurable logging library. It allows you to: print go structs as JSON messages; pr

Gyoza Tech 42 Oct 27, 2022
Pixie gives you instant visibility by giving access to metrics, events, traces and logs without changing code.

Pixie gives you instant visibility by giving access to metrics, events, traces and logs without changing code.

Pixie Labs 4.1k Jan 4, 2023
Gowl is a process management and process monitoring tool at once. An infinite worker pool gives you the ability to control the pool and processes and monitor their status.

Gowl is a process management and process monitoring tool at once. An infinite worker pool gives you the ability to control the pool and processes and monitor their status.

Hamed Yousefi 40 Nov 10, 2022
ChangeTower is intended to help you watch changes in webpages and get notified of any changes written in Go

ChangeTower is intended to help you watch changes in webpages and get notified of any changes written in Go

The Cats 34 Nov 17, 2022
You can send massage to Discord, Slack and Telegram

introduction This package divided into three different packages which includes Telegram, Slack and Discord. Let's begin with Discord Discord To use di

Amir Salehi 0 Dec 7, 2021
Filez - A tiny package showing you File info

filez A tiny package showing you File info Install go get -v github.com/Cne3Rd/f

Mukaila Samsondeen 1 Feb 4, 2022
Felix Geisendörfer 28 Feb 9, 2022
Leave Discord servers using the folder names.

leavemealone ------------ Leave Discord servers using the folder names. Usage ----- 1. `export TOKEN="<token>"` 2. `go run . <folder_name>` 3. Chec

null 5 Feb 4, 2022
EasyDecisionMakingBot - Telegram bot to leave decisions to fate

Easy Decision Making Bot This is a Telegram bot to leave decisions to fate. You

Alessio Greggi 0 Jan 16, 2022
An always-on framework that performs end-to-end functional network testing for reachability, latency, and packet loss

Arachne Arachne is a packet loss detection system and an underperforming path detection system. It provides fast and easy active end-to-end functional

Uber Open Source 370 Dec 31, 2022
This is a very simple web-app which simply always returns HTTP status code 200

Responder This is a very simple web-app which simply always returns HTTP status code 200. It will also wait for an amount of time which can be set in

Jacob Palecek 1 Dec 14, 2021
Always use a slice., Dave Cheney

Golang Resources Why Go? Getting Started Directory Structure Error Handling Modules OOP Constructors Design Patterns Architecture & Best Practices SOL

Tudor Hulban 4 Dec 15, 2022
A note taking app, that you can draw in, syncs to the cloud, and is on most platforms!

About NotDraw About · How to contribute · How to run · Trello · FAQ This is achived because I dont want to work on it anymore Structure Codebase Descr

YummyOreo 1 Jul 11, 2022
A note taking app, that you can draw in, syncs to the cloud, and is on most platforms!

About NoteDraw About · How to contribute · How to run Structure Codebase Description SRC The sorce code for the client side (Go) Branches Only Ones th

YummyOreo 1 Jul 11, 2022
A very simple note-taking CLI you can use from the terminal that uses a SQLite DB to persist, and query, notes.

Note Logger Summary A very simple note-taking CLI you can use from the terminal that uses a SQLite DB to persist, and query, notes. Building/Installin

Nicholas Page 3 Apr 14, 2022
Go models of Note, Scale, Chord and Key

gopkg.in/music-theory.v0 Music theory models in Go There's an example command-line utility music-theory.go to demo the libraries, with a bin/ wrapper.

Music Theory 415 Dec 10, 2022
Music recognition bot for Reddit powered by audd.io. Note that the code currently needs some cleaning up and doesn't follow the best practices.

Music recognition bot for Reddit u/auddbot identifies music on Reddit. When someone mentions it or writes a question like "what's the song", it sends

AudD 287 Dec 30, 2022
The Markdown-based note-taking app that doesn't suck.

Notable I couldn't find a note-taking app that ticked all the boxes I'm interested in: notes are written and rendered in GitHub Flavored Markdown, no

Notable 20.7k Jan 2, 2023
The note-tinygo Go library for communicating with Blues Wireless Notecard via serial or I²C

Blues Wireless The note-tinygo Go library for communicating with Blues Wireless Notecard via serial or I²C. This library allows you to control a Notec

Blues Inc 3 Nov 29, 2021