logs

package module
v0.1.2 Latest Latest
Warning

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

Go to latest
Published: Jun 16, 2025 License: MIT Imports: 19 Imported by: 0

README

Xeno Logs

English Version

A high-performance, feature-rich logging library for Go applications.

Features
  • Structured Logging: Support for key-value pairs and structured data
  • Multiple Log Levels: Trace, Debug, Info, Notice, Warn, Error, Fatal
  • Context Support: Built-in context integration for request tracing and metadata
  • Flexible Output: Support for console, file, and custom writers
  • Performance Optimized:
    • Zero allocation for common operations
    • Object pooling for log instances
    • Efficient buffer management
  • Customizable Format:
    • Configurable file path depth
    • Optional function name display
    • Customizable time format with timezone support
  • Middleware Support: Extensible middleware system for log processing
  • Rate Limiting: Built-in rate limiting for log output
  • Compatibility Mode: Support for traditional logging style
Quick Start
package main

import (
    "github.com/erickxeno/logs"
)

func main() {
    // Create a new logger with default settings
    logger := logs.NewCLogger(
        logs.SetPSM("my-service"),
        logs.SetFileDepth(1),  // Show last directory + filename
    )

    // Basic logging
    logger.Info("Hello, World!")

    // Logging with key-value pairs
    logger.Info("User logged in").KV("user_id", 123).KV("ip", "127.0.0.1")

    // Context-based logging
    ctx := context.Background()
    logger.Info(ctx, "Request processed").KV("request_id", "abc-123")

    // Error logging with stack trace
    if err != nil {
        logger.Error("Operation failed").Err(err)
    }
}
Advanced Usage
Custom Writer
// Create a custom writer
writer := logs.NewConsoleWriter(
    logs.SetColorful(true),
)

// Create logger with custom writer
logger := logs.NewCLogger(
    logs.SetWriter(logs.InfoLevel, writer),
)
Middleware
// Create a middleware that adds request ID to all logs
middleware := func(next logs.Middleware) logs.Middleware {
    return func(l *logs.Log) *logs.Log {
        return l.KV("request_id", uuid.New())
    }
}

logger := logs.NewCLogger(
    logs.SetMiddleware(middleware),
)
Rate Limiting
// Create a rate-limited logger
logger := logs.NewCLogger(
    logs.SetRateLimit(100), // 100 logs per second
)
Configuration Options
  • SetPSM: Set service name
  • SetFileDepth: Control file path display depth
  • SetFullPath: Show full file path
  • SetDisplayFuncName: Show function name in logs
  • SetCallDepth: Adjust stack trace depth
  • SetPadding: Customize log field separator
  • SetConvertErrorToKV: Convert errors to key-value pairs
  • SetConvertObjectToKV: Convert objects to key-value pairs
Performance

The library is optimized for performance with zero allocation for common operations and efficient buffer management.

Performance Comparison with Go Standard Library
Test Environment
goos: darwin
goarch: amd64
pkg: github.com/erickxeno/logs
cpu: Intel(R) Core(TM) i7-9750H CPU @ 2.60GHz
Detailed Benchmark Results
BenchmarkXenoVsStdLog/Xeno_Simple-12            91878649                15.26 ns/op            0 B/op          0 allocs/op
BenchmarkXenoVsStdLog/Std_Simple-12             29200424                37.28 ns/op           16 B/op          1 allocs/op
BenchmarkXenoVsStdLog/Xeno_WithKV-12             5445943               233.4 ns/op            48 B/op          3 allocs/op
BenchmarkXenoVsStdLog/Std_WithKV-12             21164678                53.87 ns/op           16 B/op          1 allocs/op
BenchmarkXenoVsStdLog/Xeno_WithContext-12        5175687               224.1 ns/op            48 B/op          3 allocs/op
BenchmarkXenoVsStdLog/Xeno_WithError-12         81696086                16.23 ns/op            0 B/op          0 allocs/op
BenchmarkXenoVsStdLog/Std_WithError-12          31007655                43.95 ns/op           16 B/op          1 allocs/op
BenchmarkXenoVsStdLog/Xeno_Concurrent-12        21555132                79.50 ns/op           48 B/op          3 allocs/op
BenchmarkXenoVsStdLog/Std_Concurrent-12         56980738                17.87 ns/op           16 B/op          1 allocs/op
Simple Logging
  • Xeno Logs: 15.26 ns/op, 0 B/op, 0 allocs/op
  • Standard Library: 37.28 ns/op, 16 B/op, 1 allocs/op Xeno Logs performs better in simple logging scenarios with no memory allocation.
Logging with Key-Value Pairs
  • Xeno Logs: 233.4 ns/op, 48 B/op, 3 allocs/op
  • Standard Library: 53.87 ns/op, 16 B/op, 1 allocs/op The standard library performs better in key-value logging scenarios with less memory allocation.
Context-based Logging
  • Xeno Logs: 224.1 ns/op, 48 B/op, 3 allocs/op
  • Standard Library: Not tested Xeno Logs provides context support with additional performance overhead.
Error Logging
  • Xeno Logs: 16.23 ns/op, 0 B/op, 0 allocs/op
  • Standard Library: 43.95 ns/op, 16 B/op, 1 allocs/op Xeno Logs performs better in error logging scenarios with no memory allocation.
