A, directories,

  • A, directories,
  • Second, the log
    • 1. Introduction
    • 2. Use the standard Logger directly
    • 3. Use a custom Logger
    • 4. Write the log file to the specified file
  • Third, the log/syslog
    • 1. Introduction
    • 2. TCP listens to the port and waits for logs to be written
    • 3. Use the Dial function to generate a Writer instance and write logs to the TCP service

Second, the log

1. Introduction

The package defines a structure Logger, on which the following functions are mounted: 1.1 initialization (New) 1.2 setup log style (SetFlags) 1.3 set the carrier of the log records (SetOutput) 1.4 set up the log prefix (methods SetPrefix) 1.5 ordinary record log (Print/f | ln) 1.6 Fatal error to exit the program and to record the log (Fatal [f | ln]) 1.7 in the form of a panic exit program and record the log (panic [f | ln]) 1.8 print log (Output) corresponding to the function call stack frames. For ease of use, the standard library also pre-implemented a standard Logger, convenient for us to directly call the function.

2. Use the standard Logger directly

package main

import (
    "log"
    "os"
)

func main(a){
    // You can set the record carrier with SetOutput (the carrier only needs to implement the IO.Writer interface). Let's choose standard output here.
    log.SetOutput(os.Stdout)
    // Set the print prefix
    log.SetPrefix("My log:")
    // Set the print style
    /* const ( Ldate = 1 << iota // the date in the local time zone: 2009/01/23 Ltime // the time in the local time zone: 01:23:23 Lmicroseconds // microsecond resolution: Assuming Llongfile // Full file name and line number: /a/b/c/d.go:23 Lshortfile // final file name element and line number: d.go:23. overrides LUTC // if Ldate or Ltime is set, use UTC rather than the local time zone LstdFlags = Ldate | Ltime // initial values for the standard logger ) */  
    log.SetFlags(log.Ldate | log.Ltime | log.Lmicroseconds | log.Llongfile)
    // Enter logs into the carrier
    log.Println("begin log")
    // Print style, prefix
    log.Print(log.Flags())
    log.Printf("%s\n", log.Prefix())
    // Print the current log, and call main
    log.Output(0."I'm caller.")
    log.Output(1."I'm caller's caller")
    log.Output(2."I'm caller's caller's caller")
    Exit with a fatal error and record the information
    log.Fatalln("I'm exit by Fatal.")}Copy the code

3. Use a custom Logger

package main

import (
    "bytes"
    "fmt"
    "log"
)

func main(a) {
    var (
        // Define a carrier
        buf bytes.Buffer
        // Logger initializes with the carrier, prefix, and style parameters
        logger = log.New(&buf, "INFO: ", log.Lshortfile)
        // Define the Output closure function
        infof = func(info string) {
            logger.Output(2, info)
        }   
    )   
    infof("Hello world")
    // Print the carrier, prefix, style
    logger.Print(logger.Flags())
    logger.Printf("%s\n", logger.Prefix())
 
    // Print the carrier contents
    fmt.Print(&buf) // FMT.Print(logger.writer ())
    
    // Exit as panic
    logger.Panic("I'm exit by Panic")}Copy the code

4. Write the log file to the specified file

package main

import (
	"log"
	"os"
)

func main(a) {
	f, err := os.OpenFile("test.log", os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0644)
	if nil! = err { log.Fatal(err) }defer f.Close()
	log.SetOutput(f)
	log.Println("works")}Copy the code

Third, the log/syslog

1. Introduction

You can send logs through Unix sockets, UDP, and TCP.

2. TCP listens to the port and waits for logs to be written

package main

import (
	"fmt"
	"io/ioutil"
	"net"
)

func main(a) {
	localAddress, _ := net.ResolveTCPAddr("tcp4"."127.0.0.1:8080")
	var tcpListener, err = net.ListenTCP("tcp", localAddress)
	if nil! = err { fmt.Println("Listening error:", err)
		return
	}
	defer func(a) {
		tcpListener.Close()
	}()
	fmt.Println("Waiting for connection...")
	var conn, err2 = tcpListener.AcceptTCP()
	if nil! = err2 { fmt.Println("Failed to accept connection:", err2)
		return
	}
	var remoteAddr = conn.RemoteAddr()
	fmt.Println("Received a link:", remoteAddr)
	fmt.Println("Reading messages...")
	var bys, _ = ioutil.ReadAll(conn)
	fmt.Println("Received message from client:".string(bys))
	// conn.Write([]byte("hello, Nice to meet you, my name is Dawn"))
	conn.Close()
}
Copy the code

3. Use the Dial function to generate a Writer instance and write logs to the TCP service

package main

import (
	"log"
	"log/syslog"
)

func main(a) {
	sysLog, err := syslog.Dial("tcp"."localhost:8080", syslog.LOG_WARNING|syslog.LOG_DAEMON, "demotag")
	if nil! = err { log.Fatal(err) }defer sysLog.Close()
	sysLog.Write([]byte("a log message.\n"))
	sysLog.Info("an info message.\n")
	sysLog.Notice("a notice message.\n")
	sysLog.Emerg("an emergency message.\n")
	sysLog.Warning("a warning message.\n")
	sysLog.Err("a err message.\n")
	sysLog.Debug("a debug message.\n")
	sysLog.Crit("a crit message.\n")
	sysLog.Alert("a alert message.\n")}Copy the code