mylog

package
v0.2.3 Latest Latest
Warning

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

Go to latest
Published: May 3, 2026 License: Apache-2.0 Imports: 34 Imported by: 32

README

mylog - Go 日志库

一个简洁、高效的 Go 日志库,提供格式化输出和多种日志级别支持。

功能特性

  • 多种日志级别:Info、Warning、Success、Trace、Error
  • 特殊格式支持:Hex、HexDump、Json、Struct
  • 自动时间戳和调用位置
  • 彩色终端输出
  • 自动格式化值
  • Key 自动设置:自动使用调用者函数名作为 key,用户只需传 value
  • 简化错误堆栈:自动过滤 mylog 内部函数,只显示用户代码调用栈

使用方法

基本用法
package main

import "github.com/ddkwork/golibrary/std/mylog"

func main() {
    mylog.Info("processing data...")
    mylog.Warning("disk space low")
    mylog.Success("task completed")
}
Key 自动设置

重要:Key 自动使用调用者函数名,用户只需传 value,不需要也不应该手动设置 key!

func ProcessData() {
    mylog.Info("processing data...")
    // 输出: ProcessData │ processing data...
}

func LoadConfig() {
    mylog.Warning("config file not found")
    // 输出: LoadConfig │ config file not found
}
特殊格式
// 十六进制输出
mylog.Hex(uint32(0xDEADBEEF))
mylog.HexDump([]byte{0x01, 0x02, 0x03, 0x04})

// JSON 输出
mylog.Json(`{"key": "value"}`)

// 结构体输出
mylog.Struct(myStruct)

错误处理

Check 函数

Check[T any](result T) 检查结果,支持三种类型:

类型 行为
bool 如果为 false 则 panic
string 如果不是成功消息则 panic
error 如果不是 EOF 且不是成功消息则 panic

注意:Check 失败会 panic,需要配合 Call 使用来捕获错误!

// ❌ 错误用法:Check 失败会 panic 导致程序崩溃
func BadExample() {
    err := someOperation()
    mylog.Check(err)  // 如果 err != nil,程序会 panic 崩溃
    mylog.Info("继续执行")  // 不会执行到这里
}

// ✅ 正确用法:用 Call 包裹,错误时打印堆栈但程序继续
func GoodExample() {
    mylog.Call(func() {
        err := someOperation()
        mylog.Check(err)  // 如果 err != nil,打印错误堆栈后继续
        mylog.Info("继续执行")  // 会执行到这里
    })
}
Check2 函数

Check2[T any](ret T, err error) T 同时检查 error 和返回值是否为 nil:

func ReadFile(path string) {
    mylog.Call(func() {
        data := mylog.Check2(os.ReadFile(path))  // 检查 error 和 data 是否为 nil
        mylog.Info("文件大小", len(data))
    })
}
CheckNil 函数

CheckNil(ptr any) 检查指针是否为 nil:

mylog.Call(func() {
    ptr := getPointer()
    mylog.CheckNil(ptr)  // 如果 ptr 为 nil 则 panic
})
Call 函数

Call(f func()) 捕获内部的 panic 并打印错误堆栈,程序不会崩溃:

func SafeOperation() {
    mylog.Call(func() {
        // 这里的任何 panic 都会被捕获并打印堆栈
        f := mylog.Check2(os.Open("config.json"))
        defer f.Close()
        
        data := mylog.Check2(io.ReadAll(f))
        mylog.Info("读取到", len(data), "字节")
    })
    // 即使上面出错,这里也会继续执行
    mylog.Info("操作完成")
}

API 参考

基础日志函数
func Info(msg ...any)
func Warning(msg ...any)
func Success(msg ...any)
func Trace(msg ...any)
特殊格式函数
func Hex[V types.Unsigned](v V) string
func HexDump[V []byte | *bytes.Buffer](buf V)
func Json(msg ...any)
func Struct(object any)
错误处理函数
func Check[T any](result T) (isEof bool)      // 检查 bool/string/error,失败 panic
func Check2[T any](ret T, err error) T        // 检查 error 和返回值
func CheckNil(ptr any)                         // 检查指针是否为 nil
func Call(f func())                            // 捕获 panic 并打印堆栈

限制规则