Concurrent Logging
  • Xeno Logs: 79.50 ns/op, 48 B/op, 3 allocs/op
  • Standard Library: 17.87 ns/op, 16 B/op, 1 allocs/op The standard library performs better in concurrent scenarios with less memory allocation.
Summary
  1. Xeno Logs performs better in simple logging and error logging scenarios with zero memory allocation
  2. The standard library performs better in key-value and concurrent logging scenarios
  3. Xeno Logs requires more memory allocation in complex scenarios (key-value pairs, context)
  4. The standard library maintains consistent memory allocation (16 bytes) across all scenarios
Recommendations
  1. Use Xeno Logs if your primary use case is simple logging and error logging
  2. Consider using the standard library if you heavily use key-value logging or concurrent logging
  3. The standard library might be more suitable if memory allocation is a critical factor
  4. Xeno Logs is the better choice if you need advanced features like context support
License

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


中文版本

高性能、功能丰富的 Go 日志库。

特性
  • 结构化日志: 支持键值对和结构化数据
  • 多级别日志: Trace, Debug, Info, Notice, Warn, Error, Fatal
  • 上下文支持: 内置请求追踪和元数据集成
  • 灵活输出: 支持控制台、文件和自定义写入器
  • 性能优化:
    • 常见操作零内存分配
    • 日志实例对象池
    • 高效缓冲区管理
  • 可定制格式:
    • 可配置文件路径深度
    • 可选函数名显示
    • 可自定义时间格式(支持时区)
  • 中间件支持: 可扩展的日志处理中间件系统
  • 速率限制: 内置日志输出速率限制
  • 兼容模式: 支持传统日志风格
快速开始
package main

import (
    "github.com/erickxeno/logs"
)

func main() {
    // 创建带有默认设置的日志器
    logger := logs.NewCLogger(
        logs.SetPSM("my-service"),
        logs.SetFileDepth(1),  // 显示最后一级目录和文件名
    )

    // 基础日志记录
    logger.Info("Hello, World!")

    // 带键值对的日志记录
    logger.Info("用户登录").KV("user_id", 123).KV("ip", "127.0.0.1")

    // 基于上下文的日志记录
    ctx := context.Background()
    logger.Info(ctx, "请求处理完成").KV("request_id", "abc-123")

    // 带堆栈跟踪的错误日志
    if err != nil {
        logger.Error("操作失败").Err(err)
    }
}
高级用法
自定义写入器
// 创建自定义写入器
writer := logs.NewConsoleWriter(
    logs.SetColorful(true),
)

// 使用自定义写入器创建日志器
logger := logs.NewCLogger(
    logs.SetWriter(logs.InfoLevel, writer),
)
中间件
// 创建添加请求ID的中间件
middleware := func(next logs.Middleware) logs.Middleware {
    return func(l *logs.Log) *logs.Log {
        return l.KV("request_id", uuid.New())
    }
}

logger := logs.NewCLogger(
    logs.SetMiddleware(middleware),
)
速率限制
// 创建带速率限制的日志器
logger := logs.NewCLogger(
    logs.SetRateLimit(100), // 每秒100条日志
)
配置选项
  • SetPSM: 设置服务名称
  • SetFileDepth: 控制文件路径显示深度
  • SetFullPath: 显示完整文件路径
  • SetDisplayFuncName: 在日志中显示函数名
  • SetCallDepth: 调整堆栈跟踪深度
  • SetPadding: 自定义日志字段分隔符
  • SetConvertErrorToKV: 将错误转换为键值对
  • SetConvertObjectToKV: 将对象转换为键值对
性能

该库针对性能进行了优化,常见操作零分配,并具有高效的缓冲区管理。

与 Go 标准库的性能对比
测试环境
goos: darwin
goarch: amd64
pkg: github.com/erickxeno/logs
cpu: Intel(R) Core(TM) i7-9750H CPU @ 2.60GHz
详细性能测试结果
BenchmarkXenoVsStdLog/Xeno_Simple-12            91878649                15.26 ns/op            0 B/op          0 allocs/op
BenchmarkXenoVsStdLog/Std_Simple-12             29200424                37.28 ns/op           16 B/op          1 allocs/op
BenchmarkXenoVsStdLog/Xeno_WithKV-12             5445943               233.4 ns/op            48 B/op          3 allocs/op
BenchmarkXenoVsStdLog/Std_WithKV-12             21164678                53.87 ns/op           16 B/op          1 allocs/op
BenchmarkXenoVsStdLog/Xeno_WithContext-12        5175687               224.1 ns/op            48 B/op          3 allocs/op
BenchmarkXenoVsStdLog/Xeno_WithError-12         81696086                16.23 ns/op            0 B/op          0 allocs/op
BenchmarkXenoVsStdLog/Std_WithError-12          31007655                43.95 ns/op           16 B/op          1 allocs/op
BenchmarkXenoVsStdLog/Xeno_Concurrent-12        21555132                79.50 ns/op           48 B/op          3 allocs/op
BenchmarkXenoVsStdLog/Std_Concurrent-12         56980738                17.87 ns/op           16 B/op          1 allocs/op
简单日志记录
  • Xeno Logs: 15.26 ns/op, 0 B/op, 0 allocs/op
  • 标准库: 37.28 ns/op, 16 B/op, 1 allocs/op Xeno Logs 在简单日志场景下性能更好,且没有内存分配。
