go - How to write log into .log files in golang? -
i'am new use go language, still learn , need help. how can write application logs in go language ".log" files similiar php phalcon framework ?
i have searching google , go language tutorials, there no simple understanding example. have try example logs text doesn't write continously. here's example used learn logging log, , think it's completly wrong.
package main import ( "bufio" "fmt" "io/ioutil" "os" "time" ) func check(e error) { if e != nil { panic(e) } } func main() { := time.now() dt := now.format("2006-01-02") dt2 := now.format("2006-01-02 15:04:05") // start, here's how dump string (or // bytes) file. d1 := []byte("hello\ngo11\n" + dt2) err := ioutil.writefile("/users/my/documents/work/src/logs/log-"+dt+".log", d1, 0644) check(err) // more granular writes, open file writing. f, err := os.create("/users/my/documents/work/src/logs/log1.log") check(err) // it's idiomatic defer `close` // after opening file. defer f.close() // can `write` byte slices you'd expect. d2 := []byte{115, 111, 109, 101, 10} n2, err := f.write(d2) check(err) fmt.printf("wrote %d bytes\n", n2) // `writestring` available. n3, err := f.writestring("writes\n" + dt) fmt.printf("wrote %d bytes\n", n3) // issue `sync` flush writes stable storage. f.sync() // `bufio` provides buffered writers in addition // buffered readers saw earlier. w := bufio.newwriter(f) n4, err := w.writestring("buffered\n") fmt.printf("wrote %d bytes\n", n4) // use `flush` ensure buffered operations have // been applied underlying writer. w.flush() }
you're trying many different things it's hard tell you're aiming specifically, if want write logs file, here example:
package main import ( "log" "os" ) func main() { //create file desired read/write permissions f, err := os.openfile("filename", os.o_wronly|os.o_create|os.o_append, 0644) if err != nil { log.fatal(err) } //defer close when you're done it, not because think it's idiomatic! defer f.close() //set output of logs f log.setoutput(f) //test case log.println("check make sure works") }
Comments
Post a Comment