You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
crate/log/logsdk/logjson/option.go

97 lines
1.9 KiB
Go

package logjson
import (
"io"
"time"
)
// Option 配置日志处理对象
type Option interface {
apply(cfg *config)
}
// WithBufferPool 配置缓冲池
func WithBufferPool(pool BytesBufferPool) Option {
return optionFunc(func(cfg *config) {
cfg.bytesBufferPool = pool
cfg.hasPool = true
})
}
// WithOutput 配置输出
func WithOutput(w io.Writer) Option {
return optionFunc(func(cfg *config) {
cfg.output = w
})
}
// WithTimeFormat 配置时间格式
func WithTimeFormat(format string) Option {
return optionFunc(func(cfg *config) {
cfg.timestampFormat = format
})
}
// WithDisableTime 配置仅用时间输出
func WithDisableTime(disable bool) Option {
return optionFunc(func(cfg *config) {
cfg.disableTime = disable
})
}
// WithDisableHTMLEscape 配置禁止 HTML 转义
func WithDisableHTMLEscape(disable bool) Option {
return optionFunc(func(cfg *config) {
cfg.disableHTMLEscape = disable
})
}
// WithPrettyPrint 配置 JSON 多行缩进输出
func WithPrettyPrint(pretty bool) Option {
return optionFunc(func(cfg *config) {
cfg.prettyPrint = pretty
})
}
func newConfig(opts ...Option) *config {
cfg := defaultConfig()
for _, opt := range opts {
opt.apply(cfg)
}
if !cfg.hasPool {
cfg.bytesBufferPool = DefaultBytesBufferPool
}
if cfg.output == nil {
cfg.output = DefaultStderrSyncWriter
}
if cfg.timestampFormat == "" {
cfg.timestampFormat = time.RFC3339Nano
}
return cfg
}
func defaultConfig() *config {
return &config{
hasPool: false,
disableTime: false,
disableHTMLEscape: false,
prettyPrint: false,
}
}
type config struct {
bytesBufferPool BytesBufferPool
output io.Writer
timestampFormat string
hasPool bool
disableTime bool
disableHTMLEscape bool
prettyPrint bool
}
type optionFunc func(cfg *config)
func (fn optionFunc) apply(cfg *config) {
fn(cfg)
}