带键值对的日志
  • Xeno Logs: 233.4 ns/op, 48 B/op, 3 allocs/op
  • 标准库: 53.87 ns/op, 16 B/op, 1 allocs/op 标准库在带键值对的场景下性能更好,内存分配也更少。
带上下文的日志
  • Xeno Logs: 224.1 ns/op, 48 B/op, 3 allocs/op
  • 标准库: 未测试 Xeno Logs 提供了上下文支持,但需要额外的性能开销。
错误日志
  • Xeno Logs: 16.23 ns/op, 0 B/op, 0 allocs/op
  • 标准库: 43.95 ns/op, 16 B/op, 1 allocs/op Xeno Logs 在错误日志场景下性能更好,且没有内存分配。
并发日志
  • Xeno Logs: 79.50 ns/op, 48 B/op, 3 allocs/op
  • 标准库: 17.87 ns/op, 16 B/op, 1 allocs/op 标准库在并发场景下性能更好,内存分配也更少。
总结
  1. Xeno Logs 在简单日志和错误日志场景下表现更好,且没有内存分配
  2. 标准库在带键值对和并发场景下表现更好
  3. Xeno Logs 在复杂场景(如带键值对、上下文)下需要更多的内存分配
  4. 标准库在所有场景下都保持稳定的内存分配(16字节)
建议
  1. 如果主要使用简单日志和错误日志,推荐使用 Xeno Logs
  2. 如果需要大量使用键值对日志或并发日志,可以考虑使用标准库
  3. 如果内存分配是关键考虑因素,标准库可能更适合
  4. 如果需要上下文支持等高级特性,Xeno Logs 是更好的选择
许可证

本项目采用 MIT 许可证 - 详见 LICENSE 文件。

Documentation

Index

Examples

Constants

View Source
const (
	LogIDCtxKey = contextKey("K_LOGID")

	DynamicLogLevelKey = contextKey("K_DYNAMIC_LOG_LEVEL")
)
View Source
const (
	TimePrecisionSecond      = time.TimePrecisionSecond
	TimePrecisionMillisecond = time.TimePrecisionMillisecond
	TimePrecisionMicrosecond = time.TimePrecisionMicrosecond
)

Variables

View Source
var (
	DefaultLogPath = "log/app" // 默认日志路径:curDir/log/app/psm.log
)

Functions

func AddCallDepth

func AddCallDepth(depth int)

AddCallDepth temporarily increases the call stack depth of the current logger to get the correct caller location. Remember to call ResetCallDepth() after use.

func AppendKVInMsg

func AppendKVInMsg() kvOption

AppendKVInMsg directly append kv to the log body.

func ConvertErrToKV

func ConvertErrToKV() errOption

ConvertErrToKV converts an error to a KV

func ConvertObjToKV

func ConvertObjToKV() objOption

ConvertObjToKV convets an obj to a KV

func CtxAddKVs

func CtxAddKVs(ctx context.Context, kvs ...interface{}) context.Context

CtxAddKVs works like logs.CtxAddKVs in logs 1.0

func CtxDebug

func CtxDebug(ctx context.Context, format string, v ...interface{})

CtxDebug works like logs.CtxDebug.

func CtxDebugKVs

func CtxDebugKVs(ctx context.Context, kvs ...interface{})

CtxDebugKVs provides function like logs.CtxDebugKVs.

func CtxDebugsf

func CtxDebugsf(ctx context.Context, format string, v ...string)

CtxDebugsf works like logs.CtxDebugsf.

func CtxError

func CtxError(ctx context.Context, format string, v ...interface{})

CtxError works like logs.CtxError.

func CtxErrorKVs

func CtxErrorKVs(ctx context.Context, kvs ...interface{})

CtxErrorKVs provides function like logs.CtxErrorKVs.

func CtxErrorsf

func CtxErrorsf(ctx context.Context, format string, v ...string)

CtxErrorsf works like logs.CtxErrorsf.

func CtxFatal

func CtxFatal(ctx context.Context, format string, v ...interface{})

CtxFatal works like logs.CtxFatal.

func CtxFatalKVs

func CtxFatalKVs(ctx context.Context, kvs ...interface{})

CtxFatalKVs provides function like logs.CtxFatalKVs.

func CtxFatalsf

func CtxFatalsf(ctx context.Context, format string, v ...string)

CtxFatalsf works like logs.CtxFatalsf.

func CtxFlushNotice

func CtxFlushNotice(ctx context.Context)

CtxFlushNotice provides function like logs.CtxFlushNotice

func CtxInfo

func CtxInfo(ctx context.Context, format string, v ...interface{})

CtxInfo works like logs.CtxInfo.

func CtxInfoKVs

func CtxInfoKVs(ctx context.Context, kvs ...interface{})

CtxInfoKVs provides function like logs.CtxInfoKVs.

func CtxInfosf

func CtxInfosf(ctx context.Context, format string, v ...string)

CtxErrorsf works like logs.CtxErrorsf.

func CtxNotice

func CtxNotice(ctx context.Context, format string, v ...interface{})

CtxNotice works like logs.CtxNotice.

func CtxNoticeKVs

