graylogger

package module
v1.0.1 Latest Latest
Warning

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

Go to latest
Published: May 11, 2020 License: MIT Imports: 14 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

GO - GrayLogger

Test Coverage Status GOdoc Version

This package was made to provide easy-to-analyze log messages.

It can be configured to:

  • print log messages only to standard output,
  • or send GELF messages to Graylog at the same time.

For sending GELF messages it uses the: github.com/Devatoria/go-graylog package.

Example output Example GELF message

Table of Contents

Logging levels

  • Debug : designates fine-grained informational events that are most useful to debug an application.
  • Info : designates informational messages that highlight the progress of the application at coarse-grained level.
  • Warning : designates potentially harmful situations.
  • Error : designates error events that might still allow the application to continue running.
  • Fatal : designates very severe error events that will presumably lead the application to abort.

Back to top

Example usage

Initialization
Example code
g := graylogger.New(graylogger.Init{
	// Optional fields for sending GELF messages to Graylog.
	GraylogHost:     "localhost",
	GraylogPort:     12201,
	GraylogProtocol: graylogger.TransportUDP,
	GraylogProvider: "ExampleService",

	// Obligatory fields.
	LogEnv:   "test",
	LogLevel: graylogger.LevelDebug,
	LogColor: true,
})

g.Debug("example", "debug message")
g.Info("example", "info message")
g.Warning("example", "warning message")
g.Error("example", "error message")

Back to top

Example output
[DEBUG] 2020/01/27 14:16:54 [file: example_usage.go line: 19 function: main.main] [example :: debug message]
[INFO] 2020/01/27 14:16:54 [file: example_usage.go line: 20 function: main.main] [example :: info message]
[WARNING] 2020/01/27 14:16:54 [file: example_usage.go line: 21 function: main.main] [example :: warning message]
[ERROR] 2020/01/27 14:16:54 [file: example_usage.go line: 22 function: main.main] [example :: error message]

Back to top

Example GELF message
{ 
   "_log_env":"test",
   "_log_key":"example",
   "_log_level":"debug",
   "_log_value":"debug message",
   "_track_file":"example_usage.go",
   "_track_function":"main.main",
   "_track_line":"19",
   "full_message":"example :: debug message",
   "host":"ExampleService",
   "level":7,
   "short_message":"example :: debug message",
   "timestamp":1580131354,
   "version":"1.1"
}

Back to top

Check error and logging at the same time
Example code
err := errors.New("example error message")

// Only logging error if it present
g.LogErrorIfErr(err)
g.LogWarningIfErr(err)

// Log error and exit with exit code 1
g.Fatal(err)

Back to top

Example output
[ERROR] 2020/01/27 14:36:49 [file: example_usage.go line: 26 function: main.main] [main.main :: example error message]
[WARNING] 2020/01/27 14:36:49 [file: example_usage.go line: 27 function: main.main] [main.main :: example error message]
[FATAL] 2020/01/27 14:36:49 [file: example_usage.go line: 30 function: main.main] [main.main :: example error message]
exit status 1

Back to top

Example GELF message
{ 
   "_log_env":"test",
   "_log_key":"main.main",
   "_log_level":"error",
   "_log_value":"example error message",
   "_track_file":"example_usage.go",
   "_track_function":"main.main",
   "_track_line":"24",
   "full_message":"main.main :: example error message",
   "host":"ExampleService",
   "level":3,
   "short_message":"main.main :: example error message",
   "timestamp":1580131737,
   "version":"1.1"
}

Back to top

Return with error and logging at the same time
Example code
err := g.ReturnWithError("example returned", "error message")
g.Fatal(err)

Back to top

Example output
[ERROR] 2020/01/27 14:42:34 [file: example_usage.go line: 21 function: main.main] [example returned :: error message]
[FATAL] 2020/01/27 14:42:34 [file: example_usage.go line: 22 function: main.main] [main.main :: example returned :: error message]
exit status 1

