[Golang] Log out file using zap

Tram Ho

Why do you need to log out the file?

  • Currently, most developers when developing functions are mostly just logging to the console, then on environments like dev, pro, .. then using tools that will support the collector without concern at all.
  • When you dev in systems that do not have applications that support collectors, you need to log out the file.
  • I need to install 2 libraries: zap and lumberjack

Code

  1. Simple config logger:

  1. Map log levels:

  1. Create interfaces for functions:

  1. Create instance logger:

  1. Get the path of the log file:

  • Getwd function is to get the current path when running the program.
  • The os.Stat function checks if the path exists or not.
  • os.Mkdir function creates folder with above path.
  1. When logging, each api needs a uuid.

  • Later when writing the API, in an api we log out 5 messages for example, then set SetLogID so that when the filter relies on this id to search.
  • This function will mostly be used in middleware
  1. Implement the functions in the interface: this code is long you see in the link .
  2. The configure function to log to the file:

  • MaxSize is the size of the file, default is 100 megabytes, demo should be 1 megabytes.
  • MaxBackups is the total number of files that will be saved, currently leaving 3 means that in the logs folder there will be 3 archived files: 1.log, 2.log, 3.log . When there is a new file 4.log, the file 1.log will be lost.
  1. Finally, the New function:

Kiểm TRA

  1. Create main.go function:

  • create a forever chan to keep the main function from exiting.
  • a time.Tick loop every 1 millisecond will write to the file.
  1. Create logs folder:

  1. run:

  • folder logs will automatically split files when the size is enough 1MB

Source https://github.com/ducnpdev/golang-demo/tree/logger

Share the news now

Source : Viblo