func CtxNoticeKVs(ctx context.Context, kvs ...interface{})

CtxNoticeKVs provides function like logs.CtxNoticeKVs.

func CtxNoticesf

func CtxNoticesf(ctx context.Context, format string, v ...string)

CtxNoticesf works like logs.CtxNoticesf.

func CtxPushNotice

func CtxPushNotice(ctx context.Context, k, v interface{})

func CtxStackInfo

func CtxStackInfo(ctx context.Context, stackInfo StackInfo) context.Context

CtxStackInfo marks whether to print the stack in the current log.

func CtxTrace

func CtxTrace(ctx context.Context, format string, v ...interface{})

CtxTrace works like logs.CtxTrace.

func CtxTraceKVs

func CtxTraceKVs(ctx context.Context, kvs ...interface{})

CtxTraceKVs provides function like logs.CtxTraceKVs.

func CtxTracesf

func CtxTracesf(ctx context.Context, format string, v ...string)

CtxTracesf works like logs.CtxDebugsf.

func CtxWarn

func CtxWarn(ctx context.Context, format string, v ...interface{})

CtxWarn works like logs.CtxWarn.

func CtxWarnKVs

func CtxWarnKVs(ctx context.Context, kvs ...interface{})

CtxWarnKVs provides function like logs.CtxWarnKVs.

func CtxWarnsf

func CtxWarnsf(ctx context.Context, format string, v ...string)

CtxErrorsf works like logs.CtxErrorsf.

func Debug

func Debug(format string, v ...interface{})

Debug works like logs.Debug.

func Debugf

func Debugf(format string, v ...interface{})

Debugf works like logs.Debugf.

func EnableDynamicLogLevel

func EnableDynamicLogLevel()

EnableDynamicLogLevel enableds dynamic context log level for compatibleLogger.

func Error

func Error(format string, v ...interface{})

Error works like logs.Erorr.

func Errorf

func Errorf(format string, v ...interface{})

Errorf works like logs.Errorf.

func Fatal

func Fatal(format string, v ...interface{})

Fatal works like logs.Fatal.

func Fatalf

func Fatalf(format string, v ...interface{})

Fatalf works like logs.Fatalf.

func Flush

func Flush()

func GetAllKVs

func GetAllKVs(ctx context.Context) []interface{}

func GetAllKVsStr

func GetAllKVsStr(ctx context.Context) string

func GetWriters

func GetWriters() []leveledWriter

GetWriters returns the level writers

func Info

func Info(format string, v ...interface{})

Info works like logs.Info.

func Infof

func Infof(format string, v ...interface{})

Infof works like logs.Infof.

func Init

func Init()

func IsSecMarkEnabled

func IsSecMarkEnabled() bool

func NewLogger

func NewLogger() *logger

func NewNoticeCtx

func NewNoticeCtx(ctx context.Context) context.Context

func Notice

func Notice(format string, v ...interface{})

Notice works like logs.Notice.

func Noticef

func Noticef(format string, v ...interface{})

Noticef works like logs.Noticef.

func PrintStack

func PrintStack(printAllGoroutines bool)

PrintStack prints the stacks in Info level. If printAllGoroutines is true, it prints the stacks of all goroutines. Otherwise, it just prints the current goroutine's stack.

func ResetCallDepth

func ResetCallDepth()

ResetCallDepth resets the call depth for the default logger.

func SecMark

func SecMark(key, val interface{}) string

SecMark adds double brackets to the key-value pairs and return the generated string. This is a function that directly exported to users. So we need to check the type of the parameters

func SetCurrentVersion

func SetCurrentVersion(version string)

SetCurrentVersion sets the current version. Call it in program initialization.

func SetDefaultLogCallDepthOffset

func SetDefaultLogCallDepthOffset(offset int)

SetDefaultLogCallDepthOffset sets the default call stack depth for newly created loggers (without considering internal depth). Unlike AddCallDepth which affects the current logger, this function affects all newly created loggers.

func SetDefaultLogPrefixFileDepth

func SetDefaultLogPrefixFileDepth(depth int)

func SetDefaultLogPrefixWithoutCluster added in v0.1.1

func SetDefaultLogPrefixWithoutCluster(withoutCluster bool)

func SetDefaultLogPrefixWithoutHost added in v0.1.1

func SetDefaultLogPrefixWithoutHost(withoutHost bool)

func SetDefaultLogPrefixWithoutPSM added in v0.1.1

func SetDefaultLogPrefixWithoutPSM(withoutPSM bool)

func SetDefaultLogPrefixWithoutSpanID added in v0.1.1

func SetDefaultLogPrefixWithoutSpanID(withoutSpanID bool)

func SetDefaultLogPrefixWithoutStage added in v0.1.1

func SetDefaultLogPrefixWithoutStage(withoutStage bool)

func SetDefaultLogger

func SetDefaultLogger(ops ...Option)

SetDefaultLogger resets the default logger with specified options, it is not thread-safe and please only call it in program initialization. Libraries should not config the default logger and leaves it to the application user, otherwise loggers would cover each other.

func SetLevel

func SetLevel(newLevel Level)

SetLevel sets the minimal level for defaultLogger and all writers. It is safe to increase the level.

func SetLevelForWriters

func SetLevelForWriters(newLevel Level, logWriters ...writer.LogWriter)

