There are many good third-party open source libraries in Golang, such as
- Go-slog, this is the author's own open source of a simple log library
- Logrus
- Zap
- Oklog
- Glog
- Seelog
- Zerolog
are very good open source Library, the function is also very powerful, many support in TXT input log or JSON output of the log, I simply tried the next few log library
1. Logrus
Package Mainimport ("Flag" "FMT" "OS" "Path" "Runtime" "Strings" "Time" "github.com/sirupsen/logr US ") func logrus_test () {fmt. Printf ("<<<<<<<<<logrus test>>>>>>>>>>>>>> \ n ") Logrus. Withfields (Logrus. fields{"SB": "Sbvalue",}). Info ("A walrus Appears") Log1: = Logrus. New () fmt. Printf ("Log1 Level:%d\n", Log1. Level) Log1. Debug ("Log1 Debug") log1. DEBUGF ("Log1 debug F,%d", ten) Log1. Info ("log1 info") log1. Warn ("Log1 Warn") log1. Error ("LOG1 error")//Log1. Panic ("Log1 Panic") log1. SetLevel (Logrus. ErrorLevel) fmt. Printf ("After set Log1 level to Errorlevel\n") log1. Debug ("Log1 Debug") fmt. Printf ("-------------test formater-------------\ n") log1. SetLevel (Logrus. DebugLevel) Log1. Formatter = &logrus. textformatter{disablecolors:true, Fulltimestamp:true, Disablesorting:true,} log1. Debug ("Log Text formatter test") FMT. Printf ("-----------JSON formatter-------------\ n") log1. Formatter = &logrus. jsonformatter{} log1. Debug ("Log JSON formatter test") fmt. Printf ("-----------Log to file test-----------\ n") log2: = Logrus. New () log2. SetLevel (Logrus. DebugLevel) log2. Formatter = &logrus. textformatter{disablecolors:true, Fulltimestamp:true, Disablesorting:true,} logger_name : = "Logrus" cur_time: = time. Now () Log_file_name: = Fmt. Sprintf ("%s_%04d-%02d-%02d-%02d-%02d.txt", Logger_name, Cur_time. Year (), Cur_time. Month (), Cur_time. Day (), Cur_time. Hour (), Cur_time. Minute ()) log_file, err: = OS. OpenFile (log_file_name, OS. O_create|os. O_append|os. O_wronly, OS. modeexclusive) If err! = Nil {fmt. Printf ("Try create logfile[%s] error[%s]\n", log_file_name, err. Error ()) return} defer log_file. Close () log2. Setoutput (log_file) for I: = 0; I < 10; i++ {log2. DEBUGF ("Logrus to file test%d", I)}}
Simple to use, with a variety of output styles
2. Zap
Package Mainimport ("Flag" "FMT" "OS" "Path" "Runtime" "Strings" "Time" "Github.com/golang/glog") Func zap_log_test () {fmt. Printf ("<<<<<<<<<zap log test>>>>>>>>>>>\n") Logger: = Zap. Newexample () Defer logger. Sync () Const URL = "http://example.com"//In most circumstances, use the Sugaredlogger. It's 4-10x faster than most//other structured logging packages and have a familiar, loosely-typed API. Sugar: = logger. Sugar () Sugar. Infow ("Failed to fetch URL.",//structured context as loosely typed key-value pairs. "url", url, "Attempt", 3, "Backoff", time. Second,) sugar. Infof ("Failed to fetch URL:%s", URL)//In the unusual situations where every microsecond matters, use the//Logge R. It ' s even faster than the Sugaredlogger, but only supports//structured logging. Logger. Info ("Failed to fetch URL.",//structured context as Strongly typed fields. Zap. String ("url", url), Zap. Int ("Attempt", 3), Zap. Duration ("Backoff", time. Second),)}
Zap's performance should only be the highest inside of these libraries
3. Glog
package mainimport ( "flag" "fmt" "os" "path" "runtime" "strings" "time" "github.com/golang/glog")func glog_test() { fmt.Printf("<<<<<<<glog_test>>>>>>>>>>\n") flag.Parse() defer glog.Flush() glog.Info("glog info test") glog.Warning("glog warn test") // glog.Error("glog error test") // glog.Fatal("glog fatal test")}
Glog is lighter, with two files, the Golang version of Google's C + + log library Glog
Using the next few libraries, although very strong, but the feeling and my needs are not quite in line with, I need to be able to a daily file or every hour a file or limited file format dynamic rotating function, but it seems not (or I did not find), and then the output format of the log is not my habit, all no way , it took two days to write a simple to meet my own requirements of the log library Go-slog, interested classmates can clone down to try, O (∩_∩) o
4. Slog
Because the above a few log library, feel not quite accord with my own taste, wrote a simple log library, download address: Https://github.com/yandaren/go-slog, interested students can clone down to try, the code is very simple, the following gives some
Example
Package Slog_exampleimport ("FMT" "Go-slog/slog" "Time") func Slog_test () {for _, LG_LVL: = Range slog. allloglevels {fmt. Printf ("%d =%s\n", Lg_lvl, Lg_lvl. String ())} FMT. Printf ("----------------------------------\ n") var lvl_strings = []string{"Debug", "Info", "Warn" , "Warning", "error", "Fatal", "none", "Sblv",} for _, Lg_lvl_str: = Range lvl_s trings {lg_lvl, err: = slog. Parselevel (LG_LVL_STR) if err! = Nil {fmt. Printf ("Parse lg_lvl_str[%s] error[%s]\n", LG_LVL_STR, err. Error ())} else {fmt. Printf ("log_lvl_str[%s] =%d\n", Lg_lvl_str, Lg_lvl)}} fmt. Printf ("---------------slog test---------------\ n") Logger: = slog. Newstdoutloggerst ("Stdout_logger") logger. Debug ("Slog stdoutlogger test") logger. Info ("Slog stdoutlogger test") logger. Warn ("Slog stdoutlogger test,%d", 3) Stderr_logger: = slog. Newstderrloggerst ("Stderr_Logger ") Stderr_logger. Debug ("Slog stderr_logger test") Stderr_logger. Info ("Slog stderr_logger test") Stderr_logger. Warn ("Slog stderr_logger test,%d", 3)}func file_writer_test () {fmt. Printf ("file_writer_test\n") Fwriter: = slog. Newfilewriter () file_name: = "File_writer_test.txt" if!fwriter. Open (file_name, False) {FMT. Printf ("Create file[%s] failed\n", file_name) return} defer fwriter. Close () for I: = 0; I < 10; i++ {fwriter. Write ([]byte ("11111111111111111111\n")} file_name1: = "File_writer_test1.txt" if!fwriter. Open (File_name1, False) {FMT. Printf ("Create file[%s] failed\n", file_name1) return} defer fwriter. Close () for I: = 0; I < 10; i++ {fwriter. Write ([]byte ("2222222222222222222222\n"))}}//This is the simplest single file of the Loggerfunc simple_file_logger_test () {fmt. Printf ("simple_file_logger_test\n") Logger: = slog. Newbasicloggerst ("Base_logger", "Basic_logger.txt") for I: = 0; I < 10; i++ {logger. Debug ("Base Logger debug Log Test") logger. Info ("Base Logger info log Test") logger. Warn ("Base logger Warn log Test")}}//This specifies the maximum size of each file, and the maximum file format maintained//The current file size reaches the specified maximum file size, once rotating//such as a maximum of 3 files// Rotate files://Log.txt, log.1.txt//log.1.txt, log.2.txt//log.2.txt, log.3.txt//log.3.txt UNC Rotating_logger_test () {fmt. Printf ("rotating_logger_test\n") Logger: = slog. Newrotatingloggerst ("Rotating_logger", "Rotating_logger.txt", 5) for I: = 0; I < 20; i++ {logger. Debug ("rorating msg xxx now_time[%s]", time. Now (). String ())}}//This is a daily file of Loggerfunc Daily_logger_test () {fmt. Printf ("daily_logger_test\n") Logger: = slog. Newdailyloggerst ("Daily_logger", "Daily_logger.txt", "N", "a") for I: = 0; I < 20; i++ {logger. Debug ("Daily_logger test")}}//this is the Loggerfunc hourly_logger_test () {FMT] that will regenerate a file every hour. Printf ("hourly_logger_test\n") Logger: = slog. NewhourlyloggersT ("Houly_logger", "Houly_logger.txt") for I: = 0; I < 20; i++ {logger. Debug ("Houlry_logger test")}}//you create a logger, the same log can be printed to multiple places as needed//such as stdout, stderr, file, such as Func muti_sink_test () { Logger: = slog. Newlogger ("Muti_logger") Sink1: = slog. Newsimplefilesinkst ("Muti_sink_logger.txt") sink2: = slog. Newhourlyfilesinkst ("Muti_hourly_logger.txt") Sink3: = slog. Newstdoutsinkst () logger. Appendsink (SINK1). Appendsink (SINK2). Appendsink (SINK3) for I: = 0; I < 20; i++ {logger. Debug ("Muti_sink_test test")}}func logger_log_test (gid int, logger *slog. Logger) {fmt. Printf ("Logger_log_test gid[%d]\n", gid) for I: = 0; I < 5; i++ {logger. Debug ("Logger_log_test gid[%d] msgid[%d]", GID, i)}}func Muti_goroutine_stdout_test_nolock () {fmt. Printf ("Muti_goroutine_stdout_test_nolock") Logger: = slog. Newstdoutloggerst ("Muti_goroutine_test_nolock") for I: = 0; I < 5; i++ {Go logger_log_test (i, logger)} FMT. Printf ("Try sleep for a while\n ") time. Sleep (Time.millisecond *) fmt. Printf ("Sleep finished, Muti_goroutine_test_nolock end\n")}func Muti_goroutine_stdout_test_lock () {fmt. Printf ("Muti_goroutine_stdout_test_lock") Logger: = slog. NEWSTDOUTLOGGERMT ("Muti_goroutine_test_lock") for I: = 0; I < 5; i++ {Go logger_log_test (i, logger)} FMT. Printf ("Try Sleep for a while\n") time. Sleep (Time.millisecond *) fmt. Printf ("Sleep finished, Muti_goroutine_test_nolock end\n")}func Muti_goroutine_log_file_test_nolock () {fmt. Printf ("Muti_goroutine_log_file_test_nolock") Logger: = slog. Newbasicloggerst ("Muti_goroutine_log_file_test_nolock", "Muti_goroutine_log_file_test_nolock.txt") for I: = 0; I < 5; i++ {Go logger_log_test (i, logger)} FMT. Printf ("Try Sleep for a while\n") time. Sleep (Time.millisecond *) fmt. Printf ("Sleep finished, Muti_goroutine_test_nolock end\n")}func Muti_goroutine_log_file_test_lock () {fmt. Printf ("Muti_goRoutine_log_file_test_lock ") Logger: = slog. NEWBASICLOGGERMT ("Muti_goroutine_log_file_test_lock", "Muti_goroutine_log_file_test_lock.txt") for I: = 0; I < 5; i++ {Go logger_log_test (i, logger)} FMT. Printf ("Try Sleep for a while\n") time. Sleep (Time.millisecond *) fmt. Printf ("Sleep finished, Muti_goroutine_test_nolock end\n")}