coralogix

package module
v1.0.6 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 18, 2024 License: Apache-2.0 Imports: 18 Imported by: 0

README

Coralogix Go SDK

goreportcard Go Reference license Build Status codecov Maintainability Test Coverage GitHub issues GitHub pull requests GitHub contributors

This package provides logging suites integrated with Coralogix logs analytics platform. For watch how to use it, please, read Coralogix Go SDK Docs.

Documentation

Overview

Package coralogix provides SDK for sending logs to Coralogix.

The simple example:

package main

import (
    coralogix "github.com/coralogix/go-coralogix-sdk"
)

func main() {
    coralogix.SetDebug(true)

    logger := coralogix.NewCoralogixLogger(
        "YOUR_PRIVATE_KEY_HERE",
        "YOUR_APPLICATION_NAME",
        "YOUR_SUBSYSTEM_NAME",
    )
    defer logger.Destroy()

    logger.Debug("Test message 1")
    logger.Info(map[string]string{
        "text":  "Test message 2",
        "extra": "additional",
    })
    logger.Warning("Test message 4")
}

If you want to use Coralogix SDK with Logrus logging library:

package main

import (
    coralogix "github.com/coralogix/go-coralogix-sdk"
    "github.com/sirupsen/logrus"
)

func main() {
    CoralogixHook := coralogix.NewCoralogixHook(
        "YOUR_PRIVATE_KEY_HERE",
        "YOUR_APPLICATION_NAME",
        "YOUR_SUBSYSTEM_NAME",
    )
    defer CoralogixHook.Close()

    log := logrus.New()
    log.SetLevel(logrus.DebugLevel)

    log.AddHook(CoralogixHook)

    log.Info("Test message!")
    log.WithFields(logrus.Fields{
        "Category":   "MyCategory",
        "ClassName":  "MyClassName",
        "MethodName": "MyMethodName",
        "ThreadId":   "MyThreadId",
    }).Info("Test message 2!")
    log.WithFields(logrus.Fields{
        "extra": "additional",
    }).Info("Test message 3!")
    log.Debug("Test message 4!")
    log.Fatal("Test message 5!")
}

For a source watch https://github.com/coralogix/go-coralogix-sdk

Copyright 2021 Coralogix Ltd. All rights reserved. Use of this source code is governed by a Apache 2.0 license that can be found in the LICENSE file.

Index

Constants

View Source
const (
	// MaxLogBufferSize is maximum log buffer size (default=128MiB)
	MaxLogBufferSize uint64 = 128 * (1024 * 1024)

	// MaxLogChunkSize is maximum chunk size (default=1.5MiB)
	MaxLogChunkSize uint64 = 1.5 * (1024 * 1024)

	// NormalSendSpeedInterval is a bulk send interval in normal mode
	NormalSendSpeedInterval = 1 * time.Second

	// FastSendSpeedInterval is a bulk send interval in fast mode
	FastSendSpeedInterval = 500 * time.Millisecond

	// TimeDelayTimeout is a timeout for time-delay request
	TimeDelayTimeout uint = 5

	// FailedPrivateKey is a default private key
	FailedPrivateKey string = "no private key"

	// NoAppName is a default application name
	NoAppName string = "NO_APP_NAME"

	// NoSubSystem is a default subsystem name
	NoSubSystem string = "NO_SUB_NAME"

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

	// 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

	// LogCategory is a default category for log record
	LogCategory string = "CORALOGIX"

	// SyncTimeUpdateInterval is a time synchronization interval (in minutes)
	SyncTimeUpdateInterval uint = 5
)

Variables

View Source
var (
	// 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")

	// Headers is the list of headers added to each send logs request
	Headers http.Header = func() http.Header {
		headers := GetEnv("CORALOGIX_HEADERS", "")
		tp := textproto.NewReader(bufio.NewReader(strings.NewReader(headers)))
		mimeHeader, err := tp.ReadMIMEHeader()
		if err != nil {
			mimeHeader = map[string][]string{}
		}
		mimeHeader.Set("Content-Type", "application/json")
		return http.Header(mimeHeader)
	}()
)
View Source
var DebugLogger = log.New(ioutil.Discard, "CORALOGIX: ", log.Ldate|log.Ltime)

DebugLogger is the internal logger (disabled by default)

