go_logger

package module
v0.0.0-...-9055c93 Latest Latest
Warning

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

Go to latest
Published: Jun 25, 2023 License: MIT Imports: 17 Imported by: 0

README

go-logger

A simple but powerful golang log Toolkit

Sourcegraph godoc license

中文文档

Feature

  • Support at the same time to console, file, URL
  • console output fonts can be colored with
  • File output supports three types of segmentation based on the size of the file, the number of file lines, and the date.
  • file output support is saved to different files at the log level.
  • Two ways of writing to support asynchronous and synchronous
  • Support json format output
  • The code is designed to be extensible, and you can design your own adapter as needed

Install

go get github.com/Digman/go-logger
go get ./...

Requirement

go 1.8

Support outputs

  • console // write console
  • file // write file
  • api // http request url
  • ...

Quick Used

  • sync
import (
    "github.com/Digman/go-logger"
)
func main()  {
    logger := go_logger.NewLogger()

    logger.Info("this is a info log!")
    logger.Errorf("this is a error %s log!", "format")
}
  • async
import (
    "github.com/Digman/go-logger"
)
func main()  {
    logger := go_logger.NewLogger()
    logger.SetAsync()

    logger.Info("this is a info log!")
    logger.Errorf("this is a error %s log!", "format")

    // Flush must be called before the end of the process
    logger.Flush()
}
  • Multiple output
import (
    "github.com/Digman/go-logger"
)
func main()  {
    logger := go_logger.NewLogger()

    logger.Detach("console")

    // console adapter config
    consoleConfig := &go_logger.ConsoleConfig{
        Color: true, // Does the text display the color
        JsonFormat: true, // Whether or not formatted into a JSON string
        Format: "", // JsonFormat is false, logger message output to console format string
    }
    // add output to the console
    logger.Attach("console", go_logger.LOGGER_LEVEL_DEBUG, consoleConfig)

    // file adapter config
    fileConfig := &go_logger.FileConfig {
        Filename : "./test.log", // The file name of the logger output, does not exist automatically
        // If you want to separate separate logs into files, configure LevelFileName parameters.
        LevelFileName : map[int]string {
            logger.LoggerLevel("error"): "./error.log",    // The error level log is written to the error.log file.
            logger.LoggerLevel("info"): "./info.log",      // The info level log is written to the info.log file.
            logger.LoggerLevel("debug"): "./debug.log",    // The debug level log is written to the debug.log file.
        },
        MaxSize : 1024 * 1024,  // File maximum (KB), default 0 is not limited
        MaxLine : 100000, // The maximum number of lines in the file, the default 0 is not limited
        DateSlice : "d",  // Cut the document by date, support "Y" (year), "m" (month), "d" (day), "H" (hour), default "no".
        JsonFormat: true, // Whether the file data is written to JSON formatting
        Format: "", // JsonFormat is false, logger message written to file format string
    }
    // add output to the file
    logger.Attach("file", go_logger.LOGGER_LEVEL_DEBUG, fileConfig)


    logger.Info("this is a info log!")
    logger.Errorf("this is a error %s log!", "format")
}

Console text with color effect

image

Customize Format output

Logger Message
Field Alias Type Comment Example
Timestamp timestamp int64 unix timestamp 1521791201
TimestampFormat timestamp_format string timestamp format 2018-3-23 15:46:41
Millisecond millisecond int64 millisecond 1524472688352
MillisecondFormat millisecond_format string millisecond_format 2018-3-23 15:46:41.970
Level level int logger level 1
LevelString level_string string logger level string Error
Body body string logger message body this is a info log
File file string Call the file of the logger main.go
Line line int The number of specific lines to call logger 64
Function function string The function name to call logger main.main

If you want to customize the format of the log output ?

config format:

consoleConfig := &go_logger.ConsoleConfig{
    Format: "%millisecond_format% [%level_string%] %body%",
}
fileConfig := &go_logger.FileConfig{
    Format: "%millisecond_format% [%level_string%] %body%",
}

output:

2018-03-23 14:55:07.003 [Critical] this is a critical log!

You can customize the format, Only needs to be satisfied Format: "%Logger Message Alias%"

More adapter examples

Benchmark

system: Linux Mint 18.2 Sonya
cpu(s): 4
model name: Intel(R) Core(TM) i5-3210M CPU @ 2.50GHz
memery: 4G