Back to top

Example GELF message
{
   "_log_env":"test",
   "_log_key":"example returned",
   "_log_level":"error",
   "_log_value":"error message",
   "_track_file":"example_usage.go",
   "_track_function":"main.main",
   "_track_line":"21",
   "full_message":"example :: error message",
   "host":"ExampleService",
   "level":3,
   "short_message":"example :: error message",
   "timestamp":1580132598,
   "version":"1.1"
}

Back to top

Re-initializing GrayLogger
Example code
// Before re-initialization it should log all logging levels
g.Debug("before re-init example", "debug message")
g.Info("before re-init example", "info message")
g.Warning("before re-init example", "warning message")
g.Error("before re-init example", "error message")

// Re-initialization
i := g.GetInit()
i.LogColor = false
i.LogLevel = graylogger.LevelWarning

g = graylogger.New(i)
fmt.Println()

// After re-initialization it should log only warning, error and fatal logging levels
g.Debug("after re-init example", "debug message")
g.Info("after re-init example", "info message")
g.Warning("after re-init example", "warning message")
g.Error("after re-init example", "error message")

Back to top

Example output
[DEBUG] 2020/01/27 14:55:03 [file: example_usage.go line: 23 function: main.main] [before re-init example :: debug message]
[INFO] 2020/01/27 14:55:03 [file: example_usage.go line: 24 function: main.main] [before re-init example :: info message]
[WARNING] 2020/01/27 14:55:03 [file: example_usage.go line: 25 function: main.main] [before re-init example :: warning message]
[ERROR] 2020/01/27 14:55:03 [file: example_usage.go line: 26 function: main.main] [before re-init example :: error message]

[WARNING] 2020/01/27 14:55:03 [file: example_usage.go line: 38 function: main.main] [after re-init example :: warning message]
[ERROR] 2020/01/27 14:55:03 [file: example_usage.go line: 39 function: main.main] [after re-init example :: error message]

Back to top

Save logs into a file
Example code
// Disable colored output ...
i := g.GetInit()
i.LogColor = false
g = graylogger.New(i)

g.Debug("before CaptureOutput example", "debug message")
fmt.Println()

// Open a file to write ...
g.CaptureOutput("example.out")

g.Debug("after CaptureOutput example", "debug message")
g.Info("after CaptureOutput example", "info message")
g.Warning("after CaptureOutput example", "warning message")
g.Error("after CaptureOutput example", "error message")

// Save output into the already opened file ...
g.SaveOutput()

// We can print content by GetOutput()
fmt.Println("g.GetOutput:")
fmt.Println(g.GetOutput())

// ... or by PrintOutput()
fmt.Println("g.PrintOutput:")
g.PrintOutput()

Back to top

Example output
[DEBUG] 2020/01/27 15:17:56 [file: example_usage.go line: 28 function: main.main] [before CaptureOutput example :: debug message]

g.GetOutput:
[DEBUG] 2020/01/27 15:17:56 [file: example_usage.go line: 34 function: main.main] [after CaptureOutput example :: debug message]
[INFO] 2020/01/27 15:17:56 [file: example_usage.go line: 35 function: main.main] [after CaptureOutput example :: info message]
[WARNING] 2020/01/27 15:17:56 [file: example_usage.go line: 36 function: main.main] [after CaptureOutput example :: warning message]
[ERROR] 2020/01/27 15:17:56 [file: example_usage.go line: 37 function: main.main] [after CaptureOutput example :: error message]

g.PrintOutput:
[DEBUG] 2020/01/27 15:17:56 [file: example_usage.go line: 34 function: main.main] [after CaptureOutput example :: debug message]
[INFO] 2020/01/27 15:17:56 [file: example_usage.go line: 35 function: main.main] [after CaptureOutput example :: info message]
[WARNING] 2020/01/27 15:17:56 [file: example_usage.go line: 36 function: main.main] [after CaptureOutput example :: warning message]
[ERROR] 2020/01/27 15:17:56 [file: example_usage.go line: 37 function: main.main] [after CaptureOutput example :: error message]

