Posts

Showing posts from April, 2020

Usage of flag in New constructor of log package in Golang

Image
Package log in Golang provides simple functionality for logging. In previous post we made several examples of usage New constructor for Logger. In this post will be exposed examples of usage New and meaning of third argument of New constructor. Let's begin with the simplest example. We will make logger that logs messages to standard output: package main import ( "log" "os" ) func main() { logger := log.New(os.Stdout, "", log.Ldate) logger.Println("First log message") } Output: 2020/04/21 First log message Let me remind signature of New: func New(out io.Writer, prefix string, flag int) *Logger In example as out io.Writer we used os.Stdout - standard output. As flag int used const from log package - log.Ldate - it is integer 1 - provides the date in the local time zone: 2020/04/21. Total there are 8 such constants in log package: log.Ldate - integer 1 - the date in the local time zone: 2020/04...

Examples of log package in Golang

Image
Hi, everybody! Today we view at some examples of log package in Golang. Package log has constructor method New . Its signature is following: func New(out io.Writer, prefix string, flag int) *Logger It means we need argument out implementing interface io.Writer : type Writer interface { Write(p []byte) (n int, err error) } Let's create our simple one: import ( "fmt" ) type CustomWriter struct {} func(c *CustomWriter) Write(p []byte) (n int, err error) { fmt.Print(string(p)) return len(p), nil } Now look at example: package main import ( "fmt" "log" ) type CustomWriter struct {} func(c *CustomWriter) Write(p []byte) (n int, err error) { fmt.Print(string(p)) return len(p), nil } func main() { var logger = log.New(&CustomWriter{}, "", log.LstdFlags) logger.Println("First log message") } Output: 2020/04/18 23:59:18 First log message Let's look at ...