Skip to content

Commit d368ca2

Browse files
Reconcile loggers (#578)
* Reconcile loggers * Restyled by gofmt * Fix tests * Restyled by gofmt Co-authored-by: Restyled.io <commits@restyled.io>
1 parent b3bb30d commit d368ca2

File tree

3 files changed

+83
-91
lines changed

3 files changed

+83
-91
lines changed

iterative/resource_task.go

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import (
99
"time"
1010

1111
"github.com/aohorodnyk/uid"
12+
"github.com/sirupsen/logrus"
1213

1314
"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
1415
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
@@ -23,6 +24,9 @@ var (
2324
)
2425

2526
func resourceTask() *schema.Resource {
27+
logrus.SetLevel(logrus.DebugLevel)
28+
logrus.SetFormatter(&utils.TpiFormatter{})
29+
2630
return &schema.Resource{
2731
CreateContext: resourceTaskCreate,
2832
DeleteContext: resourceTaskDelete,
@@ -163,12 +167,11 @@ func resourceTask() *schema.Resource {
163167
}
164168

165169
func resourceTaskCreate(ctx context.Context, d *schema.ResourceData, m interface{}) (diags diag.Diagnostics) {
166-
logger := utils.TpiLogger(d)
167-
logger.Info(fmt.Sprintf(logTpl, "Creation"))
170+
logrus.Info(fmt.Sprintf(logTpl, "Creation"))
168171

169172
spot := d.Get("spot").(float64)
170173
if spot > 0 {
171-
logger.Warn(fmt.Sprintf("Setting a maximum price `spot=%f` USD/h. Consider using auto-pricing (`spot=0`) instead.", spot))
174+
logrus.Warn(fmt.Sprintf("Setting a maximum price `spot=%f` USD/h. Consider using auto-pricing (`spot=0`) instead.", spot))
172175
}
173176

174177
task, err := resourceTaskBuild(ctx, d, m)
@@ -250,7 +253,7 @@ func resourceTaskRead(ctx context.Context, d *schema.ResourceData, m interface{}
250253
d.Set("logs", logs)
251254
d.SetId(task.GetIdentifier(ctx).Long())
252255

253-
logger := utils.TpiLogger(d)
256+
logger := logrus.WithFields(logrus.Fields{"d": d})
254257
logger.Info("instance")
255258
logger.Info("logs")
256259
logger.Info("status")
@@ -259,8 +262,7 @@ func resourceTaskRead(ctx context.Context, d *schema.ResourceData, m interface{}
259262
}
260263

261264
func resourceTaskDelete(ctx context.Context, d *schema.ResourceData, m interface{}) (diags diag.Diagnostics) {
262-
logger := utils.TpiLogger(d)
263-
logger.Info(fmt.Sprintf(logTpl, "Destruction"))
265+
logrus.Info(fmt.Sprintf(logTpl, "Destruction"))
264266

265267
task, err := resourceTaskBuild(ctx, d, m)
266268
if err != nil {

iterative/utils/logger.go

Lines changed: 64 additions & 80 deletions
Original file line numberDiff line numberDiff line change
@@ -12,99 +12,40 @@ import (
1212
"github.com/sirupsen/logrus"
1313
)
1414

15-
var baseTimestamp = time.Now()
16-
var colors = make(map[string]int)
17-
18-
type basicFormatter struct{}
19-
20-
func (f *basicFormatter) Format(entry *logrus.Entry) ([]byte, error) {
21-
levelText := strings.ToUpper(entry.Level.String())
22-
levelColor := colors[levelText]
23-
newPrefix := fmt.Sprintf("\x1b[%dmTPI [%s]\x1b[0m", levelColor, levelText)
24-
return []byte(hideUnwantedPrefix(levelText, newPrefix, entry.Message)), nil
15+
var colors = map[string]int{
16+
"DEBUG": 34,
17+
"INFO": 36,
18+
"WARNING": 33,
19+
"ERROR": 31,
20+
"FATAL": 31,
21+
"SUCCESS": 32,
22+
"foreground": 35,
2523
}
2624

27-
func init() {
28-
colors["DEBUG"] = 34
29-
colors["INFO"] = 36
30-
colors["WARNING"] = 33
31-
colors["ERROR"] = 31
32-
colors["FATAL"] = 31
33-
colors["SUCCESS"] = 32
34-
colors["foreground"] = 35
35-
36-
logrus.SetLevel(logrus.DebugLevel)
37-
logrus.SetFormatter(&basicFormatter{})
38-
}
39-
40-
type tpiFormatter struct{}
41-
42-
func (f *tpiFormatter) Format(entry *logrus.Entry) ([]byte, error) {
43-
data := make(logrus.Fields)
44-
for k, v := range entry.Data {
45-
data[k] = v
46-
}
47-
48-
if data["d"] == nil {
49-
return nil, errors.New("ResourceData is not available")
50-
}
25+
type TpiFormatter struct{}
5126

52-
d := data["d"].(*schema.ResourceData)
53-
message := entry.Message
27+
func (f *TpiFormatter) Format(entry *logrus.Entry) ([]byte, error) {
5428
levelText := strings.ToUpper(entry.Level.String())
5529
levelColor := colors[levelText]
30+
message := entry.Message
5631

57-
if message == "instance" {
58-
cloud := d.Get("cloud").(string)
59-
machine := d.Get("machine").(string)
60-
region := d.Get("region").(string)
61-
spot := d.Get("spot").(float64)
62-
63-
spottext := ""
64-
if spot > 0 {
65-
spottext = fmt.Sprintf("(Spot %f/h)", spot)
66-
}
67-
message = fmt.Sprintf("%s %s%s in %s", cloud, machine, spottext, region)
68-
}
69-
70-
if message == "status" {
71-
status := d.Get("status").(map[string]interface{})
72-
73-
message = fmt.Sprintf("\x1b[%dmStatus: queued \x1b[1m•\x1b[0m", colors["DEBUG"])
74-
75-
if status["succeeded"] != nil && status["succeeded"].(int) >= d.Get("parallelism").(int) {
76-
message = fmt.Sprintf("\x1b[%dmStatus: completed successfully \x1b[1m•\x1b[0m", colors["SUCCESS"])
77-
}
78-
if status["failed"] != nil && status["failed"].(int) > 0 {
79-
message = fmt.Sprintf("\x1b[%dmStatus: completed with errors \x1b[1m•\x1b[0m", colors["ERROR"])
80-
}
81-
if status["running"] != nil && status["running"].(int) >= d.Get("parallelism").(int) {
82-
message = fmt.Sprintf("\x1b[%dmStatus: running \x1b[1m•\x1b[0m", colors["WARNING"])
83-
}
84-
}
85-
86-
if message == "logs" {
87-
message = ""
88-
logs := d.Get("logs").([]interface{})
89-
for index, log := range logs {
90-
prefix := fmt.Sprintf("\n\x1b[%dmLOG %d >> ", colors["foreground"], index)
91-
message += strings.Trim(strings.ReplaceAll("\n"+strings.Trim(log.(string), "\n"), "\n", prefix), "\n")
92-
if index+1 < len(logs) {
93-
message += "\n"
94-
}
32+
if d, ok := entry.Data["d"].(*schema.ResourceData); ok {
33+
switch message {
34+
case "instance":
35+
message = formatSchemaInstance(d)
36+
case "status":
37+
message = formatSchemaStatus(d)
38+
case "logs":
39+
message = formatSchemaLogs(d)
40+
default:
41+
return nil, errors.New("wrong schema logging mode")
9542
}
9643
}
9744

9845
newPrefix := fmt.Sprintf("\x1b[%dmTPI [%s]\x1b[0m", levelColor, levelText)
9946
return []byte(hideUnwantedPrefix(levelText, newPrefix, message)), nil
10047
}
10148

102-
func TpiLogger(d *schema.ResourceData) *logrus.Entry {
103-
logger := logrus.New()
104-
logger.SetFormatter(&tpiFormatter{})
105-
return logger.WithFields(logrus.Fields{"d": d})
106-
}
107-
10849
func hideUnwantedPrefix(levelText, newPrefix, message string) string {
10950
timeString := time.Now().Format("2006-01-02T15:04:05.000Z0700")
11051
unwantedPrefixLength := len(fmt.Sprintf("%s [%s] provider.terraform-provider-iterative: [%[2]s]", timeString, levelText))
@@ -118,3 +59,46 @@ func hideUnwantedPrefix(levelText, newPrefix, message string) string {
11859

11960
return output
12061
}
62+
63+
func formatSchemaInstance(d *schema.ResourceData) string {
64+
cloud := d.Get("cloud").(string)
65+
machine := d.Get("machine").(string)
66+
region := d.Get("region").(string)
67+
spot := d.Get("spot").(float64)
68+
69+
spottext := ""
70+
if spot > 0 {
71+
spottext = fmt.Sprintf("(Spot %f/h)", spot)
72+
}
73+
return fmt.Sprintf("%s %s%s in %s", cloud, machine, spottext, region)
74+
}
75+
76+
func formatSchemaStatus(d *schema.ResourceData) string {
77+
status := d.Get("status").(map[string]interface{})
78+
79+
message := fmt.Sprintf("\x1b[%dmStatus: queued \x1b[1m•\x1b[0m", colors["DEBUG"])
80+
if status["succeeded"] != nil && status["succeeded"].(int) >= d.Get("parallelism").(int) {
81+
message = fmt.Sprintf("\x1b[%dmStatus: completed successfully \x1b[1m•\x1b[0m", colors["SUCCESS"])
82+
}
83+
if status["failed"] != nil && status["failed"].(int) > 0 {
84+
message = fmt.Sprintf("\x1b[%dmStatus: completed with errors \x1b[1m•\x1b[0m", colors["ERROR"])
85+
}
86+
if status["running"] != nil && status["running"].(int) >= d.Get("parallelism").(int) {
87+
message = fmt.Sprintf("\x1b[%dmStatus: running \x1b[1m•\x1b[0m", colors["WARNING"])
88+
}
89+
return message
90+
}
91+
92+
func formatSchemaLogs(d *schema.ResourceData) string {
93+
logs := d.Get("logs").([]interface{})
94+
95+
message := ""
96+
for index, log := range logs {
97+
prefix := fmt.Sprintf("\n\x1b[%dmLOG %d >> ", colors["foreground"], index)
98+
message += strings.Trim(strings.ReplaceAll("\n"+strings.Trim(log.(string), "\n"), "\n", prefix), "\n")
99+
if index+1 < len(logs) {
100+
message += "\n"
101+
}
102+
}
103+
return message
104+
}

iterative/utils/logger_test.go

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import (
44
"testing"
55

66
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
7+
"github.com/sirupsen/logrus"
78
)
89

910
func TestState(t *testing.T) {
@@ -16,7 +17,8 @@ func TestState(t *testing.T) {
1617
},
1718
})
1819

19-
logger := TpiLogger(d)
20+
logger := logrus.WithFields(logrus.Fields{"d": d})
21+
logrus.SetFormatter(&TpiFormatter{})
2022
logger.Info("status")
2123
}
2224

@@ -30,7 +32,8 @@ func TestState2(t *testing.T) {
3032
},
3133
})
3234

33-
logger := TpiLogger(d)
35+
logger := logrus.WithFields(logrus.Fields{"d": d})
36+
logrus.SetFormatter(&TpiFormatter{})
3437
logger.Info("status")
3538
}
3639

@@ -44,7 +47,8 @@ func TestState3(t *testing.T) {
4447
},
4548
})
4649

47-
logger := TpiLogger(d)
50+
logger := logrus.WithFields(logrus.Fields{"d": d})
51+
logrus.SetFormatter(&TpiFormatter{})
4852
logger.Info("status")
4953
}
5054

@@ -57,7 +61,8 @@ func TestLogs(t *testing.T) {
5761
"logs": logs,
5862
})
5963

60-
logger := TpiLogger(d)
64+
logger := logrus.WithFields(logrus.Fields{"d": d})
65+
logrus.SetFormatter(&TpiFormatter{})
6166
logger.Info("logs")
6267
}
6368

@@ -70,7 +75,8 @@ func TestMachine(t *testing.T) {
7075
"region": "us-west",
7176
})
7277

73-
logger := TpiLogger(d)
78+
logger := logrus.WithFields(logrus.Fields{"d": d})
79+
logrus.SetFormatter(&TpiFormatter{})
7480
logger.Info("instance")
7581
}
7682

0 commit comments

Comments
 (0)