Back to top

Tracking / tracing functions
Example code
func main() {
	g := graylogger.New(graylogger.Init{
		// Optional fields for sending GELF messages to Graylog.
		GraylogHost:     "localhost",
		GraylogPort:     12201,
		GraylogProtocol: graylogger.TransportUDP,
		GraylogProvider: "ExampleService",

		// Obligatory fields.
		LogEnv:   "test",
		LogLevel: graylogger.LevelDebug,
		LogColor: true,
	})

	track := graylogger.Tracking(1)
	g.Debug("track.Line", track.Line)
	g.Debug("track.Function", track.Function)
	g.Debug("track.File", track.File)

	exampleFunction(g)
}

func exampleFunction(g *graylogger.GrayLogger) {
	track := graylogger.Tracking(1)
	g.Info("depth.1.track.Line", track.Line)
	g.Info("depth.1.track.Function", track.Function)
	g.Info("depth.1.track.File", track.File)

	track = graylogger.Tracking(2)
	g.Debug("depth.2.track.Line", track.Line)
	g.Debug("depth.2.track.Function", track.Function)
	g.Debug("depth.2.track.File", track.File)
}

Back to top

Example output
[DEBUG] 2020/01/27 15:47:40 [file: example_usage.go line: 22 function: main.main] [track.Line :: 21]
[DEBUG] 2020/01/27 15:47:40 [file: example_usage.go line: 23 function: main.main] [track.Function :: main.main]
[DEBUG] 2020/01/27 15:47:40 [file: example_usage.go line: 24 function: main.main] [track.File :: example_usage.go]
[INFO] 2020/01/27 15:47:40 [file: example_usage.go line: 31 function: main.exampleFunction] [depth.1.track.Line :: 30]
[INFO] 2020/01/27 15:47:40 [file: example_usage.go line: 32 function: main.exampleFunction] [depth.1.track.Function :: main.exampleFunction]
[INFO] 2020/01/27 15:47:40 [file: example_usage.go line: 33 function: main.exampleFunction] [depth.1.track.File :: example_usage.go]
[DEBUG] 2020/01/27 15:47:40 [file: example_usage.go line: 36 function: main.exampleFunction] [depth.2.track.Line :: 26]
[DEBUG] 2020/01/27 15:47:40 [file: example_usage.go line: 37 function: main.exampleFunction] [depth.2.track.Function :: main.main]
[DEBUG] 2020/01/27 15:47:40 [file: example_usage.go line: 38 function: main.exampleFunction] [depth.2.track.File :: example_usage.go]

Back to top

Documentation

Overview

graylogger was made to provide easy-to-analyze log messages. For sending GELF messages it uses the: https://github.com/Devatoria/go-graylog package.

Index

Examples

Constants

View Source
const (
	// TransportTCP  is connection-oriented, and a connection between client
	// and server is established (passive open) before data can be sent.
	TransportTCP Transport = "tcp"

	// TransportUDP is suitable for purposes where error checking
	// and correction are either not necessary or are performed in the application
	TransportUDP Transport = "udp"

	// LevelDebug logs everything
	LevelDebug LogLevel = "debug"

	// LevelInfo logs Info, Warnings and Errors
	LevelInfo LogLevel = "info"

	// LevelWarning logs Warning and Errors
	LevelWarning LogLevel = "warning"

	// LevelError logs just Errors
	LevelError LogLevel = "error"

	// LevelFatal logs just Fatal errors and aborts the application
	LevelFatal LogLevel = "fatal"
)

Variables

This section is empty.

Functions

This section is empty.

Types

type Functions

