From a2db886493081a6fc88d76902fd448606f5deae3 Mon Sep 17 00:00:00 2001 From: melvandito Date: Fri, 6 Aug 2021 15:45:42 +0700 Subject: [PATCH] fix logging --- main.go | 17 +++++++---------- 1 file changed, 7 insertions(+), 10 deletions(-) diff --git a/main.go b/main.go index 0102520..990b7bf 100644 --- a/main.go +++ b/main.go @@ -23,7 +23,7 @@ func main() { }) if err != nil { - log.StdInfo(context.Background(), nil, err, "Failed to start Log") + log.StdFatal(context.Background(), nil, err, "Failed to start Log") } http.HandleFunc("/", HelloHandler) @@ -44,22 +44,19 @@ func HelloHandler(w http.ResponseWriter, r *http.Request) { keys, ok := r.URL.Query()["product_id"] if !ok { - log.StdFatal(ctx, nil, nil, "No product id supplied") - fmt.Fprint(w, "No product id supplied") + log.StdError(ctx, nil, errors.New("No product id supplied"), "[HelloHandler] No product id supplied") return } // parse the product id if len(keys) < 1 { - log.StdFatal(ctx, nil, nil, "No product id found") - fmt.Fprint(w, "No product id supplied") + log.StdError(ctx, nil, errors.New("No product id found"), "[HelloHandler] No product id found") return } productID, err = strconv.Atoi(keys[0]) if err != nil { - log.StdFatalf(ctx, nil, nil, "Product id not valid %s", keys[0]) - fmt.Fprint(w, "No product id supplied") + log.StdError(ctx, nil, err, fmt.Sprintf("[HelloHandler] Product id is not valid. value: %s", keys[0])) return } @@ -68,13 +65,11 @@ func HelloHandler(w http.ResponseWriter, r *http.Request) { product, err := GetProductFromDB(ctx, productID) if err != nil { - fmt.Fprint(w, "Invalid id") return } err = CalculateDiscount(ctx, product) if err != nil { - fmt.Fprint(w, "Invalid id") return } @@ -84,6 +79,7 @@ func HelloHandler(w http.ResponseWriter, r *http.Request) { func GetProductFromDB(ctx context.Context, id int) (*external.Product, error) { var result external.Product if id < 1 { + log.StdError(ctx, nil, errors.New("Product id Invalid"), fmt.Sprintf("[GetProductFromDB] ProductID is Invalid")) return nil, errors.New("Product id Invalid") } @@ -95,9 +91,10 @@ func GetProductFromDB(ctx context.Context, id int) (*external.Product, error) { func CalculateDiscount(ctx context.Context, p *external.Product) error { if p.Stock%2 == 0 { p.Discount = 20 - log.StdError(ctx, p, nil, "User get 20 discount") + log.StdDebug(ctx, p, nil, fmt.Sprintf("[CalculateDiscount] User get %d discount", p.Discount)) } else { p.Discount = 0 } + return nil }