Golang : Custom Log with Zerolog Event

Custom Log with Zerolog Event

  • model.go
import (
	"github.com/rs/zerolog"
	"github.com/rs/zerolog/log"
)

type Transaction struct {
	// transaction struct here
}

func (t Transaction) Log() *zerolog.Event {
	return log.Warn().
		Str("sellPrice", t.ProductSellPrice.String()).
		Str("buyPrice", t.BuyPrice.String()).
		Str("productName", t.ProductName.String).
		Str("productCode", t.ProductCode.String).
		Str("productCategory", t.ProductCategory.String).
		Str("orderCode", t.OrderCode)
}

  • service.go

func (s *TransactionServiceImpl) createTransaction(transaction Transaction) (Transaction, error) {
    //create logs if buy price is greater than sell price
    if transaction.BuyPrice.Abs().GreaterThan(transaction.SellPrice.Abs()) {
        transaction.Log().Msg("[this_is_logs] custom log")
    }
}
  • output example :

2022-11-28 14:06:33	2022-11-28T07:06:33Z WRN [this_is_logs] custom log buyPrice=140000 productCategory=pulsa productCode=TSEL-100 productName="Pulsa Telkomsel 100.000" orderCode=7161-1669619191 sellPrice=100000
author image

Founder of tarkiman.com, love programming and open source stuff. Subscribe him on Youtube Channel.

Comments