type Functions struct {
	Debug   *log.Logger // Designates fine-grained informational events that are most useful to debug an application.
	Info    *log.Logger // Designates informational messages that highlight the progress of the application at coarse-grained level.
	Warning *log.Logger // Designates potentially harmful situations.
	Error   *log.Logger // Designates error events that might still allow the application to continue running.
	Fatal   *log.Logger // Designates very severe error events that will presumably lead the application to abort.
}

Functions provide a different kind of logging writers which controlled by log level.

type GrayLogger

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

GrayLogger holds the needed data to use the functions of this package.

  • initData -> the data with which the package was initialized
  • functions -> logger functions: Debug, Info, Warning, Error, Fatal
  • level -> log level converted to integer
  • fileName -> set by CaptureOutput() function, provides the filename where output can be saved
  • fileOpen -> set by CaptureOutput() function, holds *os.File
  • graylog -> set by connect() function, it represents an established graylog connection

func New

func New(init Init) *GrayLogger

New configures the logging writers.

Example
package main

import (
	"fmt"

	"github.com/takattila/graylogger"
)

func main() {
	g := graylogger.New(graylogger.Init{
		LogEnv:   "test",
		LogLevel: graylogger.LevelDebug,
		LogColor: true,
	})

	fmt.Println(g.GetInit())

}
Output:
{ 0   100ms test debug true}

func (*GrayLogger) CaptureOutput

func (g *GrayLogger) CaptureOutput(fileName string) *GrayLogger

CaptureOutput will redirect logger output to a given fileName.

func (*GrayLogger) Debug

func (g *GrayLogger) Debug(keysAndValues ...interface{})

Debug writes Info to stdOut and sends GELF message to Graylog.

Example
package main

import (
	"fmt"
	"strings"

	"github.com/takattila/graylogger"
)

func main() {
	g := graylogger.New(graylogger.Init{
		LogEnv:   "test",
		LogLevel: graylogger.LevelDebug,
		LogColor: false,
	})

	g.CaptureOutput("test.out")
	g.Debug("test", graylogger.LevelDebug)
	g.SaveOutput()

	output := g.GetOutput()
	fmt.Println(strings.Contains(output, "[DEBUG]"))
	fmt.Println(strings.Contains(output, "file: output_example_test.go"))
	fmt.Println(strings.Contains(output, "function: graylogger_test.ExampleGrayLogger_Debug"))
	fmt.Println(strings.Contains(output, "[test :: debug]"))

}
Output:
true
true
true
true

func (*GrayLogger) DiscardOutput

func (g *GrayLogger) DiscardOutput()

DiscardOutput discards all level outputs and prevents sending messages to Graylog as well.

Example
package main

import (
	"fmt"

	"github.com/takattila/graylogger"
)

func main() {
	g := graylogger.New(graylogger.Init{
		LogEnv:   "test",
		LogLevel: graylogger.LevelDebug,
		LogColor: true,
	})

	g.DiscardOutput()

	fmt.Println(g.IsAllowedOutput())

}
Output:
false

func (*GrayLogger) Error

func (g *GrayLogger) Error(keysAndValues ...interface{})

Error writes Error to stdOut and sends GELF message to Graylog.

Example
package main

import (
	"fmt"
	"strings"

	"github.com/takattila/graylogger"
)

func main() {
	g := graylogger.New(graylogger.Init{
		LogEnv:   "test",
		LogLevel: graylogger.LevelDebug,
		LogColor: false,
	})

	g.CaptureOutput("test.out")
	g.Error("test", graylogger.LevelError)
	g.SaveOutput()

	output := g.GetOutput()
	fmt.Println(strings.Contains(output, "[ERROR]"))
	fmt.Println(strings.Contains(output, "file: output_example_test.go"))
	fmt.Println(strings.Contains(output, "function: graylogger_test.ExampleGrayLogger_Error"))
	fmt.Println(strings.Contains(output, "[test :: error]"))

}
Output:
true
true
true
true

func (*GrayLogger) Fatal

func (g *GrayLogger) Fatal(err error)

