Golang logging: Difference between revisions

From wikinotes
No edit summary
No edit summary
Line 12: Line 12:
</blockquote><!-- Documentation -->
</blockquote><!-- Documentation -->


= Example =
= Basics =
<blockquote>
<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">
import "os"
// customize default log's logformat
import "log"
log.SetFlags(log.Ldate|log.Ltime|log.Llongfile)


// params:
// log methods similar to 'fmt.*' methods
//   1. device you'd like to log to
log.Println("application started")  // log message
//   2. log-prefix of this logger
log.Fatalln("application exiting")  // os.Exit(1) after logged
//   3. log-formatting options
log.Panicln("application panicked") // panic() after logged
//
</syntaxhighlight>
var Logger = log.New(os.Stderr, "", log.Ldate|log.Ltime|log.Lshortfile)
</blockquote><!-- Basics -->
 
= LogLevels =
<blockquote>
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">
logFmt := log.Ldate|log.Ltime|log.Llongfile


func main() {
InfoLogger := log.New(os.Stderr, "INFO:", logFmt)
    Logger.Println("this is a test")
DebugLogger := log.New(os.Stderr, "DEBUG:", logFmt)
}
ErrorLogger := log.New(os.Stderr, "ERROR:", logFmt)
</syntaxhighlight>
</syntaxhighlight>
</blockquote><!-- Example -->
 
{{ TODO |
To silence logs, maybe redirect to <code>/dev/null</code>?
}}
</blockquote><!-- LogLevels -->

Revision as of 21:56, 18 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

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.

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

InfoLogger := log.New(os.Stderr, "INFO:", logFmt)
DebugLogger := log.New(os.Stderr, "DEBUG:", logFmt)
ErrorLogger := log.New(os.Stderr, "ERROR:", logFmt)

TODO:

To silence logs, maybe redirect to /dev/null?