BenchmarkLoggerConsoleText          500000             11375 ns/op             672 B/op         15 allocs/op
BenchmarkLoggerConsoleText-2        500000             11345 ns/op             672 B/op         15 allocs/op
BenchmarkLoggerConsoleText-4        500000              9897 ns/op             672 B/op         15 allocs/op
BenchmarkLoggerConsoleAsyncText     500000              9323 ns/op             672 B/op         15 allocs/op
BenchmarkLoggerConsoleAsyncText-2   500000              9087 ns/op             672 B/op         15 allocs/op
BenchmarkLoggerConsoleAsyncText-4   500000             10685 ns/op             672 B/op         15 allocs/op
BenchmarkLoggerConsoleJson          200000             30918 ns/op            2048 B/op         10 allocs/op
BenchmarkLoggerConsoleJson-2        200000             33153 ns/op            2048 B/op         10 allocs/op
BenchmarkLoggerConsoleJson-4        200000             30918 ns/op            2048 B/op         10 allocs/op
BenchmarkLoggerFileText             300000             14083 ns/op             912 B/op         21 allocs/op
BenchmarkLoggerFileText-2           200000             21159 ns/op             912 B/op         21 allocs/op
BenchmarkLoggerFileText-4           200000             23776 ns/op             912 B/op         21 allocs/op
BenchmarkLoggerFileAsyncText        300000             13956 ns/op             912 B/op         21 allocs/op
BenchmarkLoggerFileAsyncText-2      300000             16124 ns/op             912 B/op         21 allocs/op
BenchmarkLoggerFileAsyncText-4      300000             18641 ns/op             912 B/op         21 allocs/op
BenchmarkLoggerFileJson             200000             15472 ns/op            1968 B/op         15 allocs/op
BenchmarkLoggerFileJson-2           200000             22523 ns/op            1968 B/op         15 allocs/op
BenchmarkLoggerFileJson-4           200000             25596 ns/op            1968 B/op         15 allocs/op

Reference

beego/logs : github.com/astaxie/beego/logs

Feedback

Welcome to submit comments and code, contact information phachon@163.com

License

MIT

Thanks

Create By phachon@163.com

Documentation

Index

Constants

View Source
const (
	FILE_SLICE_DATE_NULL  = ""
	FILE_SLICE_DATE_YEAR  = "y"
	FILE_SLICE_DATE_MONTH = "m"
	FILE_SLICE_DATE_DAY   = "d"
	FILE_SLICE_DATE_HOUR  = "h"
)
View Source
const (
	LOGGER_LEVEL_EMERGENCY = iota
	LOGGER_LEVEL_ALERT
	LOGGER_LEVEL_CRITICAL
	LOGGER_LEVEL_ERROR
	LOGGER_LEVEL_WARNING
	LOGGER_LEVEL_NOTICE
	LOGGER_LEVEL_INFO
	LOGGER_LEVEL_DEBUG
)
View Source
const API_ADAPTER_NAME = "api"
View Source
const CONSOLE_ADAPTER_NAME = "console"
View Source
const (
	FILE_ACCESS_LEVEL = 1000
)
View Source
const FILE_ADAPTER_NAME = "file"

Variables

View Source
var Version = "v1.2"

Functions

func Register

func Register(adapterName string, newLog adapterLoggerFunc)

Register logger adapter

Types

type AdapterApi

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

adapter api

func (*AdapterApi) Flush

func (adapterApi *AdapterApi) Flush()

func (*AdapterApi) Init

func (adapterApi *AdapterApi) Init(apiConfig Config) error

func (*AdapterApi) Name

func (adapterApi *AdapterApi) Name() string

func (*AdapterApi) Write

func (adapterApi *AdapterApi) Write(loggerMsg *loggerMessage) error

type AdapterConsole

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

adapter console

func (*AdapterConsole) Flush

func (adapterConsole *AdapterConsole) Flush()

func (*AdapterConsole) Init

func (adapterConsole *AdapterConsole) Init(consoleConfig Config) error

func (*AdapterConsole) Name

func (adapterConsole *AdapterConsole) Name() string

func (*AdapterConsole) Write

func (adapterConsole *AdapterConsole) Write(loggerMsg *loggerMessage) error

type AdapterFile

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

adapter file

func (*AdapterFile) Flush

func (adapterFile *AdapterFile) Flush()

Flush

func (*AdapterFile) Init

func (adapterFile *AdapterFile) Init(fileConfig Config) error

init

func (*AdapterFile) Name

func (adapterFile *AdapterFile) Name() string

Name

func (*AdapterFile) Write

func (adapterFile *AdapterFile) Write(loggerMsg *loggerMessage) error

Write

type ApiConfig

type ApiConfig struct {

	// request url adddress
	Url string

	// request method
	// GET, POST
	Method string

	// request headers
	Headers map[string]string

	// is verify response code
	IsVerify bool

	// verify response http code
	VerifyCode int
}

api config

func (*ApiConfig) Name

func (ac *ApiConfig) Name() string

type Config

type Config interface {
	Name() string
}

logger config interface

type ConsoleConfig

