Skip to content

Commit

Permalink
Logrus Caller reporter added (#5)
Browse files Browse the repository at this point in the history
  • Loading branch information
EldarAliiev authored Oct 5, 2020
1 parent ee0023b commit 61b4c88
Show file tree
Hide file tree
Showing 10 changed files with 77 additions and 37 deletions.
20 changes: 10 additions & 10 deletions constant.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,14 +25,14 @@ const (
// NoSubSystem is a default subsystem name
NoSubSystem string = "NO_SUB_NAME"

// HttpTimeout is a default HTTP timeout
HttpTimeout uint = 30
// HTTPTimeout is a default HTTP timeout
HTTPTimeout uint = 30

// HttpSendRetryCount is a number of attempts to retry HTTP request
HttpSendRetryCount uint = 5
// HTTPSendRetryCount is a number of attempts to retry HTTP request
HTTPSendRetryCount uint = 5

// HttpSendRetryInterval is a interval between failed http post requests
HttpSendRetryInterval uint = 2
// HTTPSendRetryInterval is a interval between failed http post requests
HTTPSendRetryInterval uint = 2

// LogCategory is a default category for log record
LogCategory string = "CORALOGIX"
Expand All @@ -42,9 +42,9 @@ const (
)

var (
// LogUrl is the Coralogix logs url endpoint
LogUrl string = GetEnv("CORALOGIX_LOG_URL", "https://api.coralogix.com:443/api/v1/logs")
// LogURL is the Coralogix logs url endpoint
LogURL string = GetEnv("CORALOGIX_LOG_URL", "https://api.coralogix.com:443/api/v1/logs")

// TimeDeltaUrl is the Coralogix time delay url endpoint
TimeDeltaUrl string = GetEnv("CORALOGIX_TIME_DELTA_URL", "https://api.coralogix.com:443/sdk/v1/time")
// TimeDeltaURL is the Coralogix time delay url endpoint
TimeDeltaURL string = GetEnv("CORALOGIX_TIME_DELTA_URL", "https://api.coralogix.com:443/sdk/v1/time")
)
20 changes: 14 additions & 6 deletions hook.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ func (hook *Hook) Fire(entry *logrus.Entry) error {
Category string
ClassName string
MethodName string
ThreadId string
ThreadID string
)

switch entry.Level {
Expand Down Expand Up @@ -64,21 +64,29 @@ func (hook *Hook) Fire(entry *logrus.Entry) error {
ClassName = Value.(string)
delete(entry.Data, "ClassName")
} else {
ClassName = ""
if entry.HasCaller() {
ClassName = entry.Caller.File
} else {
ClassName = ""
}
}

if Value, Exist := entry.Data["MethodName"]; Exist {
MethodName = Value.(string)
delete(entry.Data, "MethodName")
} else {
MethodName = ""
if entry.HasCaller() {
MethodName = entry.Caller.Function
} else {
MethodName = ""
}
}

if Value, Exist := entry.Data["ThreadId"]; Exist {
ThreadId = Value.(string)
ThreadID = Value.(string)
delete(entry.Data, "ThreadId")
} else {
ThreadId = ""
ThreadID = ""
}

if len(entry.Data) > 0 {
Expand All @@ -99,7 +107,7 @@ func (hook *Hook) Fire(entry *logrus.Entry) error {
Category,
ClassName,
MethodName,
ThreadId,
ThreadID,
},
)

Expand Down
32 changes: 32 additions & 0 deletions hook_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,3 +37,35 @@ func TestHook_Send(t *testing.T) {
log.Error("Test error message!")
log.Panic("Test panic message!")
}

func TestHook_SendWithCaller(t *testing.T) {
CoralogixHook := NewCoralogixHook(
GetEnv(
"PRIVATE_KEY",
"7569303a-6269-4d2c-bf14-1aec9b1786a4",
),
"sdk-go",
"test",
)
defer func() { recover() }()
defer CoralogixHook.Close()

log := logrus.New()
log.SetReportCaller(true)
log.SetLevel(logrus.TraceLevel)

log.AddHook(CoralogixHook)

log.WithFields(logrus.Fields{
"Category": "MyCategory",
"ThreadId": "MyThreadId",
"extra": "additional",
}).Debug("Test message!")

log.Trace("Test trace message with caller!")
log.Debug("Test debug message with caller!")
log.Info("Test info message with caller!")
log.Warn("Test warn message with caller!")
log.Error("Test error message with caller!")
log.Panic("Test panic message with caller!")
}
10 changes: 5 additions & 5 deletions http.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,13 @@ import (
// SendRequest send logs data to Coralogix server
func SendRequest(Bulk *Bulk) int {
client := &http.Client{
Timeout: time.Duration(time.Duration(HttpTimeout) * time.Second),
Timeout: time.Duration(time.Duration(HTTPTimeout) * time.Second),
}

for Attempt := 1; uint(Attempt) <= HttpSendRetryCount; Attempt++ {
for Attempt := 1; uint(Attempt) <= HTTPSendRetryCount; Attempt++ {
DebugLogger.Println("About to send bulk to Coralogix server. Attempt number:", Attempt)

response, err := client.Post(LogUrl, "application/json", bytes.NewBuffer(Bulk.ToJSON()))
response, err := client.Post(LogURL, "application/json", bytes.NewBuffer(Bulk.ToJSON()))

if err != nil {
DebugLogger.Println("Can't execute HTTP request:", err)
Expand All @@ -31,7 +31,7 @@ func SendRequest(Bulk *Bulk) int {
return response.StatusCode
}

time.Sleep(time.Duration(HttpSendRetryInterval) * time.Second)
time.Sleep(time.Duration(HTTPSendRetryInterval) * time.Second)
}

return 0
Expand All @@ -45,7 +45,7 @@ func GetTimeSync() (bool, float64) {
Timeout: time.Duration(time.Duration(TimeDelayTimeout) * time.Second),
}

response, err := client.Get(TimeDeltaUrl)
response, err := client.Get(TimeDeltaURL)

if err != nil {
DebugLogger.Println("Can't execute HTTP request:", err)
Expand Down
12 changes: 6 additions & 6 deletions http_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,8 @@ func TestSendRequestSuccess(t *testing.T) {
"",
"",
})
HttpStatus := SendRequest(BulkToSend)
if HttpStatus != 200 {
HTTPStatus := SendRequest(BulkToSend)
if HTTPStatus != 200 {
t.Error("Logs bulk sending failed!")
}
}
Expand All @@ -27,8 +27,8 @@ func TestSendRequestPostFail(t *testing.T) {
SetDebug(true)
BulkToSend := CreateBulk()
BulkToSend.AddRecord(*InvalidLogMessage())
HttpStatus := SendRequest(BulkToSend)
if HttpStatus > 0 {
HTTPStatus := SendRequest(BulkToSend)
if HTTPStatus > 0 {
t.Error("Sending of invalid request should be failed!")
}
}
Expand All @@ -44,8 +44,8 @@ func TestSendRequestErrorResponseStatus(t *testing.T) {
"",
"",
})
HttpStatus := SendRequest(BulkToSend)
if HttpStatus == 200 {
HTTPStatus := SendRequest(BulkToSend)
if HTTPStatus == 200 {
t.Error("Logs bulk was successful!")
}
}
Expand Down
2 changes: 1 addition & 1 deletion log.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ type Log struct {
Category string `json:"category"` // Log record category
ClassName string `json:"className"` // Log record class name
MethodName string `json:"methodName"` // Log record method name
ThreadId string `json:"threadId"` // Thread ID
ThreadID string `json:"threadId"` // Thread ID
}

// Size calculate log record length in bytes
Expand Down
4 changes: 2 additions & 2 deletions logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -59,11 +59,11 @@ func (logger *CoralogixLogger) Destroy() {
}

// Log send record message to logger manager
func (logger *CoralogixLogger) Log(Severity uint, Text interface{}, Category string, ClassName string, MethodName string, ThreadId string) {
func (logger *CoralogixLogger) Log(Severity uint, Text interface{}, Category string, ClassName string, MethodName string, ThreadID string) {
if Category == "" {
Category = logger.Category
}
logger.LoggerManager.AddLogLine(Severity, Text, Category, ClassName, MethodName, ThreadId)
logger.LoggerManager.AddLogLine(Severity, Text, Category, ClassName, MethodName, ThreadID)
}

// Debug send log message with DEBUG severity level
Expand Down
6 changes: 3 additions & 3 deletions manager.go
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ func (manager *LoggerManager) SendInitMessage() {
"The Application Name %s and Subsystem Name %s from the Go SDK, version %s has started to send data",
manager.ApplicationName,
manager.SubsystemName,
SDK_VERSION,
sdkVersion,
),
LogCategory,
"",
Expand All @@ -73,7 +73,7 @@ func (manager *LoggerManager) SendInitMessage() {
}

// AddLogLine push log record to buffer
func (manager *LoggerManager) AddLogLine(Severity uint, Text interface{}, Category string, ClassName string, MethodName string, ThreadId string) {
func (manager *LoggerManager) AddLogLine(Severity uint, Text interface{}, Category string, ClassName string, MethodName string, ThreadID string) {
if manager.LogsBufferLength() < MaxLogBufferSize {
if Severity < Level.DEBUG || Severity > Level.CRITICAL {
Severity = Level.INFO
Expand All @@ -92,7 +92,7 @@ func (manager *LoggerManager) AddLogLine(Severity uint, Text interface{}, Catego
Category,
ClassName,
MethodName,
ThreadId,
ThreadID,
}

if MaxLogChunkSize <= uint64(NewLogRecord.Size()) {
Expand Down
4 changes: 2 additions & 2 deletions manager_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ type TestDummyStruct struct {
func TestNewLoggerManager(t *testing.T) {
NewLoggerManagerTestInstance := CreateLoggerManager()
if reflect.TypeOf(NewLoggerManagerTestInstance) != reflect.TypeOf(&LoggerManager{}) ||
!strings.Contains(NewLoggerManagerTestInstance.LogsBuffer[0].Text, SDK_VERSION) {
!strings.Contains(NewLoggerManagerTestInstance.LogsBuffer[0].Text, sdkVersion) {
t.Error("CoralogixLogger manager creation failed!")
}
}
Expand Down Expand Up @@ -63,7 +63,7 @@ func TestLoggerManager_LogsBufferLengthFail(t *testing.T) {
func TestLoggerManager_SendInitMessage(t *testing.T) {
NewLoggerManagerTestInstance := CreateLoggerManager()
NewLoggerManagerTestInstance.SendInitMessage()
if !strings.Contains(NewLoggerManagerTestInstance.LogsBuffer[1].Text, SDK_VERSION) {
if !strings.Contains(NewLoggerManagerTestInstance.LogsBuffer[1].Text, sdkVersion) {
t.Error("Initial message sending failed!")
}
}
Expand Down
4 changes: 2 additions & 2 deletions version.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package coralogix

// SDK_VERSION contains Coralogix Go SDK version
const SDK_VERSION = "1.0.0"
// sdkVersion contains Coralogix Go SDK version
const sdkVersion = "1.0.1"

0 comments on commit 61b4c88

Please sign in to comment.