SetLevelForWriters updates the minimal level for the writer of the defaultLogger. It may also update the loggers' level.

func SetLogPrefixTimePrecision added in v0.1.1

func SetLogPrefixTimePrecision(precision TimePrecision)

SetLogPrefixTimePrecision sets the time precision for the log prefix. It affects all loggers, including the default logger.

func SetNewLogIDCtxKey added in v0.1.1

func SetNewLogIDCtxKey(newKey string) contextKey

func SetSecMark

func SetSecMark(isEnabled bool)

SetSecMark updates enableSecMark. Call it in program initialization.

func Stop

func Stop()

func Trace

func Trace(format string, v ...interface{})

Trace works like logs.Trace.

func Tracef

func Tracef(format string, v ...interface{})

Tracef works like logs.Tracef.

func ValueToStr

func ValueToStr(o interface{}) string

func Warn

func Warn(format string, v ...interface{})

Warn works like logs.Warn.

func Warnf

func Warnf(format string, v ...interface{})

Warnf works like logs.Warnf.

func WithCtx

func WithCtx(ctx context.Context) loggerOption

WithCtx attach a context to a specific logger It can also temporarily change the level of the logger

func WithDynamicLoggerLevel

func WithDynamicLoggerLevel(level Level) loggerOption

WithDynamicLoggerLevel temporarily sets the logger level for a log. It can allow user to temporily print low-level logs.

Types

type CLogger

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

CLogger is a common logging handler. It is also the default logger.

var (
	V1 *CLogger
)

func NewCLogger

func NewCLogger(options ...Option) *CLogger

NewCLogger creates a new CLogger with options

func (*CLogger) Close

func (l *CLogger) Close() error

func (*CLogger) CtxFlushNotice

func (l *CLogger) CtxFlushNotice(ctx context.Context)

func (*CLogger) CtxLevel

func (l *CLogger) CtxLevel(ctx context.Context) (Level, bool)

func (*CLogger) Debug

func (l *CLogger) Debug(ops ...loggerOption) *Log

Debug starts a debug level log printing.

func (*CLogger) Error

func (l *CLogger) Error(ops ...loggerOption) *Log

Error starts a error level log printing.

func (*CLogger) Fatal

func (l *CLogger) Fatal(ops ...loggerOption) *Log

Fatal starts a fatal level log printing.

func (*CLogger) Flush

func (l *CLogger) Flush() error

func (*CLogger) GetLevel

func (l *CLogger) GetLevel() Level

GetLevel gets the minimal level specified in logger writers.

func (*CLogger) GetOptions

func (l *CLogger) GetOptions() []Option

func (*CLogger) GetWriter

func (l *CLogger) GetWriter() []leveledWriter

func (*CLogger) Info

func (l *CLogger) Info(ops ...loggerOption) *Log

Info starts a info level log printing.

func (*CLogger) Notice

func (l *CLogger) Notice(ops ...loggerOption) *Log

Notice starts a notice level log printing.

func (*CLogger) SetLevel

func (l *CLogger) SetLevel(newLevel Level)

SetLevel sets the minimal level for the logger. It is safe to increase the level. Please not decrease the level directly. Use SetLevelForWriters instead.

func (*CLogger) SetLevelForWriters

func (l *CLogger) SetLevelForWriters(newLevel Level, logWriters ...writer.LogWriter)

SetLevelForWriters updates the minimal level for the writer. It may also update the loggers' level.

func (*CLogger) Trace

func (l *CLogger) Trace(ops ...loggerOption) *Log

Trace starts a trace level log printing.

func (*CLogger) Warn

func (l *CLogger) Warn(ops ...loggerOption) *Log

Warn starts a warn level log printing.

type CompatLogger

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

CompatLogger CLogger does not support std string format originally, CompatLogger creates a simple fast approach fmt.Sprintf, map %s to Log.Str, %f to Log.Float, %v to json.Marshal and ignore any prefix on verbs. it is not only able to boost the format performance but also keep the compatibility.

func NewCompatLogger

func NewCompatLogger(ops ...Option) *CompatLogger

NewCompatLogger creates a compatible logger CompatLogger, it supports Info, CtxInfo, CtxInfosf, CtxInfoKVs and other level methods.

func NewCompatLoggerFrom

func NewCompatLoggerFrom(logger *CLogger, ops ...CompatibleLoggerOption) *CompatLogger

NewCompatLoggerFrom creates a compatible logger CompatLogger from a CLogger.

func (*CompatLogger) Close

func (l *CompatLogger) Close() error

Close flushes logger and graceful exit.

func (*CompatLogger) CtxDebug

func (l *CompatLogger) CtxDebug(ctx context.Context, format string, v ...interface{})

func (*CompatLogger) CtxDebugKVs

func (l *CompatLogger) CtxDebugKVs(ctx context.Context, kvs ...interface{})

func (*CompatLogger) CtxDebugsf

func (l *CompatLogger) CtxDebugsf(ctx context.Context, format string, v ...string)

func (*CompatLogger) CtxError

func (l *CompatLogger) CtxError(ctx context.Context, format string, v ...interface{})

func (*CompatLogger) CtxErrorKVs

func (l *CompatLogger) CtxErrorKVs(ctx context.Context, kvs ...interface{})

func (*CompatLogger) CtxErrorsf