type ConsoleConfig struct {
	// console text is show color
	Color bool

	// is json format
	JsonFormat bool

	// jsonFormat is false, please input format string
	// if format is empty, default format "%millisecond_format% [%level_string%] %body%"
	//
	//  Timestamp "%timestamp%"
	//	TimestampFormat "%timestamp_format%"
	//	Millisecond "%millisecond%"
	//	MillisecondFormat "%millisecond_format%"
	//	Level int "%level%"
	//	LevelString "%level_string%"
	//	Body string "%body%"
	//	File string "%file%"
	//	Line int "%line%"
	//	Function "%function%"
	//
	// example: format = "%millisecond_format% [%level_string%] %body%"
	Format string
}

console config

func (*ConsoleConfig) Name

func (cc *ConsoleConfig) Name() string

type ConsoleWriter

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

console writer

type FileConfig

type FileConfig struct {

	// log filename
	Filename string

	// level log filename
	LevelFileName map[int]string

	// max file size
	MaxSize int64

	// max file line
	MaxLine int64

	// file slice by date
	// "y" Log files are cut through year
	// "m" Log files are cut through mouth
	// "d" Log files are cut through day
	// "h" Log files are cut through hour
	DateSlice string

	// is json format
	JsonFormat bool

	// jsonFormat is false, please input format string
	// if format is empty, default format "%millisecond_format% [%level_string%] %body%"
	//
	//  Timestamp "%timestamp%"
	//	TimestampFormat "%timestamp_format%"
	//	Millisecond "%millisecond%"
	//	MillisecondFormat "%millisecond_format%"
	//	Level int "%level%"
	//	LevelString "%level_string%"
	//	Body string "%body%"
	//	File string "%file%"
	//	Line int "%line%"
	//	Function "%function%"
	//
	// example: format = "%millisecond_format% [%level_string%] %body%"
	Format string
}

file config

func (*FileConfig) Name

func (fc *FileConfig) Name() string

type FileWriter

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

file writer

func NewFileWrite

func NewFileWrite(fn string) *FileWriter

type Logger

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

func NewLogger

func NewLogger() *Logger

new logger return logger

func (*Logger) Alert

func (logger *Logger) Alert(msg string)

log alert level

func (*Logger) Alertf

func (logger *Logger) Alertf(format string, a ...interface{})

log alert format

func (*Logger) Attach

func (logger *Logger) Attach(adapterName string, level int, config Config) error

start attach a logger adapter param : adapterName console | file | database | ... return : error

func (*Logger) Critical

func (logger *Logger) Critical(msg string)

log critical level

func (*Logger) Criticalf

func (logger *Logger) Criticalf(format string, a ...interface{})

log critical format

func (*Logger) Debug

func (logger *Logger) Debug(msg string)

log debug level

func (*Logger) Debugf

func (logger *Logger) Debugf(format string, a ...interface{})

log debug format

func (*Logger) Detach

func (logger *Logger) Detach(adapterName string) error

start attach a logger adapter param : adapterName console | file | database | ... return : error

func (*Logger) Emergency

func (logger *Logger) Emergency(msg string)

log emergency level

func (*Logger) Emergencyf

func (logger *Logger) Emergencyf(format string, a ...interface{})

log emergency format

func (*Logger) Error

func (logger *Logger) Error(msg string)

log error level

func (*Logger) Errorf

func (logger *Logger) Errorf(format string, a ...interface{})

log error format

func (*Logger) Flush

func (logger *Logger) Flush()

if SetAsync() or logger.synchronous is false, must call Flush() to flush msgChan data

func (*Logger) Info

func (logger *Logger) Info(msg string)

log info level

func (*Logger) Infof

func (logger *Logger) Infof(format string, a ...interface{})

log info format

func (*Logger) LoggerLevel

func (logger *Logger) LoggerLevel(levelStr string) int

func (*Logger) Notice

func (logger *Logger) Notice(msg string)

log notice level

func (*Logger) Noticef

func (logger *Logger) Noticef(format string, a ...interface{})

log notice format

func (*Logger) Printf

func (logger *Logger) Printf(format string, a ...interface{})

alias of Infof

func (*Logger) SetAsync

func (logger *Logger) SetAsync(data ...int)

set logger synchronous false params : sync bool

func (*Logger) Warning

func (logger *Logger) Warning(msg string)

log warning level

func (*Logger) Warningf

func (logger *Logger) Warningf(format string, a ...interface{})

log warning format

func (*Logger) Writer

func (logger *Logger) Writer(level int, msg string) error

write log message params : level int, msg string return : error

type LoggerAbstract

type LoggerAbstract interface {
	Name() string
	Init(config Config) error
	Write(loggerMsg *loggerMessage) error
	Flush()
}

func NewAdapterApi

func NewAdapterApi() LoggerAbstract

func NewAdapterConsole

func NewAdapterConsole() LoggerAbstract

func NewAdapterFile

func NewAdapterFile() LoggerAbstract

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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