Golang logging: Difference between revisions
From wikinotes
No edit summary |
No edit summary |
||
Line 12: | Line 12: | ||
</blockquote><!-- Documentation --> | </blockquote><!-- Documentation --> | ||
= | = 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"> | ||
// 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 --> | |||
= 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 | |||
InfoLogger := log.New(os.Stderr, "INFO:", logFmt) | |||
DebugLogger := log.New(os.Stderr, "DEBUG:", logFmt) | |||
ErrorLogger := log.New(os.Stderr, "ERROR:", logFmt) | |||
</syntaxhighlight> | </syntaxhighlight> | ||
</blockquote><!-- | |||
{{ 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
?