File: log.go

package info (click to toggle)
golang-github-akamai-akamaiopen-edgegrid-golang 1.0.1-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, bullseye, forky, sid, trixie
  • size: 1,408 kB
  • sloc: sh: 532; makefile: 3
file content (161 lines) | stat: -rw-r--r-- 4,036 bytes parent folder | download
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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
// Copyright 2018. Akamai Technologies, Inc
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package edgegrid

import (
	"bufio"
	"bytes"
	"encoding/json"
	"fmt"
	"net/http"
	"net/http/httputil"
	"os"
	"strings"

	logstd "log"

	log "github.com/sirupsen/logrus"
)

var logBuffer *bufio.Writer
var LogFile *os.File
var EdgegridLog *log.Logger

func SetupLogging() {

	if EdgegridLog != nil {
		return // already configured
	}

	EdgegridLog = log.New()
	EdgegridLog.SetFormatter(&log.TextFormatter{
		DisableLevelTruncation:    true,
		EnvironmentOverrideColors: true,
	})
	// Log file destination specified? If not, use default stdout
	if logFileName := os.Getenv("AKAMAI_LOG_FILE"); logFileName != "" {
		// If the file doesn't exist, create it, or append to the file
		LogFile, err := os.OpenFile(logFileName, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
		if err != nil {
			log.Fatal(err)
		}
		EdgegridLog.SetOutput(LogFile)
	}

	EdgegridLog.SetLevel(log.PanicLevel)
	if logLevel := os.Getenv("AKAMAI_LOG"); logLevel != "" {
		level, err := log.ParseLevel(logLevel)
		if err == nil {
			EdgegridLog.SetLevel(level)
		} else {
			log.Warningln("[WARN] Unknown AKAMAI_LOG value. Allowed values: panic, fatal, error, warn, info, debug, trace")

		}
	}

	defer LogFile.Close()
}

func LogMultiline(f func(args ...interface{}), args ...string) {
	for _, str := range args {
		for _, str := range strings.Split(strings.Trim(str, "\n"), "\n") {
			f(str)
		}
	}
}

func LogMultilineln(f func(args ...interface{}), args ...string) {
	LogMultiline(f, args...)
}

func LogMultilinef(f func(formatter string, args ...interface{}), formatter string, args ...interface{}) {
	str := fmt.Sprintf(formatter, args...)
	for _, str := range strings.Split(strings.Trim(str, "\n"), "\n") {
		f(str)
	}
}

// Utility func to print http req
func PrintHttpRequest(req *http.Request, body bool) {

	if req == nil {
		return
	}
	b, err := httputil.DumpRequestOut(req, body)
	if err == nil {
		LogMultiline(EdgegridLog.Traceln, string(b))
	}
}

func PrintHttpRequestCorrelation(req *http.Request, body bool, correlationid string) {

	if req == nil {
		return
	}
	b, err := httputil.DumpRequestOut(req, body)
	if err == nil {
		LogMultiline(EdgegridLog.Traceln, string(b))
		PrintfCorrelation("[DEBUG] REQUEST", correlationid, prettyPrintJsonLines(b))
	}
}

// Utility func to print http response
func PrintHttpResponse(res *http.Response, body bool) {

	if res == nil {
		return
	}
	b, err := httputil.DumpResponse(res, body)
	if err == nil {
		LogMultiline(EdgegridLog.Traceln, string(b))
	}
}

func PrintHttpResponseCorrelation(res *http.Response, body bool, correlationid string) {

	if res == nil {
		return
	}
	b, err := httputil.DumpResponse(res, body)
	if err == nil {
		LogMultiline(EdgegridLog.Traceln, string(b))
		PrintfCorrelation("[DEBUG] RESPONSE ", correlationid, prettyPrintJsonLines(b))
	}
}

func PrintfCorrelation(level string, correlationid string, msg string) {

	if correlationid == "" {
		logstd.Printf("%s  %s\n", level, msg)
	} else {
		logstd.SetFlags(0)
		logstd.Printf("%v %s\n", correlationid, msg)
	}

}

// prettyPrintJsonLines iterates through a []byte line-by-line,
// transforming any lines that are complete json into pretty-printed json.
func prettyPrintJsonLines(b []byte) string {
	parts := strings.Split(string(b), "\n")
	for i, p := range parts {
		if b := []byte(p); json.Valid(b) {
			var out bytes.Buffer
			json.Indent(&out, b, "", " ")
			parts[i] = out.String()
		}
	}
	return strings.Join(parts, "\n")
}