Value 限制
规则 说明
不能为空 value 必须提供有效内容
不能包含格式化语法 禁止使用 %s%d 等格式化符号,mylog 会自动格式化
Key 说明
说明
Key 完全自动设置,使用调用者函数名,用户不需要也不应该手动设置

错误示例

// ❌ 错误:value 为空
mylog.Info()

// ❌ 错误:value 包含格式化语法
mylog.Info("value is %s", "test")

// ❌ 错误:Check 失败会 panic,不用 Call 包裹会导致程序崩溃
func BadCheck() {
    mylog.Check(errors.New("some error"))  // panic!
}

正确示例

// ✅ 正确:只需传 value,key 自动使用函数名
func ProcessData() {
    mylog.Info("processing data...")
}

// ✅ 正确:多个 value 自动格式化
mylog.Info("user_id", 12345, "ip", "192.168.1.1")

// ✅ 正确:中文放在 value 中
mylog.Info("用户登录成功")

// ✅ 正确:用 Call 包裹 Check,错误时打印堆栈但程序继续
func SafeCheck() {
    mylog.Call(func() {
        mylog.Check(errors.New("some error"))  // 打印错误堆栈,程序继续
    })
    mylog.Info("这里会继续执行")
}

日志输出格式

普通日志
2026-03-22 02:47:26    Info -> ProcessData │ processing data... main.go:10

格式说明:

  • 时间戳
  • 日志级别(右对齐)
  • 调用者函数名(自动设置)
  • value 内容
  • 调用位置(文件名:行号)
错误堆栈
2026-03-22 02:47:26   Error ->           │ open 2332: The system cannot find the file specified.
                                         │ mylog_test.bug check_test.go:82
                                         │ mylog_test.m5 check_test.go:77
                                         │ mylog_test.TestCheckM5 check_test.go:16

错误堆栈自动过滤 mylog 内部函数(Check、Check2 等),只显示用户代码调用栈。

Panic 情况

以下情况会导致 panic:

  1. log value cannot be empty - value 为空
  2. log value cannot contain format syntax - value 包含格式化语法
  3. Check 失败 - 传入 bool(false)、非成功 string、或非 nil error

重要:使用 mylog.Call(func(){}) 包裹可以捕获 panic,打印错误堆栈但程序不会崩溃!

许可证

MIT License

Documentation

Index

Constants

View Source
const (
	FgHiBlack attribute = iota + 90
	FgHiRed
	FgHiGreen
	FgHiYellow
	FgHiBlue
	FgHiMagenta
	FgHiCyan
	FgHiWhite
)
View Source
const TimeLayout = "2006-01-02 15:04:05"

Variables

View Source
var (
	GithubWorkspace = os.Getenv("GITHUB_WORKSPACE")
	IsAction        = GithubWorkspace != ""
)
View Source
var (
	RegexpIp     = regexp.MustCompile(`((25[0-5]|2[0-4]\d|((1\d{2})|([1-9]?\d)))\.){3}(25[0-5]|2[0-4]\d|((1\d{2})|([1-9]?\d)))`)
	RegexpIpPort = regexp.MustCompile(`((25[0-5]|2[0-4]\d|((1\d{2})|([1-9]?\d)))\.){3}(25[0-5]|2[0-4]\d|((1\d{2})|([1-9]?\d))):([0-9]+)`)
)
View Source
var RegexpCenter = `(.+?)`
View Source
var RuntimePrefixesToFilter = []string{
	"runtime.",
	"testing.",
	"github.com/ddkwork/golibrary/std/mylog.callWithHandler",
	"github.com/ddkwork/golibrary/std/mylog.Call",
	"github.com/ddkwork/golibrary/std/mylog.Check",
	"github.com/ddkwork/golibrary/std/mylog.Check2",
	"github.com/ddkwork/golibrary/std/mylog.Check3",
	"github.com/ddkwork/golibrary/std/mylog.Check4",
	"github.com/ddkwork/golibrary/std/mylog.Check5",
	"github.com/ddkwork/golibrary/std/mylog.Check6",
	"github.com/ddkwork/golibrary/std/mylog.CheckNil",
	"github.com/ddkwork/golibrary/std/mylog.CheckIgnore",
	"github.com/ddkwork/golibrary/std/mylog.Check2Ignore",
	"github.com/ddkwork/golibrary/std/mylog.Check2Bool",
	"github.com/ddkwork/golibrary/std/mylog.Check3Bool",
	"github.com/ddkwork/golibrary/std/mylog.Check4Bool",
	"github.com/ddkwork/golibrary/std/mylog.Check5Bool",
}