func (l *CompatLogger) CtxErrorsf(ctx context.Context, format string, v ...string)

func (*CompatLogger) CtxFatal

func (l *CompatLogger) CtxFatal(ctx context.Context, format string, v ...interface{})

func (*CompatLogger) CtxFatalKVs

func (l *CompatLogger) CtxFatalKVs(ctx context.Context, kvs ...interface{})

func (*CompatLogger) CtxFatalsf

func (l *CompatLogger) CtxFatalsf(ctx context.Context, format string, v ...string)

func (*CompatLogger) CtxFlushNotice

func (l *CompatLogger) CtxFlushNotice(ctx context.Context)

func (*CompatLogger) CtxInfo

func (l *CompatLogger) CtxInfo(ctx context.Context, format string, v ...interface{})

func (*CompatLogger) CtxInfoKVs

func (l *CompatLogger) CtxInfoKVs(ctx context.Context, kvs ...interface{})

func (*CompatLogger) CtxInfosf

func (l *CompatLogger) CtxInfosf(ctx context.Context, format string, v ...string)

func (*CompatLogger) CtxNotice

func (l *CompatLogger) CtxNotice(ctx context.Context, format string, v ...interface{})

func (*CompatLogger) CtxNoticeKVs

func (l *CompatLogger) CtxNoticeKVs(ctx context.Context, kvs ...interface{})

func (*CompatLogger) CtxNoticesf

func (l *CompatLogger) CtxNoticesf(ctx context.Context, format string, v ...string)

func (*CompatLogger) CtxTrace

func (l *CompatLogger) CtxTrace(ctx context.Context, format string, v ...interface{})

func (*CompatLogger) CtxTraceKVs

func (l *CompatLogger) CtxTraceKVs(ctx context.Context, kvs ...interface{})

func (*CompatLogger) CtxTracesf

func (l *CompatLogger) CtxTracesf(ctx context.Context, format string, v ...string)

func (*CompatLogger) CtxWarn

func (l *CompatLogger) CtxWarn(ctx context.Context, format string, v ...interface{})

func (*CompatLogger) CtxWarnKVs

func (l *CompatLogger) CtxWarnKVs(ctx context.Context, kvs ...interface{})

func (*CompatLogger) CtxWarnsf

func (l *CompatLogger) CtxWarnsf(ctx context.Context, format string, v ...string)

func (*CompatLogger) Debug

func (l *CompatLogger) Debug(format string, v ...interface{})

func (*CompatLogger) Error

func (l *CompatLogger) Error(format string, v ...interface{})

func (*CompatLogger) Fatal

func (l *CompatLogger) Fatal(format string, v ...interface{})

func (*CompatLogger) Flush

func (l *CompatLogger) Flush()

Flush blocks logger and flush all buffered logs.

func (*CompatLogger) Info

func (l *CompatLogger) Info(format string, v ...interface{})

func (*CompatLogger) Notice

func (l *CompatLogger) Notice(format string, v ...interface{})

func (*CompatLogger) PrintStack

func (l *CompatLogger) PrintStack(printAllGoroutines bool)

PrintStack prints the stacks in Info level. If printAllGoroutines is true, it prints the stacks of all goroutines. Otherwise, it just prints the current goroutine's stack.

func (*CompatLogger) Stop

func (l *CompatLogger) Stop()

Stop graceful exit with no error returned.

func (*CompatLogger) Trace

func (l *CompatLogger) Trace(format string, v ...interface{})

func (*CompatLogger) Warn

func (l *CompatLogger) Warn(format string, v ...interface{})

type CompatibleLoggerOption

type CompatibleLoggerOption func(*CompatLogger)

CompatibleLoggerOption provides some options to config CompatLogger

func WithCallDepthOffset

func WithCallDepthOffset(offset int) CompatibleLoggerOption

WithCallDepthOffset sets the call depth offset for the compatibale logger.

func WithDynamicLevel

func WithDynamicLevel(isEnabled bool) CompatibleLoggerOption

WithDynamicLevel sets whether the dyancmic level is enabled for the compatibale logger.

type ContentSetter

type ContentSetter interface {
	SetBody([]byte)
	SetKVList([]*writer.KeyValue)
}

ContentSetter allows to rewrite the log content.

type KVPosition

type KVPosition int32

KVPosition defines the position of the kv list

const (
	BeforeMsg KVPosition = iota
	AfterMsg
)

type Lazier

type Lazier func() interface{}

func Lazy

func Lazy(f func() interface{}) Lazier

Lazy is a helper function to avoid

Example
l := NewCompatLogger(SetPSM("test.test.test"),
	SetWriter(InfoLevel, w.NewConsoleWriter()),
)
l.Debug("hello %v", Lazy(func() interface{} {
	panic("dead code")
}))

type Level

type Level int32

Level defines log levels

const (
	// TraceLevel defines Trace Level.
	TraceLevel Level = iota
	// DebugLevel defines Debug Level.
	DebugLevel
	// InfoLevel defines Info Level.
	InfoLevel
	// NoticeLevel defines Notice Level.
	NoticeLevel
	// WarnLevel defines Warn Level.
	WarnLevel
	// ErrorLevel defines Error Level.
	ErrorLevel
	// FatalLevel defines Fatal Level.
	FatalLevel
)