Fatal writes Error to stdOut and exit with exit code 1, if err doesn't nil. It also sends GELF message to Graylog, if it possible.

Example
package main

import (
	"fmt"

	"github.com/takattila/graylogger"
)

func main() {
	g := graylogger.New(graylogger.Init{
		LogEnv:   "test",
		LogLevel: graylogger.LevelDebug,
		LogColor: false,
	})

	err := fmt.Errorf("test :: %s", graylogger.LevelError)
	g.Fatal(err)

	// [FATAL] 2020/02/03 14:43:37 [file: example.go line: 17 function: main.main] [main.main :: test :: error]
	// exit status 1
}

func (*GrayLogger) GetInit

func (g *GrayLogger) GetInit() Init

GetInit returns with the initial logger data.

Example
package main

import (
	"fmt"

	"github.com/takattila/graylogger"
)

func main() {
	g := graylogger.New(graylogger.Init{
		LogEnv:   "test",
		LogLevel: graylogger.LevelDebug,
		LogColor: false,
	})

	init := g.GetInit()

	fmt.Println(init.LogEnv)
	fmt.Println(init.LogLevel)
	fmt.Println(init.LogColor)

}
Output:
test
debug
false

func (*GrayLogger) GetLogLevel

func (g *GrayLogger) GetLogLevel() (int, string)

GetLogLevel returns with the set log level (int, string).

Example
package main

import (
	"fmt"

	"github.com/takattila/graylogger"
)

func main() {
	g := graylogger.New(graylogger.Init{
		LogEnv:   "test",
		LogLevel: graylogger.LevelDebug,
		LogColor: true,
	})

	levelNum, levelString := g.GetLogLevel()

	fmt.Println(levelNum)
	fmt.Println(levelString)

}
Output:
7
debug

func (*GrayLogger) GetOutput

func (g *GrayLogger) GetOutput() string

GetOutput reads the file content what we set in the CaptureOutput() function.

Example
package main

import (
	"fmt"
	"strings"

	"github.com/takattila/graylogger"
)

func main() {
	g := graylogger.New(graylogger.Init{
		LogEnv:   "test",
		LogLevel: graylogger.LevelDebug,
		LogColor: false,
	})

	g.CaptureOutput("test.out")
	g.Debug("test", "get_output")
	g.SaveOutput()

	output := g.GetOutput()
	fmt.Println(strings.Contains(output, "[DEBUG]"))
	fmt.Println(strings.Contains(output, "file: output_example_test.go"))
	fmt.Println(strings.Contains(output, "function: graylogger_test.ExampleGrayLogger_GetOutput"))
	fmt.Println(strings.Contains(output, "[test :: get_output]"))

}
Output:
true
true
true
true

func (*GrayLogger) Info

func (g *GrayLogger) Info(keysAndValues ...interface{})

Info writes Info to stdOut and sends GELF message to Graylog.

Example
package main

import (
	"fmt"
	"strings"

	"github.com/takattila/graylogger"
)

func main() {
	g := graylogger.New(graylogger.Init{
		LogEnv:   "test",
		LogLevel: graylogger.LevelDebug,
		LogColor: false,
	})

	g.CaptureOutput("test.out")
	g.Info("test", graylogger.LevelInfo)
	g.SaveOutput()

	output := g.GetOutput()
	fmt.Println(strings.Contains(output, "[INFO]"))
	fmt.Println(strings.Contains(output, "file: output_example_test.go"))
	fmt.Println(strings.Contains(output, "function: graylogger_test.ExampleGrayLogger_Info"))
	fmt.Println(strings.Contains(output, "[test :: info]"))

}
Output:
true
true
true
true

func (*GrayLogger) IsAllowedOutput

func (g *GrayLogger) IsAllowedOutput() bool

IsAllowedOutput tells that StdOut is allowed or discarded on all log levels.

Example
package main

import (
	"fmt"

	"github.com/takattila/graylogger"
)

