Logging:
Logging
suggest changeLogging is a very deep subject because different programs have different logging requirements.
Logging with fmt.Printf and fmt.Fprintf
The simplest way to log is to write to standard output (stdout):
fmt.Printf("Logging to %s\n", "stdout")
To write to standard error (stderr):
fmt.Fprintf(os.Stderr, "Logging to %s\n", "stderr")
Logging with log package
Standard package log offers more functionality:
log.Printf("Logging")
log.Printf("Second line\n")
2020/07/12 07:24:09 Logging
2020/07/12 07:24:09 Second line
Compared to fmt.Printf, log.Printf: * by default logs to stderr (os.Stderr) * adds current time to each log line * ensures that echo log is on it’s own line by adding \n if not explicitly provided
To log fatal issues:
f, err := os.Open("file.txt")
if err != nil {
log.Fatalf("os.Open('file.txt') failed with '%s'\n", err)
}
log.Fatalf logs the message and calls os.Exit(1) to end the process.
Logging to a file
Log package allows changing where the log output is sent. We can log to a file:
logfile, err := os.OpenFile("test.log", os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
if err != nil {
log.Fatalf("os.OpenFile() failed with '%s\n", err)
}
defer logfile.Close()
log.SetOutput(logfile)
log.Println("Log entry")
Logging to syslog
When running on Unix, we might log to syslog:
syslogger, err := syslog.New(syslog.LOG_INFO, "syslog_example")
if err != nil {
log.Fatalln(err)
}
log.SetOutput(syslogger)
log.Println("Log entry")
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents
4
Strings
5
Pointers
6
Arrays
7
Slices
8
Maps
9
Structs
10
Interfaces
15
Functions
16
Methods
18
Defer
20
Concurrency
22
Mutex
23
Packages
27
Logging
30
JSON
31
XML
32
CSV
33
YAML
34
SQL
35
HTTP Client
36
HTTP Server
38
Reflection
39
Context
40
Package fmt
41
OS Signals
42
Testing
49
gob
50
Plugin
53
Console I/O
54
Cryptography
59
Contributors