func GetLevel

func GetLevel() Level

func (Level) String

func (l Level) String() string

String stringify Level.

type Line

type Line struct {
	sync.Once
	// contains filtered or unexported fields
}

Line creates a cached source code file line information by sync.Once to avoid reflect call of each log printing.

func CustomLine

func CustomLine(value []byte) *Line

func LineWithOnlyFilename

func LineWithOnlyFilename() *Line

If user does not want to define log's Line struct for every log, can use LineWithOnlyFilename to generate a global Line var in its file, and use this in all log.XXX().Line() calls within this file

type Log

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

Log is a log instance of execute each log printing. A Log instance is always bound to a specific Logger, But a Logger can get some log from the log pool.

func (*Log) Bool

func (l *Log) Bool(b bool) *Log

Bool prints a boolean in the log.

func (*Log) CallDepth

func (l *Log) CallDepth(d int) *Log

func (*Log) Emit

func (l *Log) Emit()

Emit emits log print.

func (*Log) EmitEveryN

func (l *Log) EmitEveryN(n int)

EmitEveryN emits the log based on the count of calls. It logs the 1st call, (N+1)st call, (2N+1)st call, etc.

func (*Log) EmplaceKV

func (l *Log) EmplaceKV(key interface{}, value interface{}) *Log

EmplaceKV converts a kv pair into a string (key=value) and append it to the message. It is equivalent to use KV(key, value, AppendKVInMsg())

func (*Log) EmplaceKVs

func (l *Log) EmplaceKVs(kvlist ...interface{}) *Log

EmplaceKVs converts a KV list into strings and append them to the message body.

func (*Log) Error

func (l *Log) Error(err error, ops ...errOption) *Log

Error prints an error in the log.

func (*Log) Float

func (l *Log) Float(fs ...float64) *Log

Float prints some floats in the log.

func (*Log) Int

func (l *Log) Int(is ...int) *Log

Int prints some integers in the log.

func (*Log) Int64

func (l *Log) Int64(is ...int64) *Log

Int64 prints some Int64 in the log.

func (*Log) KV

func (l *Log) KV(key interface{}, value interface{}, ops ...kvOption) *Log

KV creates a KV instance and appends it into the kv list. When the log is emitted, the kv list will be handled depending on cases. If security mark is enabled, it converts the kv to a string (pattern: {{key=value}}) and appends it to the message body.

func (*Log) KVs

func (l *Log) KVs(kvlist ...interface{}) *Log

KVs handles a KV list.

func (*Log) Limit

func (l *Log) Limit(limit int) *Log

Limit controls the rate of a log based on its file location. limit is the max frequency in a second. The rate limit is not accurate. You may find the actual number of logs slightly exceeds limit * time.

func (*Log) Line

func (l *Log) Line(line *Line) *Log

Line uses a cached Line instance to avoid reflection overhead, if there is no Line provided, Log would try to call runtime.Caller each printing.

func (*Log) Location

func (l *Log) Location(pos string) *Log

Location directly sets the file location of the log. The users must make sure the file location has the right format. Otherwise, StreamLog may fail to parse the log. It must be "{Filename}.go:{LineNumber}"

func (*Log) Obj

func (l *Log) Obj(o interface{}, ops ...objOption) *Log

Obj prints a object uses json.Marshal by default and prefer fmt.Stringer if the structure implements it, remind that fmt.Stringer would cause extra malloc here.

func (*Log) Stack

func (l *Log) Stack(printAllGoroutines bool) *Log

Stack will add stack info when composing the log instance. If printAllGoroutines is true, it prints the stacks of all goroutines. Otherwise, it just prints the current goroutine's stack.

func (*Log) Str

func (l *Log) Str(contents ...string) *Log

Str prints some strings in the log.

func (*Log) StrKV

func (l *Log) StrKV(key, value string) *Log

StrKV creates a KV instance for two strings and appends it into the kv list. When the log is emitted, the kv list will be handled depending on cases. If security mark is enabled, it converts the kv to a string (pattern: {{key=value}}) and appends it to the message body.

func (*Log) StrKVs

func (l *Log) StrKVs(kvlist ...string) *Log

StrKVs handles a string list.

func (*Log) With

func (l *Log) With(ctx context.Context) *Log

With uses to pass a context to each printing, it is able to log log id and span id.

type Middleware

type Middleware func(log RewritableLog) RewritableLog

Middleware function is a hook to get and update logs before writing to each writers.

type NoticeKVs

type NoticeKVs struct {
	sync.Mutex
	// contains filtered or unexported fields
}

func GetNotice

func GetNotice(ctx context.Context) *NoticeKVs

func (*NoticeKVs) KVs

func (l *NoticeKVs) KVs() []interface{}

func (*NoticeKVs) PushNotice

func (l *NoticeKVs) PushNotice(k, v interface{})

type Option

type Option func(*CLogger)

Option provides some options to config CLogger.

func AppendWriter

func AppendWriter(level Level, ws ...writer.LogWriter) Option

AppendWriter sets CLogger outputs to which writers. It will not remove existing writers.

func ConfigSecMark

func ConfigSecMark(isEnabled bool) Option

ConfigSecMark sets if the logger needs to add double brackets to key-value pairs example:

isEnabled=false:  count=100
isEnabled=true:   {{count=100}}