Functions

func AlignString

func AlignString(s string, length int) (ss string)

func BaseName

func BaseName(path string) string

func Call

func Call(f func())

func ChdirToGithubWorkspace

func ChdirToGithubWorkspace()

func Check

func Check[T any](result T) (isEof bool)

func Check2

func Check2[T any](ret T, err error) T

func Check2Bool

func Check2Bool[T any](ret T, ok bool) T

func Check2ForJsonNumberNodeType

func Check2ForJsonNumberNodeType[T any](ret T, err error) bool

func Check2Ignore

func Check2Ignore[T any](ret T, err error) T

func Check2IgnoreBool

func Check2IgnoreBool[T any](ret T, err error) (T, bool)

func Check3

func Check3[T1 any, T2 any](ret1 T1, ret2 T2, err error) (T1, T2)

func Check3Bool

func Check3Bool[T1 any, T2 any](ret1 T1, ret2 T2, ok bool) (T1, T2)

func Check4

func Check4[T1 any, T2 any, T3 any](ret1 T1, ret2 T2, ret3 T3, err error) (T1, T2, T3)

func Check4Bool

func Check4Bool[T1 any, T2 any, T3 any](ret1 T1, ret2 T2, ret3 T3, ok bool) (T1, T2, T3)

func Check5

func Check5[T1 any, T2 any, T3 any, T4 any](ret1 T1, ret2 T2, ret3 T3, ret4 T4, err error) (T1, T2, T3, T4)

func Check5Bool

func Check5Bool[T1 any, T2 any, T3 any, T4 any](ret1 T1, ret2 T2, ret3 T3, ret4 T4, ok bool) (T1, T2, T3, T4)

func Check6

func Check6[T1 any, T2 any, T3 any, T4 any, T5 any](ret1 T1, ret2 T2, ret3 T3, ret4 T4, ret5 T5, err error) (T1, T2, T3, T4, T5)

func Check6Bool

func Check6Bool[T1 any, T2 any, T3 any, T4 any, T5 any](ret1 T1, ret2 T2, ret3 T3, ret4 T4, ret5 T5, ok bool) (T1, T2, T3, T4, T5)

func Check7

func Check7[T1 any, T2 any, T3 any, T4 any, T5 any, T6 any](ret1 T1, ret2 T2, ret3 T3, ret4 T4, ret5 T5, ret6 T6, err error) (T1, T2, T3, T4, T5, T6)

func Check7Bool

func Check7Bool[T1 any, T2 any, T3 any, T4 any, T5 any, T6 any](ret1 T1, ret2 T2, ret3 T3, ret4 T4, ret5 T5, ret6 T6, ok bool) (T1, T2, T3, T4, T5, T6)

func CheckIgnore

func CheckIgnore(err any)

func CheckNil

func CheckNil(ptr any)

func Copy

func Copy(src, dst string)

Copy src to dst. src may be a directory, file, or symlink.

func CopyDir

func CopyDir(src, dst string)

func CopyFile

func CopyFile(path, dstPath string)

func CopyWithMask

func CopyWithMask(src, dst string, mask fs.FileMode)

CopyWithMask src to dst. src may be a directory, file, or symlink.

func CreatDirectory

func CreatDirectory(dir string) bool

func CurrentDirName

func CurrentDirName(path string) (currentDirName string)

func DirDepth

func DirDepth(dirPath string) (depth int)

func DumpRequest

func DumpRequest(req *http.Request, body bool) string

func DumpResponse

func DumpResponse(resp *http.Response, body bool) string

func FileExists

func FileExists(path string) bool

FileExists returns true if the path points to a regular file.

func FileLineCountIsMoreThan

func FileLineCountIsMoreThan(path string, n int) bool

func FormatTime

func FormatTime(t time.Time) string

func GenA2Z

func GenA2Z() iter.Seq[string]

func GenMask

func GenMask()

func GetDaysDiff

func GetDaysDiff(dstTime string) string

func GetPackageName

func GetPackageName() (pkgName string)

func GetTimeNowString

func GetTimeNowString() string

func GetTimeStamp

