Examples of log package in Golang

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 the second argument of New.

Second argument is string prefix - it's just prefix for every log message you will do:

var logger  = log.New(&CustomWriter{}, "Hi, I'm just prefix: ", log.LstdFlags)
logger.Println("First log message")
logger.Println("Second message")

Output:

Hi, I'm just prefix: 2020/04/19 00:08:32 First log message
Hi, I'm just prefix: 2020/04/19 00:08:32 Second message



Comments

Popular posts from this blog

Methods for reading XML in Java

XML, well-formed XML and valid XML

ArrayList and LinkedList in Java, memory usage and speed