For more exciting posts, please visit my personal blog


preface

I am a Java programmer, seeing the momentum of Go in recent years is good, in line with the principle of technical more not pressure body, also follow the trend of slowly learning. I have to say that Go is actually quite different from Java. After all, I am used to the idea of object-oriented, and I can’t accept it for a while. As the saying goes, practice is the real knowledge, this is thinking of taking just learned point fur practice hand, the result encountered a problem: log.

Unlike its Java Cousins such as Log4j, Go’s own log library has limited functionality. Although logrus, Zap and many other excellent third-party logging libraries have been created, I still couldn’t find one on Github that met my needs.

I need the log library function

The idea was to have one that supports log splitting and configuration to output logs to different directories (well, I think Log4J is great), but many tripartite libraries don’t support this feature. Sure, writing logs to logstash or databases is becoming more and more popular, but it’s a shame you can’t split up your logs.

So thinking about going online copy, there should be ready-made, but find a circle is either copy and paste, or with the effect I want is not the same, so they think about their own hands to achieve a. Does Logrus support hook support?

Implement a log library yourself

The imagined implementation would look something like this:

The code is too troublesome to paste, the finished product has been put on github: github.com/jptangchina…

You can use it directly:

package main

import log "github.com/jptangchina/log4g"

func main(a) {
  log.Info("Test info output")}Copy the code

The main functions are as follows:

  1. Configuration file Configures the output behavior, including file size division, time division, and log level
  2. Mask logrus console output when output to a file
  3. Logs of different levels can be output to different files
  4. Logs of different levels can be output to the same file
  5. Oh, I don’t know. You can experience it yourself

conclusion

Generally speaking, it is very difficult to write completely by oneself, but fortunately, predecessors have done enough work. However, I have just started to learn Go, and I am sure that I am not very good at writing it. If there is a better tool with the same implementation here also ask for a recommendation, I really can not find. In addition, if there is a wrong place to write, you can correct, but please do not bar, I have just learned, do not bar! Go away, please!


For more exciting posts, please visit my personal blog