func main() {
	g := graylogger.New(graylogger.Init{
		LogEnv:   "test",
		LogLevel: graylogger.LevelDebug,
		LogColor: true,
	})

	fmt.Println(g.IsAllowedOutput())

}
Output:
true

func (*GrayLogger) LogErrorIfErr

func (g *GrayLogger) LogErrorIfErr(err error)

LogErrorIfErr only writes Error to stdOut, if err doesn't nil. It also sends GELF message to Graylog, if it possible.

Example
package main

import (
	"fmt"
	"strings"

	"github.com/takattila/graylogger"
)

func main() {
	g := graylogger.New(graylogger.Init{
		LogEnv:   "test",
		LogLevel: graylogger.LevelDebug,
		LogColor: false,
	})

	g.CaptureOutput("test.out")

	err := fmt.Errorf("test :: %s", graylogger.LevelError)
	g.LogErrorIfErr(err)
	g.SaveOutput()

	output := g.GetOutput()
	fmt.Println(strings.Contains(output, "[ERROR]"))
	fmt.Println(strings.Contains(output, "file: output_example_test.go"))
	fmt.Println(strings.Contains(output, "function: graylogger_test.ExampleGrayLogger_LogErrorIfErr"))
	fmt.Println(strings.Contains(output, "[graylogger_test.ExampleGrayLogger_LogErrorIfErr :: test :: error]"))

}
Output:
true
true
true
true

func (*GrayLogger) LogWarningIfErr

func (g *GrayLogger) LogWarningIfErr(err error)

LogWarningIfErr only writes Warning to stdOut, if err doesn't nil. It also sends GELF message to Graylog, if it possible.

Example
package main

import (
	"fmt"
	"strings"

	"github.com/takattila/graylogger"
)

func main() {
	g := graylogger.New(graylogger.Init{
		LogEnv:   "test",
		LogLevel: graylogger.LevelDebug,
		LogColor: false,
	})

	g.CaptureOutput("test.out")

	err := fmt.Errorf("test :: %s", graylogger.LevelWarning)
	g.LogWarningIfErr(err)
	g.SaveOutput()

	output := g.GetOutput()
	fmt.Println(strings.Contains(output, "[WARNING]"))
	fmt.Println(strings.Contains(output, "file: output_example_test.go"))
	fmt.Println(strings.Contains(output, "function: graylogger_test.ExampleGrayLogger_LogWarningIfErr"))
	fmt.Println(strings.Contains(output, "[graylogger_test.ExampleGrayLogger_LogWarningIfErr :: test :: warning]"))

}
Output:
true
true
true
true

func (*GrayLogger) PrintOutput

func (g *GrayLogger) PrintOutput()

PrintOutput prints out the file content what we set in the CaptureOutput() function.

Example
package main

import (
	"github.com/takattila/graylogger"
)

func main() {
	g := graylogger.New(graylogger.Init{
		LogEnv:   "test",
		LogLevel: graylogger.LevelDebug,
		LogColor: false,
	})

	g.CaptureOutput("test.out")
	g.Debug("test", "print_output")
	g.SaveOutput()

	g.PrintOutput()

	// [DEBUG] 2020/02/03 14:44:37 [file: example.go line: 15 function: main.main] [test :: print_output]
}

func (*GrayLogger) ResetLogger

func (g *GrayLogger) ResetLogger() *GrayLogger

ResetLogger allows StdOut with the initialized log level and allows sending messages to Graylog as well.

Example
package main

import (
	"fmt"

	"github.com/takattila/graylogger"
)

func main() {
	g := graylogger.New(graylogger.Init{
		LogEnv:   "test",
		LogLevel: graylogger.LevelDebug,
		LogColor: true,
	})

	g.DiscardOutput()
	fmt.Println(g.IsAllowedOutput())

	g = g.ResetLogger()
	fmt.Println(g.IsAllowedOutput())

}
Output:
false
true