View Source
var Level = SeveritiesList{
	1,
	1,
	2,
	3,
	4,
	5,
	6,
	6,
	6,
}

Level is a list with default logs levels values

Functions

func GetEnv added in v1.0.1

func GetEnv(Variable string, Default string) string

GetEnv receives environment variable or default value

func GetTimeSync

func GetTimeSync() (bool, float64)

GetTimeSync synchronize logs time with Coralogix servers time

func MessageToString

func MessageToString(Message interface{}) string

MessageToString convert log content to simple string

func SendRequest

func SendRequest(Bulk *Bulk) int

SendRequest send logs data to Coralogix server

func SetDebug

func SetDebug(Status bool)

SetDebug enable/disable internal logger

Types

type Bulk

type Bulk struct {
	PrivateKey      string `json:"privateKey"`      // Coralogix private key
	ApplicationName string `json:"applicationName"` // Your application name
	SubsystemName   string `json:"subsystemName"`   // Subsystem name of your application
	ComputerName    string `json:"computerName"`    // Current machine hostname
	LogEntries      []Log  `json:"logEntries"`      // Log records list
}

Bulk describe logs batch format for Coralogix API

func NewBulk

func NewBulk(Credentials Credentials) *Bulk

NewBulk initialize new logs bulk

func (*Bulk) AddRecord

func (bulk *Bulk) AddRecord(Record Log)

AddRecord add log record to the logs bulk

func (*Bulk) ToJSON

func (bulk *Bulk) ToJSON() []byte

ToJSON convert logs bulk to JSON format

type CoralogixHandler added in v1.0.4

type CoralogixHandler struct {
	// contains filtered or unexported fields
}

func NewCoralogixHandler added in v1.0.4

func NewCoralogixHandler(privateKey, applicationName, subsystemName string, opts *slog.HandlerOptions) *CoralogixHandler

func (*CoralogixHandler) Enabled added in v1.0.4

func (h *CoralogixHandler) Enabled(ctx context.Context, level slog.Level) bool

Enabled reports whether the logger emits log records at the given context and level. Note: We handover the decision down to the next handler.

func (*CoralogixHandler) Handle added in v1.0.4

func (h *CoralogixHandler) Handle(ctx context.Context, r slog.Record) error

Handle handles the provided log record.

func (*CoralogixHandler) Stop added in v1.0.4

func (h *CoralogixHandler) Stop()

func (*CoralogixHandler) WithAttrs added in v1.0.4

func (h *CoralogixHandler) WithAttrs(attrs []slog.Attr) slog.Handler

WithAttrs returns a new Coralogix whose attributes consists of handler's attributes followed by attrs.

func (*CoralogixHandler) WithGroup added in v1.0.4

func (h *CoralogixHandler) WithGroup(name string) slog.Handler

WithGroup returns a new Coralogix with a group, provided the group's name.

type CoralogixLogger

type CoralogixLogger struct {
	Category      string        // Current logger logs records category
	LoggerManager LoggerManager // CoralogixLogger manager instance
}

CoralogixLogger is interface for using SDK

func NewCoralogixLogger

func NewCoralogixLogger(PrivateKey string, ApplicationName string, SubsystemName string) *CoralogixLogger

NewCoralogixLogger initialize new SDK interface instance

func NewCoralogixLoggerWithCategory

func NewCoralogixLoggerWithCategory(PrivateKey string, ApplicationName string, SubsystemName string, Category string) *CoralogixLogger

NewCoralogixLoggerWithCategory initialize new SDK interface instance with custom category

func (*CoralogixLogger) Critical

func (logger *CoralogixLogger) Critical(Text interface{})

Critical send log message with CRITICAL severity level

func (*CoralogixLogger) Debug

func (logger *CoralogixLogger) Debug(Text interface{})

Debug send log message with DEBUG severity level

func (*CoralogixLogger) Destroy

func (logger *CoralogixLogger) Destroy()

Destroy stop logger manager and cleanup logs buffer before exit

func (*CoralogixLogger) Error

func (logger *CoralogixLogger) Error(Text interface{})

Error send log message with ERROR severity level

func (*CoralogixLogger) Info

func (logger *CoralogixLogger) Info(Text interface{})

Info send log message with INFO severity level

func (*CoralogixLogger) Log

func (logger *CoralogixLogger) Log(Severity uint, Text interface{}, Category string, ClassName string, MethodName string, ThreadID string)

