log

package module
v1.1.0 Latest Latest
Warning

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

Go to latest
Published: Jul 5, 2024 License: Apache-2.0 Imports: 16 Imported by: 0

README ΒΆ

πŸ“œ Log Package

Generic badge Generic badge Generic badge

πŸ“Œ Getting Started

go get -u github.com/gerins/log

πŸ€ Sample Log Request

{"time":"2024-06-28T20:02:49.496462+07:00","level":"DEBUG","msg":"Testing Global Log Debug"}
{"time":"2024-06-28T20:02:49.499957+07:00","level":"INFO","msg":"Testing Global Log Info"}
{"time":"2024-06-28T20:02:49.500123+07:00","level":"WARN","msg":"Testing Global Log Warn"}
{"time":"2024-06-28T20:02:49.500188+07:00","level":"ERROR","msg":"Testing Global Log Error"}
{
    "time": "2024-06-28T20:00:02.089362+07:00",
    "level": "TRACE",
    "caller": "log/request.go:66",
    "processID": "oWCEjmzbdw7AMuob17wa",
    "ip": "127.0.0.1",
    "method": "GET",
    "url": "localhost:8080/",
    "statusCode": 200,
    "requestDuration": 104,
    "requestHeader": {
        "Accept": [
            "*/*"
        ],
        "User-Agent": [
            "curl/8.6.0"
        ]
    },
    "requestBody": {},
    "responseHeader": {
        "Content-Type": [
            "text/plain; charset=UTF-8"
        ]
    },
    "responseBody": null,
    "extraData": {
        "userData": {
            "Name": "Bob",
            "Age": 29
        }
    },
    "subLog": [
        {
            "level": "[DEBUG] echo/main.go:43",
            "message": "Testing Log Request Debug"
        },
        {
            "level": "[INFO] echo/main.go:44",
            "message": "Testing Log Request Info"
        },
        {
            "level": "[WARN] echo/main.go:45",
            "message": "Testing Log Request Warn"
        },
        {
            "level": "[ERROR] echo/main.go:46",
            "message": "Testing Log Request Error"
        },
        {
            "level": "[DURATION] echo/main.go:54",
            "message": "[104.193ms] handler total process duration"
        }
    ]
}
Echo
package main

import (
	"context"
	"net/http"
	"time"

	"github.com/labstack/echo/v4"
	"github.com/labstack/echo/v4/middleware"

	"github.com/gerins/log"
	middlewareLog "github.com/gerins/log/middleware/echo"
)

func main() {
	// Using the default configuration. Please use InitWithConfig() for the production environment.
	log.Init()
	e := echo.New()

	// Initialize logging middleware
	e.Use(middlewareLog.SetLogRequest())                       // Mandatory
	e.Use(middleware.BodyDump(middlewareLog.SaveLogRequest())) // Mandatory

	// Route to simulate logging request
	e.GET("/", func(c echo.Context) error {
		// Get context from echo locals
		ctx := c.Get("ctx").(context.Context)

		// Capture a duration for a function
		defer log.Context(ctx).RecordDuration("handler total process duration").Stop()
		time.Sleep(100 * time.Millisecond) // Simulate a process

		// Add some extra data
		log.Context(ctx).ExtraData["userData"] = struct {
			Name string
			Age  int
		}{
			Name: "Bob",
			Age:  29,
		}

		// Log Request
		log.Context(ctx).Debug("Testing Log Request Debug")
		log.Context(ctx).Info("Testing Log Request Info")
		log.Context(ctx).Warn("Testing Log Request Warn")
		log.Context(ctx).Error("Testing Log Request Error")

		// Global log
		log.Debug("Testing Global Log Debug")
		log.Info("Testing Global Log Info")
		log.Warn("Testing Global Log Warn")
		log.Error("Testing Global Log Error")

		return c.String(http.StatusOK, "Hello, Log!")
	})

	e.Start("localhost:8080")
}

Documentation ΒΆ

Index ΒΆ

Constants ΒΆ

View Source
const (

	// Logging level from least important to most important
	LevelDebug   = slog.LevelDebug
	LevelInfo    = slog.LevelInfo
	LevelWarning = slog.LevelWarn
	LevelError   = slog.LevelError
	LevelFatal   = slog.Level(12)
	LevelTrace   = slog.Level(16) // Trace service to service communication
	LevelRequest = slog.Level(17) // Request log
)

Variables ΒΆ

View Source
var (
	DefaultConfig = Config{
		LogToTerminal:     true,
		LogToFile:         false,
		Location:          "/log/",
		FileLogName:       "server_log",
		FileFormat:        ".%Y-%b-%d-%H-%M.log",
		MaxAge:            30,
		RotationFile:      24,
		Level:             LevelDebug,
		CustomWriter:      nil,
		HideSensitiveData: false,
	}
)

Functions ΒΆ

func Context ΒΆ

func Context(ctx context.Context) *request

Context is used for get log request model from context

func Debug ΒΆ

func Debug(i ...any)

func Debugf ΒΆ

func Debugf(format string, i ...any)

func Error ΒΆ

func Error(i ...any)

func Errorf ΒΆ

func Errorf(format string, i ...any)

func Fatal ΒΆ

func Fatal(i ...any)

func Fatalf ΒΆ

func Fatalf(msg string, i ...any)

func GetCaller ΒΆ

func GetCaller(level string, skip int) string

GetCaller return trimmed location of the file who call the log function example project_name/usecase/user.go:34

func Info ΒΆ

func Info(i ...any)

func Infof ΒΆ

func Infof(format string, i ...any)

func Init ΒΆ

func Init()

func InitWithConfig ΒΆ

func InitWithConfig(cfg Config)

func NewRequest ΒΆ

func NewRequest() *request

NewRequest will create new log data model for incoming request

func NewTrace ΒΆ

func NewTrace(method, url string, reqHeader, reqBody any, addToExtraData bool) trace

func Warn ΒΆ

func Warn(i ...any)

func Warnf ΒΆ

func Warnf(format string, i ...any)

Types ΒΆ

type Config ΒΆ

type Config struct {
	LogToTerminal     bool       // Set log output to stdout
	LogToFile         bool       // Set log output to file
	Location          string     // Location file log will be save. Default "project_directory/log/".
	FileLogName       string     // File log name. Default "server_log".
	FileFormat        string     // Default "FileLogName.2021-Oct-22-00-00.log"
	MaxAge            int        // Days before deleting log file. Default 30 days.
	RotationFile      int        // Hour before creating new file. Default 24 hour.
	Level             slog.Level // Log output level. Default level DEBUG
	CustomWriter      io.Writer  // Specify custom writer for log output
	HideSensitiveData bool       // Enable hide sensitive data with struct tag `log:"hide"`
}

Directories ΒΆ

Path Synopsis
example
echo command
fiber command
gorm command
extension
middleware

Jump to

Keyboard shortcuts

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