Skip to content

juparave/mylogger

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

6 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

mylogger

mylogger is a simple logging utility for Go projects. Using Go's slog but with separated outputs for stdout and stderr.

Installation

You can install mylogger using go get:

go get github.com/juparave/mylogger

Usage

package main

import (
	"github.com/juparave/mylogger"
)

func main() {
	// Create a new logger
	logger := mylogger.NewLogger()

	// Log some messages
	logger.Info("This is an informational message")
    logger.Debug("This is a debug message")
	logger.Warn("This is a warning message")
	logger.Error("This is an error message")
}

Using a Custom slog.Logger

You can create a MyLogger from an existing slog.Logger using FromSlog. This is useful when you want to use a custom handler or configuration:

package main

import (
	"log/slog"
	"os"

	"github.com/juparave/mylogger"
	"github.com/lmittmann/tint"
)

func main() {
	// Create a custom slog logger with tint handler
	logger := slog.New(tint.NewHandler(os.Stderr, &tint.Options{
		Level:      slog.LevelDebug,
		TimeFormat: "2006-01-02 15:04:05",
		AddSource:  true,
	}))

	// Set it as the default slog logger (optional)
	slog.SetDefault(logger)

	// Create MyLogger from the slog logger
	log := mylogger.FromSlog(logger, slog.LevelDebug)

	// Use the logger
	log.Info("Application started", "version", "1.0.0")
	log.Debug("Debug information")
	log.Warn("Warning message")
	log.Error("Error occurred")
}

Testing with Custom Buffers

You can also create a logger with custom output buffers for testing purposes using NewLoggerBuffers:

package main

import (
	"bytes"
	"github.com/juparave/mylogger"
)

func main() {
	// Create buffers for capturing log output
	var stdOut, errOut bytes.Buffer

	// Create a logger with custom output buffers
	logger := mylogger.NewLoggerBuffers(&stdOut, &errOut)

	// Log some messages
	logger.Info("This is an informational message")
    logger.Debug("This is a debug message")
	logger.Warn("This is a warning message")
	logger.Error("This is an error message")

	// Check the output captured in buffers
	println("Standard output:", stdOut.String())
	println("Error output:", errOut.String())
}

Setting the Log Level

You can set the log level by using the LOG_LEVEL environment variable. The available log levels are:

  • DEBUG: Logs all messages.
  • INFO: Logs informational, warning, and error messages.
  • WARN: Logs warning and error messages.
  • ERROR: Logs only error messages.

To set the log level, use the following command before running your application:

export LOG_LEVEL=DEBUG

License

This project is licensed under the MIT License - see the LICENSE file for details.

About

Custom go logger wrapper

Resources

License

Stars

Watchers

Forks

Packages

 
 
 

Contributors

Languages