func GetTimeStamp() string

func GetTimeStamp13Bits

func GetTimeStamp13Bits() int64

func GetUserConfigDirs

func GetUserConfigDirs() (UserConfigDirs map[string]string)

func GetWindowsLogicalDrives

func GetWindowsLogicalDrives() iter.Seq[string]

func GitProxy

func GitProxy(isSetProxy bool)

func Hex

func Hex[V types.Unsigned](v V) string

func HexDump

func HexDump[V []byte | *bytes.Buffer](buf V)

func HomeDir

func HomeDir() string

func Info

func Info(msg ...any)

func IntegerToIP

func IntegerToIP(ip int64) string

func IsAndroid

func IsAndroid() bool

func IsDarwin

func IsDarwin() bool

func IsDir

func IsDir(path string) bool

IsDir returns true if the specified path exists and is a directory.

func IsDirEx

func IsDirEx(path string) (ok bool)

func IsDirRoot

func IsDirRoot(path string) bool

func IsFilePath

func IsFilePath(path string) bool

func IsFilePathEx

func IsFilePathEx(path string) (ok bool)

func IsFreebsd

func IsFreebsd() bool

func IsIos

func IsIos() bool

func IsJs

func IsJs() bool

func IsLinux

func IsLinux() bool

func IsTermux

func IsTermux() bool

func IsWindows

func IsWindows() bool

func IsZero

func IsZero(v reflect.Value) bool

func JoinHomeDir

func JoinHomeDir(path string) (join string)

func JoinHomeFile

func JoinHomeFile(path string) (join string)

func Json

func Json(msg ...any)

func JsonIndent

func JsonIndent(b []byte) string

func Lines

func Lines(s string) iter.Seq2[int, string]

Lines returns an iterator over the newline-terminated lines in the string s. The lines yielded by the iterator include their terminating newlines. If s is empty, the iterator yields no lines at all. If s does not end in a newline, the final yielded line will not end in a newline. It returns a single-use iterator with both line number and line content.

func LinesBytes

func LinesBytes(s []byte) iter.Seq2[int, []byte]

LinesBytes returns an iterator over the newline-terminated lines in the byte slice s. The lines yielded by the iterator include their terminating newlines. If s is empty, the iterator yields no lines at all. If s does not end in a newline, the final yielded line will not end in a newline. It returns a single-use iterator.

func MarshalJSON

func MarshalJSON(v any) []byte

func MarshalJson

func MarshalJson(msg any)

func MarshalJsonToFile

func MarshalJsonToFile(v any, name string)

func New

func New() *log

func RandomAnySlice

func RandomAnySlice[T any](slice []T) T

func ReadFileToChunks

func ReadFileToChunks(path string, n int) iter.Seq[[]byte]

func ReadFileToLines

func ReadFileToLines(path string) iter.Seq[string]

func ReflectVisibleFields

func ReflectVisibleFields(object any) iter.Seq2[int, reflect.StructField]

func RegexpWebBodyBlocks

func RegexpWebBodyBlocks(tagName string) string

func Request

func Request(Request *http.Request, body bool)

func Response

func Response(Response *http.Response, body bool)

func RunDir

func RunDir() string

func SetCallBack

func SetCallBack(callBack func(row string))

func SetDebug

func SetDebug(debug bool)

func Struct

func Struct(object any)

func Success

func Success(msg ...any)

func Todo

func Todo(body any)

func Trace

func Trace(msg ...any)

func TrimExtension

func TrimExtension(path string) string

func Warning

func Warning(msg ...any)

func WriteAppend

func WriteAppend[T Type](name string, data T)

func WriteBinaryFile

func WriteBinaryFile[T Type](name string, data T)

func WriteGoFile

func WriteGoFile[T Type](name string, data T)

func WriteTruncate

func WriteTruncate[T Type](name string, data T)

Types

type Buffer

type Buffer struct {
	*bytes.Buffer
	// contains filtered or unexported fields
}

全排列 矩阵置换 拓扑排序 N叉树 treeGrid

func NewBuffer

func NewBuffer[T Type](data T) *Buffer

func NewHexDump

func NewHexDump(hexdumpStr HexDumpString) (data *Buffer)

func NewHexString

func NewHexString(s HexString) *Buffer

func ReaderGzip