func (*GrayLogger) ReturnWithError

func (g *GrayLogger) ReturnWithError(keysAndValues ...interface{}) error

ReturnWithError writes Error to stdOut and returns with that error message at the same time. It also sends GELF message to Graylog, if it possible.

Example
package main

import (
	"fmt"
	"strings"

	"github.com/takattila/graylogger"
)

func main() {
	g := graylogger.New(graylogger.Init{
		LogEnv:   "test",
		LogLevel: graylogger.LevelDebug,
		LogColor: false,
	})

	g.CaptureOutput("test.out")

	ret := g.ReturnWithError("test", graylogger.LevelError)
	g.SaveOutput()

	output := g.GetOutput()
	fmt.Println(strings.Contains(output, "[ERROR]"))
	fmt.Println(strings.Contains(output, "file: output_example_test.go"))
	fmt.Println(strings.Contains(output, "function: graylogger_test.ExampleGrayLogger_ReturnWithError"))
	fmt.Println(ret)

}
Output:
true
true
true
test :: error

func (*GrayLogger) SaveOutput

func (g *GrayLogger) SaveOutput()

SaveOutput will close the file, what we set in CaptureOutput() function and re-set the output of all logger functions .

Example
package main

import (
	"fmt"
	"strings"

	"github.com/takattila/graylogger"
)

func main() {
	g := graylogger.New(graylogger.Init{
		LogEnv:   "test",
		LogLevel: graylogger.LevelDebug,
		LogColor: false,
	})

	g.CaptureOutput("test.out")
	g.Debug("test", "save_output")
	g.SaveOutput()

	output := g.GetOutput()
	fmt.Println(strings.Contains(output, "[DEBUG]"))
	fmt.Println(strings.Contains(output, "file: output_example_test.go"))
	fmt.Println(strings.Contains(output, "function: graylogger_test.ExampleGrayLogger_SaveOutput"))
	fmt.Println(strings.Contains(output, "[test :: save_output]"))

}
Output:
true
true
true
true

func (*GrayLogger) SendGELF

func (g *GrayLogger) SendGELF(level int, keysAndValues ...interface{})

SendGELF sends GELF messages into Graylog instance. If the Graylog host is unreachable, it writes an error message to stdOut.

Example
package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"log"
	"net"
	"time"

	"github.com/takattila/graylogger"
)

func main() {
	//  UDP server initialization ...
	udpServer := func(port int, response chan string) {
		conn, err := net.ListenUDP("udp", &net.UDPAddr{
			Port: port,
			IP:   net.ParseIP("0.0.0.0"),
		})
		if err != nil {
			log.Fatalf("net.ListenUDP: %s\n", err)
		}

		defer func() {
			_ = conn.Close()
		}()

		message := make([]byte, 262144)
		_, _, err = conn.ReadFromUDP(message[:])
		if err != nil {
			log.Fatalf("conn.ReadFromUDP: %s\n", err)
		}

		response <- string(message)
	}

	// Setup Init structure ...
	init := graylogger.Init{
		GraylogHost:     "127.0.0.1",
		GraylogPort:     12201,
		GraylogProvider: "TestService",
		GraylogProtocol: graylogger.TransportUDP,

		LogEnv:   "test",
		LogLevel: graylogger.LevelDebug,
		LogColor: false,
	}

	// Starting UDP server ...
	response := make(chan string)
	go udpServer(init.GraylogPort, response)
	time.Sleep(100 * time.Millisecond)

	// GrayLogger initialization ...
	g := graylogger.New(init)

	g.CaptureOutput("test.out")
	g.Info("test", "gelf_message")
	g.SaveOutput()

	// Removing NUL characters from bytes
	responseBytes := bytes.Trim([]byte(<-response), "\x00")

	// Parsing JSON response ...
	obj := map[string]interface{}{}
	err := json.Unmarshal(responseBytes, &obj)
	if err != nil {
		log.Fatalf("json.Unmarshal: %v\n", err)
	}

	fmt.Println(obj["_log_env"])
	fmt.Println(obj["_log_key"])
	fmt.Println(obj["_log_level"])
	fmt.Println(obj["_log_value"])
	fmt.Println(obj["_track_file"])
	fmt.Println(obj["_track_function"])
	fmt.Println(obj["full_message"])
	fmt.Println(obj["short_message"])
	fmt.Println(obj["host"])
	fmt.Println(obj["version"])
	fmt.Println(obj["level"])

}
Output:
test
test
info
gelf_message
graylog_example_test.go
graylogger_test.ExampleGrayLogger_SendGELF
test :: gelf_message
test :: gelf_message
TestService
1.1
6

