forked from Imam-Rahensa/logging-workshop
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
106 lines (86 loc) · 2.54 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
package main
import (
"context"
"errors"
"fmt"
"math/rand"
"net/http"
"strconv"
"github.com/imam-rahensa/logging-workshop/external"
"github.com/tokopedia/tdk/go/log"
)
func main() {
// Set Standard Log Config
err := log.SetStdLog(&log.Config{
Level: "trace", // Default will be in info level
LogFile: "./log/logging-workshop.error.log", // If none supplied will goes to os.Stderr, for production you must put log file
DebugFile: "./log/logging-workshop.debug.log", // If none supplied will goes to os.Stderr, for production you must put log file
AppName: "logging-workshop", // your app name, the format will be `{service_name}_{function}`
})
if err != nil {
log.StdError(context.Background(), nil, err, "Failed to start Log")
}
http.HandleFunc("/", HelloHandler)
http.ListenAndServe(":8080", nil)
}
func HelloHandler(w http.ResponseWriter, r *http.Request) {
ctx := context.Background()
// Init context for logging. This will inject request_id to your context
ctx = log.InitLogContext(ctx)
var (
productID int
err error
)
keys, ok := r.URL.Query()["product_id"]
if !ok {
log.StdError(ctx, nil, nil, "No product id supplied")
fmt.Fprint(w, "No product id supplied")
return
}
// parse the product id
if len(keys) < 1 {
log.StdError(ctx, nil, nil, "No product id found")
fmt.Fprint(w, "No product id supplied")
return
}
productID, err = strconv.Atoi(keys[0])
if err != nil {
log.StdErrorf(ctx, nil, nil, "Product id not valid %s", keys[0])
fmt.Fprint(w, "Invalid product id")
return
}
// Set your context id. In this case you will put your product id
ctx = log.SetCtxID(ctx, strconv.Itoa(productID))
product, err := GetProductFromDB(ctx, productID)
if err != nil {
log.StdError(ctx, nil, nil, "Product id invalid")
fmt.Fprint(w, "Invalid id")
return
}
err = CalculateDiscount(ctx, product)
if err != nil {
log.StdError(ctx, nil, nil, "Product id invalid")
fmt.Fprint(w, "Invalid id")
return
}
fmt.Fprintf(w, "%+v", product)
}
func GetProductFromDB(ctx context.Context, id int) (*external.Product, error) {
var result external.Product
if id < 1 {
log.StdError(ctx, nil, nil, "Product id invalid")
return nil, errors.New("Product id Invalid")
}
result.Name = "product testing"
result.Stock = rand.Int()
return &result, nil
}
func CalculateDiscount(ctx context.Context, p *external.Product) error {
if p.Stock%2 == 0 {
p.Discount = 20
log.StdInfo(ctx, p, nil, "User get 20 discount")
} else {
p.Discount = 0
}
return nil
}