Golang logging: Difference between revisions

From wikinotes
(Created page with "Logging is a standardized format of writing progress/debug info. = Example = <blockquote> <syntaxhighlight lang="go"> // ./logger.go package main import "os" import "log" // params: // 1. device you'd like to log to // 2. log-prefix of this logger // 3. log-formatting options // var Logger = log.New(os.Stderr, "", log.Ldate|log.Ltime|log.Lshortfile) </syntaxhighlight> <syntaxhighlight lang="go"> // ./main.go package main func main() { Logger.Println("th...")
 
 
(8 intermediate revisions by the same user not shown)
Line 1: Line 1:
Logging is a standardized format of writing progress/debug info.
Logging is a standardized format of writing progress/debug info.


= Example =
= Documentation =
<blockquote>
<blockquote>
{| class="wikitable"
|-
| <code>log</code> || https://pkg.go.dev/log
|-
| logfmt flags || https://pkg.go.dev/log#pkg-constants
|-
|}
</blockquote><!-- Documentation -->
= Basics =
<blockquote>
Go creates a logger that logs to stderr by default.<br>
If you like, you can modify it's logformat.<br>
There are no log-levels by default.


<syntaxhighlight lang="go">
<syntaxhighlight lang="go">
// ./logger.go
// customize default log's logformat
log.SetFlags(log.Ldate|log.Ltime|log.Llongfile)
 
// log methods similar to 'fmt.*' methods
log.Println("application started")  // log message
log.Fatalln("application exiting")  // os.Exit(1) after logged
log.Panicln("application panicked") // panic() after logged
</syntaxhighlight>
</blockquote><!-- Basics -->


package main
= LogLevels =
<blockquote>
{{ NOTE |
[https://github.com/go-xorm/xorm/blob/master/logger.go xorm] has a really nice logger implementation }}
 
Go doesn't provide log-levels, but you can create separate loggers to implement this yourself.<br>
You don't need to do this in every file, log-format flags indicating filepath will use the correct path where it is called from.


<syntaxhighlight lang="go">
import "os"
import "os"
import "io/ioutil"
import "log"
import "log"


// params:
logFmt := log.Ldate|log.Ltime|log.Llongfile
//  1. device you'd like to log to
 
//  2. log-prefix of this logger
InfoLogger := log.New(os.Stderr, "INFO: ", logFmt)
//  3. log-formatting options
ErrorLogger := log.New(os.Stderr, "ERROR: ", logFmt)
//
DebugLogger := log.New(ioutil.Discard, "DEBUG: ", logFmt) // redirects to /dev/null
var Logger = log.New(os.Stderr, "", log.Ldate|log.Ltime|log.Lshortfile)
</syntaxhighlight>
</syntaxhighlight>
{{ expand
| Sample Implementation
|


<syntaxhighlight lang="go">
<syntaxhighlight lang="go">
// ./main.go
package main
 
import "log"
import "os"
import "io/ioutil"
 
var (
    LogDebug *log.Logger
    LogInfo *log.Logger
    LogWarn *log.Logger
    LogError *log.Logger
)
 
func setupLog() {
    debug_writer := ioutil.Discard
    info_writer := ioutil.Discard
 
    for _, arg := range os.Args[1:] {
        switch arg {
        case "-v", "--verbose":
            info_writer = os.Stderr
        case "-vv", "--very-verbose":
            info_writer = os.Stderr
            debug_writer = os.Stderr
        }
    }
    logFmt := log.Ldate|log.Ltime|log.Llongfile
 
    LogDebug = log.New(debug_writer, "DEBUG: ", logFmt)
    LogInfo = log.New(info_writer, "INFO: ", logFmt)
    LogWarn = log.New(os.Stderr, "WARN: ", logFmt)
    LogError = log.New(os.Stderr, "ERROR: ", logFmt)
}


package main


func main() {
func main() {
     Logger.Println("this is a test")
     setupLog()
 
    LogWarn.Println("high memory usage")
    LogInfo.Println("application started")
    LogDebug.Println("preparing for error...")
    LogError.Println("an error was encountered")
}
}
</syntaxhighlight>
</syntaxhighlight>


Then on your commandline
<syntaxhighlight lang="bash">
<syntaxhighlight lang="bash">
go run main.go logger.go  # build/run
go build main.go     # prints            warn/error
go build main.go -v # prints      info/warn/error
go build main.go -vv # prints debug/info/warn/error
</syntaxhighlight>
</syntaxhighlight>
</blockquote><!-- Example -->
 
}}
</blockquote><!-- LogLevels -->

Latest revision as of 02:59, 20 June 2022

Logging is a standardized format of writing progress/debug info.

Documentation

log https://pkg.go.dev/log
logfmt flags https://pkg.go.dev/log#pkg-constants

Basics

Go creates a logger that logs to stderr by default.
If you like, you can modify it's logformat.
There are no log-levels by default.

// customize default log's logformat
log.SetFlags(log.Ldate|log.Ltime|log.Llongfile)

// log methods similar to 'fmt.*' methods
log.Println("application started")  // log message
log.Fatalln("application exiting")  // os.Exit(1) after logged
log.Panicln("application panicked") // panic() after logged

LogLevels

NOTE:

xorm has a really nice logger implementation

Go doesn't provide log-levels, but you can create separate loggers to implement this yourself.
You don't need to do this in every file, log-format flags indicating filepath will use the correct path where it is called from.

import "os"
import "io/ioutil"
import "log"

logFmt := log.Ldate|log.Ltime|log.Llongfile

InfoLogger := log.New(os.Stderr, "INFO: ", logFmt)
ErrorLogger := log.New(os.Stderr, "ERROR: ", logFmt)
DebugLogger := log.New(ioutil.Discard, "DEBUG: ", logFmt)  // redirects to /dev/null

Sample Implementation


package main

import "log"
import "os"
import "io/ioutil"

var (
    LogDebug *log.Logger
    LogInfo *log.Logger
    LogWarn *log.Logger
    LogError *log.Logger
)

func setupLog() {
    debug_writer := ioutil.Discard
    info_writer := ioutil.Discard

    for _, arg := range os.Args[1:] {
        switch arg {
        case "-v", "--verbose":
            info_writer = os.Stderr
        case "-vv", "--very-verbose":
            info_writer = os.Stderr
            debug_writer = os.Stderr
        }
    }
    logFmt := log.Ldate|log.Ltime|log.Llongfile

    LogDebug = log.New(debug_writer, "DEBUG: ", logFmt)
    LogInfo = log.New(info_writer, "INFO: ", logFmt)
    LogWarn = log.New(os.Stderr, "WARN: ", logFmt)
    LogError = log.New(os.Stderr, "ERROR: ", logFmt)
}


func main() {
    setupLog()

    LogWarn.Println("high memory usage")
    LogInfo.Println("application started")
    LogDebug.Println("preparing for error...")
    LogError.Println("an error was encountered")
}

Then on your commandline

go build main.go     # prints            warn/error
go build main.go -v  # prints       info/warn/error
go build main.go -vv # prints debug/info/warn/error