Log send record message to logger manager

func (*CoralogixLogger) Verbose

func (logger *CoralogixLogger) Verbose(Text interface{})

Verbose send log message with VERBOSE severity level

func (*CoralogixLogger) Warning

func (logger *CoralogixLogger) Warning(Text interface{})

Warning send log message with WARNING severity level

type Credentials

type Credentials struct {
	PrivateKey      string // Coralogix private key
	ApplicationName string // Your application name
	SubsystemName   string // Subsystem name of your application
}

Credentials is the container for Coralogix data

type Hook

type Hook struct {
	Writer LoggerManager
}

Hook is presenting Coralogix Logger for Logrus library

func NewCoralogixHook

func NewCoralogixHook(PrivateKey string, ApplicationName string, SubsystemName string) *Hook

NewCoralogixHook build Coralogix logger hook

func (*Hook) Close

func (hook *Hook) Close()

Close is a defer function for buffer cleanup before exit

func (*Hook) Fire

func (hook *Hook) Fire(entry *logrus.Entry) error

Fire send message to Coralogix

func (*Hook) Levels

func (hook *Hook) Levels() []logrus.Level

Levels return levels which can be sent with this hook

type Log

type Log struct {
	Timestamp  float64 `json:"timestamp"`  // Log record timestamp
	Severity   uint    `json:"severity"`   // Log record severity level
	Text       string  `json:"text"`       // Log record message
	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
	// contains filtered or unexported fields
}

Log describe record format for Coralogix API

func (*Log) Size

func (Record *Log) Size() uint64

Size calculate log record length in bytes

type LogBuffer added in v1.0.3

type LogBuffer struct {
	// contains filtered or unexported fields
}

func (*LogBuffer) Append added in v1.0.3

func (lb *LogBuffer) Append(log Log)

func (*LogBuffer) Len added in v1.0.3

func (lb *LogBuffer) Len() int

func (*LogBuffer) Size added in v1.0.3

func (lb *LogBuffer) Size() uint64

func (*LogBuffer) Slice added in v1.0.3

func (lb *LogBuffer) Slice(i int) []Log

type LoggerManager

type LoggerManager struct {
	SyncTime            bool           // Synchronize time with Coralogix servers
	TimeDelta           float64        // Time difference between local machine and Coralogix servers
	TimeDeltaLastUpdate int            // Last time-delta update time
	Stopped             bool           // Is current logger manager stopped
	SendInterval        time.Duration  // Send bulk logs interval
	LogsBuffer          LogBuffer      // Logs buffer
	Credentials                        // Credentials for Coralogix account
	Lock                sync.WaitGroup // CoralogixLogger manager locker
}

LoggerManager is a logs buffer operations manager

func NewLoggerManager

func NewLoggerManager(PrivateKey string, ApplicationName string, SubsystemName string, SyncTime bool) *LoggerManager

NewLoggerManager configure new logger manager instance

func (*LoggerManager) AddLogLine

func (manager *LoggerManager) AddLogLine(Severity uint, Text interface{}, Category string, ClassName string, MethodName string, ThreadID string)

AddLogLine push log record to buffer

func (*LoggerManager) Flush

func (manager *LoggerManager) Flush()

Flush clean buffer and send logs to Coralogix

func (*LoggerManager) Run

func (manager *LoggerManager) Run()

Run should work in separate thread and asynchronously operate with logs

func (*LoggerManager) SendBulk

func (manager *LoggerManager) SendBulk(SyncTime bool) bool

SendBulk send logs bulk to Coralogix

func (*LoggerManager) SendInitMessage

func (manager *LoggerManager) SendInitMessage()

SendInitMessage send initialization message to Coralogix for connection verify

func (*LoggerManager) Stop

func (manager *LoggerManager) Stop()

Stop logger manager and kill threaded agent

func (*LoggerManager) UpdateTimeDeltaInterval

func (manager *LoggerManager) UpdateTimeDeltaInterval()

UpdateTimeDeltaInterval get time difference between local machine and Coralogix servers

type SeveritiesList

type SeveritiesList struct {
	TRACE    uint
	DEBUG    uint
	VERBOSE  uint
	INFO     uint
	WARNING  uint
	ERROR    uint
	CRITICAL uint
	FATAL    uint
	PANIC    uint
}

SeveritiesList describe logs levels values

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL