Linux is unique in many ways relative to Windows, and writing programs in Linux is no exception. Standard output, the use of standard err and null devices is not only a good idea, but also a principle. If your program will log information, it is best to follow the goal convention. In this way, your program will be compatible with all mac/linux tools and managed environments. Go has a log packet and logger type in the standard library. Using the log package will provide you with everything you need to be a good citizen (meaning that the log package is very compatible). You will be able to write all standard devices, custom files or support IO. Any target of the Writer interface. I have provided a very simple example that will help you get started with logger: "Gopackage mainimport (" io "" io/ioutil "" Log "" OS ") Var (Trace *log. Logger Info *log. Logger Warning *log. Logger Error *log. Logger) func Init (Tracehandle io. Writer, Infohandle io. Writer, Warninghandle io. Writer, Errorhandle io. Writer) {Trace = log. New (Tracehandle, "TRACE:", log.) Ldate|log. Ltime|log. Lshortfile) Info = log. New (Infohandle, "INFO:", log.) Ldate|log. Ltime|log. Lshortfile) Warning = log. New (Warninghandle, "WARNING:", log.) Ldate|log. Ltime|log. Lshortfile) Error = log. New (Errorhandle, "ERROR:", log.) Ldate|log. Ltime|log. Lshortfile)}func Main () {Init (ioutil. Discard, OS. Stdout, OS. Stdout, OS. Stderr) trace.println ("I had something standard to say") info.println ("Special information") WarNing. Println ("There is something you need to know on") error.println ("Something Has Failed")} ' ' When you run this program, you will get the following output: ' ' info:20 13/11/05 18:11:01 main.go:44:special informationwarning:2013/11/05 18:11:01 Main.go:45:there is something we need to K Now abouterror:2013/11/05 18:11:01 main.go:46:something have failed ' ' you will notice that the trace logging is not shown (note: Trace Recorder). Let's look at the code to find out why. View the code for the Trace logging section: "Govar trace *log. Loggertrace = log. New (Tracehandle, "TRACE:", log.) Ldate|log. Ltime|log. Lshortfile) Init (ioutil. Discard, OS. Stdout, OS. Stdout, OS. Stderr) trace.println ("I had something standard to say") "This code creates a package-level variable named Trace, which is a pointer to log. A pointer to the Logger object. Then create a new log inside the Init function. The Logger object. Log. The parameters of the new function are as follows: "' Gofunc new (out IO. Writer, prefix string, flag int) *logger "" out:the out variable sets the destination to which log data would be written . The out variable setting will be written to the target of the log data prefix:the prefix appears at the beginning of each generated log line. The prefix appears at the beginning of each generated journal line. Flags:the flag argument defines the logging Properties. The flag parameter defines the Logging property ' ' Flags: ' ' goconst (//Bits or ' Ed together to control what ' s printed. There is no control over the//order they appear (the order listed here) or the format they present (AS//described in T He comments). A Colon appears after these items://2009/01/23 01:23:23.123123/a/b/c/d.go:23:message Ldate = 1 << iota//The DA TE:2009/01/23 ltime//The time:01:23:23 lmicroseconds//microsecond resolution:01:23:23.123123. Assumes Ltime. 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 llongfile Lstdflags = Ldate | Ltime//Initial values for the standard logger) "In this sample program, the target of Trace is ioutil. Discard. This is a null device (the corresponding/dev/null is equivalent to a garbage bin, the message is discarded), and all write calls can succeed without doing anything. Therefore, when you write using Trace, nothing is displayed in the terminal window. Then take a look at info's code: "' Govar info *log." Loggerinfo = log. New (Infohandle, "INFO:", log.) Ldate|log. Ltime|log. Lshortfile) Init (ioutil. Discard, OS. Stdout, OS. Stdout, OS. Stderr) Info.priNTLN ("Special Information") "for Info (note: message logger), OS. The Stdout passed into the init function to Infohandle. This means that when you write a message using Info, the message is displayed in the terminal window via standard output. Finally, look at the error code: "' Govar error *log. Loggererror = log. New (Errorhandle, "ERROR:",//: The original text is different from the original definition, it should be a clerical error, so directly modify the log. Ldate|log. Ltime|log. Lshortfile) Init (ioutil. Discard, OS. Stdout, OS. Stdout, OS. Stderr) error.println ("Something has failed")//: The original is special information and the original definition, should be a clerical error, so directly modify the "" this time the OS. The Stderr passed into the Init function to Errorhandle. This means that when you use the error to write a message, the message is displayed in the terminal window via a standard error. However, these messages are passed to the OS. Stderr allows other applications running the program to know that an error has occurred. Because IO is supported. Any target of the Writer interface is acceptable, so you can create and use the file: ' Gofile, err: = OS. OpenFile ("file.txt", OS. O_create|os. O_wronly|os. O_append, 0666) if err! = Nil {log. Fatalln ("Failed to open log file", Output, ":", err)}myfile = log. New (File, "PREFIX:", log.) Ldate|log. Ltime|log. Lshortfile) "In the sample code, open a file and pass it to log. The New function. Now, when you write with MyFile, the data is written to file.txt. You can also have logger (note recorder) write to multiple targets at the same time. "' Gofile, err: = OS. OpenFile ("file.txt", OS. O_create|os. O_wronly|os. O_append, 0666) if Err! = Nil {log. Fatalln ("Failed to open log file", Output, ":", err)}multi: = Io. Multiwriter (file, OS. Stdout) MyFile: = log. New (Multi, "PREFIX:", log.) Ldate|log. Ltime|log. Lshortfile) "Here the data will be written to the file and the standard output. Note Use log when handling any errors with OpenFile. Fatalln method. The log package provides an initial logger that can be configured. The following is an example program that uses a log with a standard configuration: "' Gopackage mainimport (" Log ") func main () {log. Println ("Hello World")} ' ' is output: ' ' 2013/11/05 18:42:26 Hello world ' If you want to delete or change the output format, you can use log. SetFlags method: "' Gopackage mainimport (" Log ") func main () {log. SetFlags (0) log. Println ("Hello World")} "" Below is output: "' Hello World ' now all formats have been deleted. If you want to send the output to a different destination, use log. Setoutput: "Gopackage mainimport (" Io/ioutil "" Log ") func main () {log. Setoutput (Ioutil. Discard) log. Println ("Hello World")} "will now not display anything on the terminal window. You can use any support IO. The target of the Writer interface. For this example, I wrote a new log package for all my programs: Go get github.com/goinggo/tracelog I hope I know log and loggers when I start writing go programs. Look forward to seeing more log packages I've written in the future.
Via:https://www.ardanlabs.com/blog/2013/11/using-log-package-in-go.html
Author: William Kennedy Translator: Chaoshong proofreading: polaris1119
This article by GCTT original compilation, go language Chinese network honor launches
This article was originally translated by GCTT and the Go Language Chinese network. Also want to join the ranks of translators, for open source to do some of their own contribution? Welcome to join Gctt!
Translation work and translations are published only for the purpose of learning and communication, translation work in accordance with the provisions of the CC-BY-NC-SA agreement, if our work has violated your interests, please contact us promptly.
Welcome to the CC-BY-NC-SA agreement, please mark and keep the original/translation link and author/translator information in the text.
The article only represents the author's knowledge and views, if there are different points of view, please line up downstairs to spit groove
167 Reads