Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Go - Wrap logger in order to add a specific information in each message of a request

I'm working on a project of an http api and there is a thing I want to implement but I have not find the way to do it. So, in my case I send in a request a transaction id, and the thin I want to do is to get this transaction id and use it in the logger, add this information in each log entry of the current request. I want to do this to have a better filtering of my logs when I want to retrieve information if some issue happens.

For example my transaction id is foo : api | [GIN] 2016/08/19 - 13:00:37 | 201 | 30.791855ms | 192.168.99.1:63922 | POST /v1/my/endpoint api | time="2016-08-19T13:00:39Z" level=info msg="Authenticated API user: tests" transactionId="foo" api | time="2016-08-19T13:00:39Z" level=debug msg="SQL query" args=25 query=" SELECT id, created, information1, information2 FROM mydb.mytable WHERE id = ?; " transactionId="foo" This is the kind of information I want to have in my logs.

So instead injecting the transaction id in each log call, I was wondering if there is a way to use the logger as a singleton and add the information each time the logger is called.

I hope I provided enough details in this issue.

thanks.

like image 946
jtonyoak Avatar asked Oct 29 '22 21:10

jtonyoak


1 Answers

Prefix your transaction id in logger. Standard go logger provide many ways to do it. An example is log.New() method.

func GetLogger(transactionID string) *log.Logger {
    return log.New(os.Stdout, fmt.Sprintf("[transactionId = %s ] ", transactionID),
         log.Lshortfile)
}

GetLogger will give you a logger that will prefix your transactionID in every log.

like image 152
Mayank Patel Avatar answered Nov 15 '22 08:11

Mayank Patel