func ReaderGzip[T Type](data T) *Buffer

func SwapAdjacent

func SwapAdjacent[T Type](data T) *Buffer

func (*Buffer) Append

func (b *Buffer) Append(others ...*Buffer) *Buffer

func (*Buffer) AppendByteSlice

func (b *Buffer) AppendByteSlice(bytesSlice ...[]byte) []byte

func (*Buffer) BigNumXorWithAlign

func (b *Buffer) BigNumXorWithAlign(arg1, arg2 []byte, align int) []byte

func (*Buffer) Contains

func (b *Buffer) Contains(substr string) bool

func (*Buffer) CutWithIndex

func (b *Buffer) CutWithIndex(x, y int) []byte

func (*Buffer) Empty

func (b *Buffer) Empty() bool

func (*Buffer) HexString

func (b *Buffer) HexString() HexString

func (*Buffer) HexStringUpper

func (b *Buffer) HexStringUpper() HexString

func (*Buffer) Indent

func (b *Buffer) Indent(deep int)

func (*Buffer) InsertByte

func (b *Buffer) InsertByte(index int, ch byte)

func (*Buffer) InsertBytes

func (b *Buffer) InsertBytes(index int, insert []byte)

func (*Buffer) InsertString

func (b *Buffer) InsertString(index int, s string) *Buffer

func (*Buffer) Join

func (b *Buffer) Join(sep string, size int) string

func (*Buffer) NewLine

func (b *Buffer) NewLine() *Buffer

func (*Buffer) ObjectBegin

func (b *Buffer) ObjectBegin()

func (*Buffer) ObjectEnd

func (b *Buffer) ObjectEnd()

func (*Buffer) Peek

func (b *Buffer) Peek(n int) []byte

func (*Buffer) Quote

func (b *Buffer) Quote()

func (*Buffer) QuoteWith

func (b *Buffer) QuoteWith(s string) *Buffer

func (*Buffer) ReWriteSelf

func (b *Buffer) ReWriteSelf()

func (*Buffer) ReWriteSelfGo

func (b *Buffer) ReWriteSelfGo()

func (*Buffer) ReadBinary

func (b *Buffer) ReadBinary(order binary.ByteOrder) (data any)

func (*Buffer) ReadN

func (b *Buffer) ReadN(n int) []byte

func (*Buffer) ReaderGzip

func (b *Buffer) ReaderGzip() *Buffer

func (*Buffer) Replace

func (b *Buffer) Replace(old, new string, n int) *Buffer

func (*Buffer) ReplaceAll

func (b *Buffer) ReplaceAll(old, new string) *Buffer

func (*Buffer) Reverse

func (b *Buffer) Reverse() *Buffer

func (*Buffer) SliceBegin

func (b *Buffer) SliceBegin()

func (*Buffer) SliceEnd

func (b *Buffer) SliceEnd()

func (*Buffer) ToLines

func (b *Buffer) ToLines() (lines iter.Seq[string])

func (*Buffer) TrimPrefix

func (b *Buffer) TrimPrefix(prefix string) *Buffer

func (*Buffer) TrimSpace

func (b *Buffer) TrimSpace() *Buffer

func (*Buffer) TrimSuffix

func (b *Buffer) TrimSuffix(suffix string) *Buffer

func (*Buffer) WriteBinary

func (b *Buffer) WriteBinary(order binary.ByteOrder, data any)

func (*Buffer) WriteBytesLn

func (b *Buffer) WriteBytesLn(buf []byte) *Buffer

func (*Buffer) WritePackageName

func (b *Buffer) WritePackageName()

func (*Buffer) WriteStringLn

func (b *Buffer) WriteStringLn(s string) *Buffer

type HexDumpString

type HexDumpString string

type HexString

type HexString string

type Pool

type Pool[T any] struct {
	// contains filtered or unexported fields
}

func NewPool

func NewPool[T any](fn func() T) *Pool[T]

func (*Pool[T]) Get

func (p *Pool[T]) Get() T

func (*Pool[T]) Put

func (p *Pool[T]) Put(v T)

type Type

type Type interface {
	string | HexString | HexDumpString | ~[]byte | cmp.Ordered | ~*bytes.Buffer | *big.Int | *Buffer
}

全排列 矩阵置换 拓扑排序 N叉树 treeGrid

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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