When instantiating a new Logger
, you can pass a few useful parameters and/or helper strings to help define and clarify the output. Each log entry can be prepended with a string, which can be helpful while reviewing multiple types of log entries. You can also define the type of date and time formatting that you would like on each entry.
To create a custom formatted log, just invoke the New()
function with an io.Writer
as shown:
package main import ( "log" "os" ) var ( Warn *log.Logger Error *log.Logger Notice *log.Logger ) func main() { warnFile, err := os.OpenFile("warnings.log", os.O_RDWR|os.O_APPEND, 0660) defer warnFile.Close() if err != nil { log.Fatal(err) } Warn = log.New(warnFile, "WARNING: ", log.Ldate|log.Ltime) Warn.Println("Messages written to a file called 'warnings.log' are likely to be ignored :(") log.Println("Done!") }
This not only allows us to utilize stdout
with our log.Println
function but also store more significant messages in a log file called warnings.log
. Using the os.O_RDWR|os.O_APPEND
constants allow us to write to the file and use an append file mode, which is useful for logging.