logging

package
v0.2.1 Latest Latest
Warning

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

Go to latest
Published: Sep 26, 2026 License: AGPL-3.0 Imports: 11 Imported by: 0

Documentation

Overview

Package logging 统一构造 slog 日志器。

Index

Constants

View Source
const FilePrefix = "lumo-"

FilePrefix 是日志文件名的固定前缀,读取端据此识别日志文件。

View Source
const FileSuffix = ".log"

FileSuffix 是日志文件的扩展名。

Variables

This section is empty.

Functions

func ListFiles added in v0.1.2

func ListFiles(dir string) ([]string, error)

ListFiles 返回目录下的日志文件名,按日期与序号倒序(最新的在前)。

func New

func New(w io.Writer, opts Options) *slog.Logger

New 按 opts 构造日志器,写入 w。 无法识别的取值回退到 info / text,而不是报错——日志本身不该成为启动失败的原因。

func NewTee added in v0.1.2

func NewTee(console, file io.Writer, opts Options) *slog.Logger

NewTee 构造同时写控制台与文件的日志器。

两路各自成句:控制台跟随 opts.Format(站长习惯的 text 或 json), 文件一律 JSON —— 后台日志页要把每行解析成结构化字段,text 格式做不到这件事。

为什么保留控制台那一路:Docker 部署靠 docker logs、systemd 靠 journald, 两者都读 stdout。只写文件会让这两种部署方式的用户失去他们习惯的排障入口。

func ParseFileName added in v0.1.2

func ParseFileName(name string) (day string, seq int, ok bool)

ParseFileName 从文件名解析日期与序号,不是日志文件时 ok 为 false。

供读取端复用:哪些文件算日志、怎么排序,只有一个答案。

func ParseLevel

func ParseLevel(level string) slog.Level

ParseLevel 把级别字符串转成 slog.Level,无法识别时回退 info。

func SafeFileName added in v0.1.2

func SafeFileName(name string) (string, bool)

SafeFileName 校验调用方给的文件名确实是本目录下的日志文件。

下载与读取接口都要用它:文件名来自请求,必须挡住 ../ 与任意路径。

Types

type Options

type Options struct {
	// Level 取值 debug / info / warn / error,大小写不敏感。
	Level string
	// Format 取值 text / json,大小写不敏感。
	Format string
}

Options 是日志器构造参数。

type RotateOptions added in v0.1.2

type RotateOptions struct {
	// Dir 是日志目录。
	Dir string
	// RetainDays 是保留天数,按文件名里的日期判断;小于 1 时用 defaultRetainDays。
	RetainDays int
	// MaxSizeMB 是单文件大小上限,超过则在同一天内滚到下一个序号;
	// 小于 1 时用 defaultMaxSizeMB。
	MaxSizeMB int
}

RotateOptions 是滚动写入器的参数。

type RotatingFile added in v0.1.2

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

RotatingFile 是按天切割、按大小滚动的日志写入器。

自己实现而不是引第三方轮转库:需要的只是「按天切 + 超限换一个 + 删过期」这三件事, 而日志文件名的形态同时是读取端的契约(见 internal/logs),由本包定义最稳妥。

并发安全:slog 的 handler 会被多个请求并发调用,Write 必须串行化。

func NewRotatingFile added in v0.1.2

func NewRotatingFile(opts RotateOptions) (*RotatingFile, error)

NewRotatingFile 构造写入器并打开当天的文件。

func (*RotatingFile) Close added in v0.1.2

func (w *RotatingFile) Close() error

Close 关闭当前文件。

func (*RotatingFile) Write added in v0.1.2

func (w *RotatingFile) Write(p []byte) (int, error)

Write 实现 io.Writer。

写失败不向上报错到调用方以外的地方:日志写不进磁盘时,进程仍应继续服务, stdout 那一路也还在(见 New 的多路输出)。

Jump to

Keyboard shortcuts

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