This golang tutorial help to Write file, read and write files is very importing features of any programming language.Go is providing os package to create/read/write the file.You can read data from file or write something into file using golang os package.
I am creating go snippet to Write Log into a file using os
module, You can use writing into file feature for logging, saving data, store data in file etc.
We will import all required pacakge,
import ( "github.com/labstack/echo" "log" "net/http" "os" )
We will create Struct for logs message into file,
type Response struct { Status int `json:"status"` Meta string `json:"_meta"` Resource interface{} `json:"resource"` } type Reso struct { Output string `json:"output_data"` }
We will open log file and write data into this file when the rest end points call,You can also write logs without any rest call.
f, _ := os.OpenFile("testlogfile.log", os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
We are opening testlogfile.log
file in read write mode, if file does not exist then it would be new one created.We are appending data into testlogfile.log
file on each time write data.
defer f.Close() log.SetOutput(f)
We’re also using defer method to close the file access once the function has finished to write data.
We will log HTTP details and message on call of restful service,I am using ECHO to create rest call for demonstration purpose.
e := echo.New() e.GET("/testlog", func(c echo.Context) error { log.Println("get called") response := Response{} resource := Reso{} resource.Output = "output_data test" response.Status = http.StatusOK response.Meta = "Just for fun" response.Resource = resource return c.JSON(http.StatusOK, &response) })
We are setting data into resource and response struct instance variable and write to file, so whenever you will call http://localhost:1323/testlog
using browser, log message would be logged into testlogfile.log
file.
The post How to Write Log into Files in Go/Golang appeared first on Rest Api Example.