If you also specify the current version of your app, otherwise it will use the image tag by default

func SetCallDepth

func SetCallDepth(c int) Option

SetCallDepth sets CLogger call depth while logging file location.

func SetConvertErrorToKV

func SetConvertErrorToKV(isEnabled bool) Option

SetConvertErrorToKV sets if it converts an error to a KV pair.

func SetConvertObjectToKV

func SetConvertObjectToKV(isEnabled bool) Option

SetConvertObjectToKV sets if it converts an object to a KV pair.

func SetDeduplicateCtxKVs

func SetDeduplicateCtxKVs(isEnabled bool) Option

SetDeduplicateCtxKVs sets if it converts the kvlist in the ctx to a string. if isEnabled is true, it keeps the kvlist and will deduplicate the KVs in StreamLog 2.0 Else it allows duplicate kvs and convert the kvs to a string and append it to the message body.

func SetDisplayEnvInfo

func SetDisplayEnvInfo(displayEnvInfo bool) Option

SetDisplayEnvInfo sets if the logger will add a KV pair: ("_env", {env}) to all logs.

func SetDisplayFuncName

func SetDisplayFuncName(withPackage bool) Option

SetDisplayFuncName sets if the logger will print the function name. It will attach a kv: func={function name} to the logs. It withPackage is true, function name will look like {pkg name}.{func name}, e.g., func=github.com/facebookgo/ensure.TestFunc

func SetEnableDynamicLevel

func SetEnableDynamicLevel(isEnabled bool) Option

SetEnableDynamicLevel sets whether to enable dynamic log level in compatLogger. It only works for compatible logger.

func SetEnableKVList deprecated

func SetEnableKVList(isEnabled bool) Option

Deprecated: KVList is always enabled.

func SetFatalOSExit

func SetFatalOSExit(isEnabled bool) Option

SetFatalOSExit sets whether log sdk calls os.Exit after printing fatal log.

func SetFullPath

func SetFullPath(fullpath bool) Option

SetFullPath sets print the full path of log file location.

func SetKVPosition

func SetKVPosition(position KVPosition) Option

SetKVPosition sets the positions of the kv list in console and file writers' output.

func SetLazyHandleCtx

func SetLazyHandleCtx() Option

SetLazyHandleCtx sets if the logger lazily handles the ctx, e.g., extrating kvs from ctx.

func SetLogPrefixFileDepth

func SetLogPrefixFileDepth(depth int) Option

SetLogPrefixFileDepth sets how many directory levels to include in file path. - When logPrefixFileDepth is 0, returns only the filename - When logPrefixFileDepth is 1, returns the last directory name and filename - When logPrefixFileDepth is n, returns the last n directory names and filename

func SetLogPrefixWithoutCluster added in v0.1.1

func SetLogPrefixWithoutCluster(withoutCluster bool) Option

SetLogPrefixWithoutCluster sets if the log prefix should include the cluster.

func SetLogPrefixWithoutHost added in v0.1.1

func SetLogPrefixWithoutHost(withoutHost bool) Option

SetLogPrefixWithoutHost sets if the log prefix should include the host.

func SetLogPrefixWithoutPSM added in v0.1.1

func SetLogPrefixWithoutPSM(withoutPSM bool) Option

SetLogPrefixWithoutPSM sets if the log prefix should include the PSM.

func SetLogPrefixWithoutSpanID added in v0.1.1

func SetLogPrefixWithoutSpanID(withoutSpanID bool) Option

SetLogPrefixWithoutSpanID sets if the log prefix should include the span ID.

func SetLogPrefixWithoutStage added in v0.1.1

func SetLogPrefixWithoutStage(withoutStage bool) Option

SetLogPrefixWithoutStage sets if the log prefix should include the stage.

func SetMiddleware

func SetMiddleware(m ...Middleware) Option

SetMiddleware adds the middleware to the logger

func SetPSM

func SetPSM(psm string) Option

SetPSM sets psm to CLogger, logger would read env.PSM as default.

func SetPadding

func SetPadding(padding string) Option

SetPadding sets CLogger padding between each element.

func SetTracing

func SetTracing() Option

SetTracing sets a compatible tracing writer to trace level logs, it is only used in compatible cases,

func SetWriter

func SetWriter(level Level, ws ...writer.LogWriter) Option

SetWriter sets CLogger outputs to which writers.

func SetZoneInfo

func SetZoneInfo(include bool) Option

SetZoneInfo sets if the time string include zone info example:

include=false:  2021-07-15 15:19:14,161
include=true:   2021-07-15 15:19:14,161 +0800

func UpdateMiddleware

func UpdateMiddleware(m ...Middleware) Option

UpdateMiddleware sets middleware to the logger

type RegionType

type RegionType int32
const (
	REGION_NORMAL RegionType = iota
	REGION_1
	REGION_2
)

func DetermineRegion

func DetermineRegion() RegionType

type RewritableLog

type RewritableLog interface {
	writer.StructuredLog
	ContentSetter
}

RewritableLog provides some methods to get and set logs.

type StackInfo

type StackInfo byte
const (
	NoPrint StackInfo = iota
	CurrGoroutine
	AllGoroutines
)

type TimePrecision added in v0.1.1

type TimePrecision = time.TimePrecision

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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