func (*GrayLogger) Warning

func (g *GrayLogger) Warning(keysAndValues ...interface{})

Warning writes Warning to stdOut and sends GELF message to Graylog.

Example
package main

import (
	"fmt"
	"strings"

	"github.com/takattila/graylogger"
)

func main() {
	g := graylogger.New(graylogger.Init{
		LogEnv:   "test",
		LogLevel: graylogger.LevelDebug,
		LogColor: false,
	})

	g.CaptureOutput("test.out")
	g.Warning("test", graylogger.LevelWarning)
	g.SaveOutput()

	output := g.GetOutput()
	fmt.Println(strings.Contains(output, "[WARNING]"))
	fmt.Println(strings.Contains(output, "file: output_example_test.go"))
	fmt.Println(strings.Contains(output, "function: graylogger_test.ExampleGrayLogger_Warning"))
	fmt.Println(strings.Contains(output, "[test :: warning]"))

}
Output:
true
true
true
true

type GraylogExtraFields

type GraylogExtraFields struct {
	Env      string `json:"log_env"`
	Level    string `json:"log_level"`
	Key      string `json:"log_key"`
	Value    string `json:"log_value"`
	Line     string `json:"track_line"`
	File     string `json:"track_file"`
	Function string `json:"track_function"`
}

GraylogExtraFields represents the extra GELF data which will be sent into Graylog instance.

type Init

type Init struct {
	GraylogHost     string        // Host name of the Graylog server
	GraylogPort     int           // Port number of the Graylog server
	GraylogProvider string        // The Name of the service which generates the log messages or sends logs into Graylog
	GraylogProtocol Transport     // The name of the transport protocol: the way we send GELF messages (TransportTCP or TransportUDP)
	GraylogTimeout  time.Duration // Optional, it declares the maximum amount of time a dial will wait for a connection to complete.

	LogEnv   string   // Environment of the service: dev / test / prod
	LogLevel LogLevel // It can be: debug, info, warning, error
	LogColor bool     // Turn on/off colored log output. Color output can be useful during development, but it is recommended to turn it off in production environment.
}

Init initializes the logger instance

type LogLevel

type LogLevel string

LogLevel defines the log levels that can be entered.

type TrackInfo

type TrackInfo struct {
	File     string
	Line     string
	Function string
}

TrackInfo holds debug information about the caller's:

  • File name
  • Line number
  • Function name

func Tracking

func Tracking(depth int) TrackInfo

Tracking provides debug information about function invocations on the calling goroutine's stack:

  • File (where Tracking was called)
  • Line (where function was called)
  • Function (name of the function)
Example
package main

import (
	"fmt"
	"strconv"

	"github.com/takattila/graylogger"
)

func main() {
	track := graylogger.Tracking(1)

	fmt.Println(track.File)

	num, _ := strconv.Atoi(track.Line)
	fmt.Printf("%T\n", num)

	fmt.Println(track.Function)

}
Output:
output_example_test.go
int
graylogger_test.ExampleTracking

type Transport

type Transport string

Transport declares the the way we send GELF messages (TransportTCP or TransportUDP).

Jump to

Keyboard shortcuts

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