In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)05/31 Report--
Most people do not understand the knowledge points of this article "how to use a log bag in the GE language", so the editor summarizes the following content, detailed content, clear steps, and has a certain reference value. I hope you can gain something after reading this article. Let's take a look at this "how to use a log bag in the GE language" article.
Let's look at the definition of the log file:
Log files are files that record events that occur during the operation of the operating system or other software or messages between different users of the communication software. Recording is the act of keeping a log.
Logs are the eyes and ears of developers that can be used to track, locate errors, debug and analyze code, and monitor application performance. In the simplest case, the message is written to a single log file.
Log package of Go language Standard Library
Because logging is very important, so the Go language standard library provides log package, you can do some simple configuration of logging, we can customize a set of our own logger.
The log package in Golang implements a simple logging package. It defines a type, Logger, and a method to format the output. It also has predefined "standard" loggers, which can be accessed through the helper functions Print [f | ln], Fatal [f | ln], and Panic [f | ln], which are easier to use than manually creating loggers.
The basic log entries include: prefix, date and time stamp, which source file the log is recorded by, the line in which the source file records the log, and finally the log message. Let's take a look at the simple use of the log package: the message returns to the program when dividing by 0 during division, rather than exiting the program directly.
Package mainimport ("errors"fmt"log") func myDiv (x float64, y float64) (float64, error) {if y = = 0 {return 0, errors.New ("the divisor cannot be 0")} return x / y, nil} func main () {var x float64 = 128.2var y float64res, err: = myDiv (x, y) if err! = nil {log.Print (err) / / Print to the standard logger} fmt.Println (res)}
Run the program:
$go run learninglog.go
The divisor at 23:18:06 on 2022-04-19 cannot be 0
0
In the above program, we imported three packages: errors, fmt, and log.
The Print function in the log package is then used: at this point the logger will write to the standard error and print the date and time of each recorded message, which is very useful in general. Each log message has an output on a separate line: if the message being printed does not end on the new line, the logger adds a line.
In addition, the Fatal function in the log package calls os.Exit (1) after writing the log message.
Func main () {var x float64 = 128.2var y float64res, err: = myDiv (x, y) if err! = nil {log.Fatal (err) / / the call os.Exit (1)} fmt.Println (res)} / is followed by a call to os.Exit (1)} fmt.Println (res)} / / the divisor at 23:22:44 on 2022-04-19 cannot be 0nd / exit status 1.
On the other hand, the Panic function calls panic after writing the log message, which will cause the program to terminate after printing the call stack unless the program executes the recover () function.
Func main () {var x float64 = 128.2var y float64res, err: = myDiv (x, y) if err! = nil {log.Panic (err) / / Panic will then use panic ()} fmt.Println (res)} after calling Print ()
Running result:
The divisor at 23:24:18 on 2022-04-19 cannot be 0
Panic: the divisor cannot be 0
Goroutine 1 [running]:
Log.Panic ({0xc0086f60rooms, 0xc000086f70bands, 0x404f99?})
/ usr/local/go/src/log/log.go:385 + 0x65
Main.main ()
/ home/wade/go/src/logLearning/learninglog.go:26 + 0x65
Exit status 2
It can be seen that the Print series of functions is the standard way to write log messages.
How to store log messages in files in Go
In the above code, it is not enough to simply print the log message to the console, because the console is real-time, and if the console is turned off, the log message will be turned off.
Now that we have learned how the Go language reads files, we can store log messages in a file and store all logs in that file.
Package mainimport ("errors"fmt"log"os") func myDiv (x float64, y float64) (float64, error) {if y = = 0 {return 0, errors.New ("the divisor cannot be 0")} return x / y, nil} func main () {var x float64 = 128.2var y float64res, exception: = myDiv (x, y) file, err: = os.OpenFile ("info.log", os.O_CREATE | os.O_APPEND | os.O_WRONLY) 0600) if err! = nil {log.Fatal (err)} defer file.Close () / / close the file log.SetOutput (file) log.Print (exception) fmt.Println (res)}
Run the code:
$go run learninglog.go
0
In addition, we will find that there is an extra info.log file created in the directory. Open the file and you will see something similar to the following printed out.
Customize your logger
To create a custom logger, we need to create a structure of type Logger, and then configure each logger with an output destination, prefix, and flag. And each logger is multi-goroutine secure, and each Logger structure has a mutex, which means that multiple goroutine can call these functions from the same logger at the same time without writing conflicts with each other. Take a look at the underlying implementation of the Logger structure:
Logger structure
/ / A Logger represents an active logging object that generates lines of// output to an io.Writer. Each logging operation makes a single call to// the Writer's Write method. A Logger can be used simultaneously from// multiple goroutines; it guarantees to serialize access to the Writer.type Logger struct {mu sync.Mutex / / ensures atomic writes; protects the following fieldsprefix string / / prefix on each line to identify the logger (but see Lmsgprefix) flag int / / propertiesout io.Writer / / destination for outputbuf [] byte / / for accumulating text to write}
Then let's look at a sample program:
Package mainimport ("io"io/ioutil"log"os") var (Trace * log.Logger / / record all log info * log.Logger / / important information Warning * log.Logger / / warning message Error * log.Logger / / error message) func init () {file, err: = os.OpenFile ("errors.txt", os.O_CREATE | os.O_WRONLY | os.O_APPEND, 0666) if err! = nil {log.Fatalln ("Failed to open error log file:" Err)} Trace = log.New (ioutil.Discard, "Trace:", log.Ldate | log.Ltime | log.Lshortfile) Info = log.New (os.Stdout, "Info:", log.Ldate | log.Ltime | log.Lshortfile) Warning = log.New (os.Stdout, "Warning:", log.Ldate | log.Ltime | log.Lshortfile) Error = log.New (io.MultiWriter (file, os.Stderr), "Error:" Log.Ldate | log.Ltime | log.Lshortfile)} func main () {Trace.Println ("hello") Info.Println ("Information") Warning.Println ("Warning") Error.Println ("Error")}
Running result:
Info: 2022-04-20 00:37:34 learninglog.go:36: Information
Warning: 2022-04-20 00:37:34 learninglog.go:37: Warning
Error: 2022-04-20 00:37:34 learninglog.go:38: Error
Using the New function of the log package, create and initialize a value of type Logger, and then the New function returns the address of the newly created value.
New function
Func New (out io.Writer, prefix string, flag int) * Logger {return & Logger {out: out, prefix: prefix, flag: flag}
The first parameter of the New function, out, specifies the destination where the log is to be written, and the value passed in by this parameter must implement the io.Writer interface.
The second parameter, prefix, appears at the beginning of each line of log generated.
The third parameter, flag, defines which attributes the log contains.
In this procedure:
The Trace logger uses the Discard variable in the ioutil package as the destination to write to. All Writer calls have no action, but will return successfully. When a certain level of logging is not important, use the Discard variable to disable that level of logging.
Both the loggers Info and Warning use stdout as log output.
The first argument of the New function in logging to Error uses the MultiWriter function, and this function call returns a value of type io.Writer, which contains the previously opened file file, as well as stderr. This function is a variable parameter function and can accept any value that implements the io.Writer interface, so all incoming io.Writer will be bound together. When the return value is written, it will be written to all bound io.Writer values. So as to realize the output to multiple Writer. The advantage of this is that when you use the Error logger to log, the output is written to both the file and the stderr.
The above is about the content of this article on "how to use the log package in the GE language". I believe we all have some understanding. I hope the content shared by the editor will be helpful to you. If you want to know more about the relevant knowledge, please follow the industry information channel.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.