Go Package log: Difference between revisions
Jump to navigation
Jump to search
Line 45: | Line 45: | ||
===Log to a File=== | ===Log to a File=== | ||
<syntaxhighlight lang='go'> | |||
import ( | |||
"log" | |||
"os" | |||
) | |||
... | |||
func init() { | |||
// change the device for logging to a custom file | |||
fileName := "/tmp/somefile.log" | |||
f, err := os.Create(fileName) | |||
if err != nil { | |||
fmt.Printf("failed to open log file %s for writing\n", fileName) | |||
... | |||
} else { | |||
log.SetOutput(f) | |||
} | |||
} | |||
</syntaxhighlight > |
Revision as of 01:26, 19 December 2023
External
Internal
Overview
The "log" package provides support for logging messages to stdout, stderr or custom devices.
import (
"log"
)
...
log.Printf("something %s\n", "else")
Elements
- log.Fatal: Fatal is equivalent to Print() followed by a call to os.Exit(1).
Recipes
Changing the Logging Device
By default, the logger is set to write to stderr. To change that:
Log to stdout
import (
"log"
"os"
)
...
func init() {
// change the device for logging to stdout
log.SetOutput(os.Stdout)
}
Log to a File
import (
"log"
"os"
)
...
func init() {
// change the device for logging to a custom file
fileName := "/tmp/somefile.log"
f, err := os.Create(fileName)
if err != nil {
fmt.Printf("failed to open log file %s for writing\n", fileName)
...
} else {
log.SetOutput(f)
}
}