{"id":13413325,"url":"https://github.com/gookit/slog","last_synced_at":"2025-04-07T09:15:23.028Z","repository":{"id":37481212,"uuid":"277423652","full_name":"gookit/slog","owner":"gookit","description":"📑 Lightweight, configurable, extensible logging library written in Go. Support multi level, multi outputs and built-in multi file logger, buffers, clean, rotate-file handling.一个易于使用的，轻量级、可配置、可扩展的日志库。支持多个级别，输出到多文件；内置文件日志处理、自动切割、清理、压缩等增强功能","archived":false,"fork":false,"pushed_at":"2024-09-14T11:20:48.000Z","size":1540,"stargazers_count":386,"open_issues_count":8,"forks_count":25,"subscribers_count":6,"default_branch":"master","last_synced_at":"2024-09-15T21:02:56.108Z","etag":null,"topics":["console-logger","file-logging","formatter","go-logger","log","log-cleaner","log-processor","log-rotation","logger","logging","logging-library","monolog","rotate-file","slog"],"latest_commit_sha":null,"homepage":"https://pkg.go.dev/github.com/gookit/slog","language":"Go","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/gookit.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2020-07-06T02:26:45.000Z","updated_at":"2024-09-15T10:30:57.000Z","dependencies_parsed_at":"2023-02-02T19:02:50.337Z","dependency_job_id":"d6c5c795-4352-49ac-88bc-90ca572a84b6","html_url":"https://github.com/gookit/slog","commit_stats":null,"previous_names":[],"tags_count":31,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/gookit%2Fslog","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/gookit%2Fslog/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/gookit%2Fslog/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/gookit%2Fslog/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/gookit","download_url":"https://codeload.github.com/gookit/slog/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":247622988,"owners_count":20968575,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["console-logger","file-logging","formatter","go-logger","log","log-cleaner","log-processor","log-rotation","logger","logging","logging-library","monolog","rotate-file","slog"],"created_at":"2024-07-30T20:01:37.775Z","updated_at":"2025-04-07T09:15:23.001Z","avatar_url":"https://github.com/gookit.png","language":"Go","readme":"# slog\n\n![GitHub go.mod Go version](https://img.shields.io/github/go-mod/go-version/gookit/slog?style=flat-square)\n[![GoDoc](https://godoc.org/github.com/gookit/slog?status.svg)](https://pkg.go.dev/github.com/gookit/slog)\n[![Go Report Card](https://goreportcard.com/badge/github.com/gookit/slog)](https://goreportcard.com/report/github.com/gookit/slog)\n[![Unit-Tests](https://github.com/gookit/slog/workflows/Unit-Tests/badge.svg)](https://github.com/gookit/slog/actions)\n[![GitHub tag (latest SemVer)](https://img.shields.io/github/tag/gookit/slog)](https://github.com/gookit/slog)\n[![Coverage Status](https://coveralls.io/repos/github/gookit/slog/badge.svg?branch=master)](https://coveralls.io/github/gookit/slog?branch=master)\n\n📑 Lightweight, extensible, configurable logging library written in Golang.\n\n**Output in console:**\n\n![console-log-all-level](_example/images/console-log-all-level.png)\n\n## Features\n\n- Simple, directly available without configuration\n- Support common log level processing.\n  - eg: `trace` `debug` `info` `notice` `warn` `error` `fatal` `panic`\n- Support any extension of `Handler` `Formatter` as needed\n- Supports adding multiple `Handler` log processing at the same time, outputting logs to different places\n- Support to custom log message `Formatter`\n  - Built-in `json` `text` two log record formatting `Formatter`\n- Support to custom build log messages `Handler`\n  - The built-in `handler.Config` `handler.Builder` can easily and quickly build the desired log handler\n- Has built-in common log write handler program\n  - `console` output logs to the console, supports color output\n  - `writer` output logs to the specified `io.Writer`\n  - `file` output log to the specified file, optionally enable `buffer` to buffer writes\n  - `simple` output log to the specified file, write directly to the file without buffering\n  - `rotate_file` outputs logs to the specified file, and supports splitting files by time and size, and `buffer` buffered writing is enabled by default\n  - See [./handler](./handler) folder for more built-in implementations\n- Benchmark performance test please see [Benchmarks](#benchmarks)\n\n### Output logs to file\n\n- Support enabling `buffer` for log writing\n- Support splitting log files by `time` and `size`\n- Support configuration to compress log files via `gzip`\n- Support clean old log files by `BackupNum` `BackupTime`\n\n### `rotatefile` subpackage\n\n- The `rotatefile` subpackage is a stand-alone tool library with file splitting, cleaning, and compressing backups\n- `rotatefile.Writer` can also be directly wrapped and used in other logging libraries. For example: `log`, `glog`, `zap`, etc.\n- `rotatefile.FilesClear` is an independent file cleaning backup tool, which can be used in other places (such as other program log cleaning such as PHP)\n- For more usage, please see [rotatefile](rotatefile/README.md)\n\n## [中文说明](README.zh-CN.md)\n\n中文说明请阅读 [README.zh-CN](README.zh-CN.md)\n\n## GoDoc\n\n- [Godoc for github](https://pkg.go.dev/github.com/gookit/slog?tab=doc)\n\n## Install\n\n```bash\ngo get github.com/gookit/slog\n```\n\n## Quick Start\n\n`slog` is very simple to use and can be used without any configuration\n\n```go\npackage main\n\nimport (\n\t\"github.com/gookit/slog\"\n)\n\nfunc main() {\n\tslog.Info(\"info log message\")\n\tslog.Warn(\"warning log message\")\n\tslog.Infof(\"info log %s\", \"message\")\n\tslog.Debugf(\"debug %s\", \"message\")\n}\n```\n\n**Output:**\n\n```text\n[2020/07/16 12:19:33] [application] [INFO] [main.go:7] info log message  \n[2020/07/16 12:19:33] [application] [WARNING] [main.go:8] warning log message  \n[2020/07/16 12:19:33] [application] [INFO] [main.go:9] info log message  \n[2020/07/16 12:19:33] [application] [DEBUG] [main.go:10] debug message  \n```\n\n### Console Color\n\nYou can enable color on output logs to console. _This is default_\n\n```go\npackage main\n\nimport (\n\t\"github.com/gookit/slog\"\n)\n\nfunc main() {\n\tslog.Configure(func(logger *slog.SugaredLogger) {\n\t\tf := logger.Formatter.(*slog.TextFormatter)\n\t\tf.EnableColor = true\n\t})\n\n\tslog.Trace(\"this is a simple log message\")\n\tslog.Debug(\"this is a simple log message\")\n\tslog.Info(\"this is a simple log message\")\n\tslog.Notice(\"this is a simple log message\")\n\tslog.Warn(\"this is a simple log message\")\n\tslog.Error(\"this is a simple log message\")\n\tslog.Fatal(\"this is a simple log message\")\n}\n```\n\n**Output:**\n\n![](_example/images/console-color-log.png)\n\n### Change log output style\n\nAbove is the `Formatter` setting that changed the default logger.\n\n\u003e You can also create your own logger and append `ConsoleHandler` to support printing logs to the console:\n\n```go\nh := handler.NewConsoleHandler(slog.AllLevels)\nl := slog.NewWithHandlers(h)\n\nl.Trace(\"this is a simple log message\")\nl.Debug(\"this is a simple log message\")\n```\n\nChange the default logger log output style:\n\n```go\nh.Formatter().(*slog.TextFormatter).SetTemplate(slog.NamedTemplate)\n```\n\n**Output:**\n\n![](_example/images/console-color-log1.png)\n\n\u003e Note: `slog.TextFormatter` uses a template string to format the output log, so the new field output needs to adjust the template at the same time.\n\n### Use JSON Format\n\n`slog` also has a built-in `Formatter` for JSON format. If not specified, the default is to use `TextFormatter` to format log records.\n\n```go\npackage main\n\nimport (\n\t\"github.com/gookit/slog\"\n)\n\nfunc main() {\n\t// use JSON formatter\n\tslog.SetFormatter(slog.NewJSONFormatter())\n\n\tslog.Info(\"info log message\")\n\tslog.Warn(\"warning log message\")\n\tslog.WithData(slog.M{\n\t\t\"key0\": 134,\n\t\t\"key1\": \"abc\",\n\t}).Infof(\"info log %s\", \"message\")\n\n\tr := slog.WithFields(slog.M{\n\t\t\"category\": \"service\",\n\t\t\"IP\": \"127.0.0.1\",\n\t})\n\tr.Infof(\"info %s\", \"message\")\n\tr.Debugf(\"debug %s\", \"message\")\n}\n```\n\n**Output:**\n\n```text\n{\"channel\":\"application\",\"data\":{},\"datetime\":\"2020/07/16 13:23:33\",\"extra\":{},\"level\":\"INFO\",\"message\":\"info log message\"}\n{\"channel\":\"application\",\"data\":{},\"datetime\":\"2020/07/16 13:23:33\",\"extra\":{},\"level\":\"WARNING\",\"message\":\"warning log message\"}\n{\"channel\":\"application\",\"data\":{\"key0\":134,\"key1\":\"abc\"},\"datetime\":\"2020/07/16 13:23:33\",\"extra\":{},\"level\":\"INFO\",\"message\":\"info log message\"}\n{\"IP\":\"127.0.0.1\",\"category\":\"service\",\"channel\":\"application\",\"datetime\":\"2020/07/16 13:23:33\",\"extra\":{},\"level\":\"INFO\",\"message\":\"info message\"}\n{\"IP\":\"127.0.0.1\",\"category\":\"service\",\"channel\":\"application\",\"datetime\":\"2020/07/16 13:23:33\",\"extra\":{},\"level\":\"DEBUG\",\"message\":\"debug message\"}\n```\n\n## Introduction\n\n- `Logger` - log dispatcher. One logger can register multiple `Handler`, `Processor`\n- `Record` - log records, each log is a `Record` instance.\n- `Processor` - enables extended processing of log records. It is called before the log `Record` is processed by the `Handler`.\n  - You can use it to perform additional operations on `Record`, such as: adding fields, adding extended information, etc.\n- `Handler` - log handler, each log will be processed by `Handler.Handle()`.\n  - Here you can send logs to console, file, remote server, etc.\n- `Formatter` - logging data formatting process.\n  - Usually set in `Handler`, it can be used to format log records, convert records into text, JSON, etc., `Handler` then writes the formatted data to the specified place.\n  - `Formatter` is not required. You can do without it and handle logging directly in `Handler.Handle()`.\n\n**Simple structure of log scheduler**：\n\n```text\n          Processors\nLogger --{\n          Handlers --|- Handler0 With Formatter0\n                     |- Handler1 With Formatter1\n                     |- Handler2 (can also without Formatter)\n                     |- ... more\n```\n\n\u003e Note: Be sure to remember to add `Handler`, `Processor` to the logger instance and log records will be processed by `Handler`.\n\n### Processor\n\n`Processor` interface:\n\n```go\n// Processor interface definition\ntype Processor interface {\n\t// Process record\n\tProcess(record *Record)\n}\n\n// ProcessorFunc definition\ntype ProcessorFunc func(record *Record)\n\n// Process record\nfunc (fn ProcessorFunc) Process(record *Record) {\n\tfn(record)\n}\n```\n\n\u003e You can use it to perform additional operations on the Record before the log `Record` reaches the `Handler` for processing, such as: adding fields, adding extended information, etc.\n\nAdd processor to logger:\n\n```go\nslog.AddProcessor(slog.AddHostname())\n\n// or\nl := slog.New()\nl.AddProcessor(slog.AddHostname())\n```\n\nThe built-in processor `slog.AddHostname` is used here as an example, which can add a new field `hostname` on each log record.\n\n```go\nslog.AddProcessor(slog.AddHostname())\nslog.Info(\"message\")\n```\n\nOutput, including new fields `\"hostname\":\"InhereMac\"`：\n\n```json\n{\"channel\":\"application\",\"level\":\"INFO\",\"datetime\":\"2020/07/17 12:01:35\",\"hostname\":\"InhereMac\",\"data\":{},\"extra\":{},\"message\":\"message\"}\n```\n\n### Handler\n\n`Handler` interface:\n\n\u003e You can customize any `Handler` you want, just implement the `slog.Handler` interface.\n\n```go\n// Handler interface definition\ntype Handler interface {\n\tio.Closer\n\tFlush() error\n\t// IsHandling Checks whether the given record will be handled by this handler.\n\tIsHandling(level Level) bool\n\t// Handle a log record.\n\t// all records may be passed to this method, and the handler should discard\n\t// those that it does not want to handle.\n\tHandle(*Record) error\n}\n```\n\n### Formatter\n\n`Formatter` interface:\n\n```go\n// Formatter interface\ntype Formatter interface {\n\tFormat(record *Record) ([]byte, error)\n}\n```\n\nFunction wrapper type：\n\n```go\n// FormatterFunc wrapper definition\ntype FormatterFunc func(r *Record) ([]byte, error)\n\n// Format a log record\nfunc (fn FormatterFunc) Format(r *Record) ([]byte, error) {\n\treturn fn(r)\n}\n```\n\n**JSON formatter**\n\n```go\ntype JSONFormatter struct {\n\t// Fields exported log fields.\n\tFields []string\n\t// Aliases for output fields. you can change export field name.\n\t// item: `\"field\" : \"output name\"`\n\t// eg: {\"message\": \"msg\"} export field will display \"msg\"\n\tAliases StringMap\n\t// PrettyPrint will indent all json logs\n\tPrettyPrint bool\n\t// TimeFormat the time format layout. default is time.RFC3339\n\tTimeFormat string\n}\n```\n\n**Text formatter**\n\nDefault templates:\n\n```go\nconst DefaultTemplate = \"[{{datetime}}] [{{channel}}] [{{level}}] [{{caller}}] {{message}} {{data}} {{extra}}\\n\"\nconst NamedTemplate = \"{{datetime}} channel={{channel}} level={{level}} [file={{caller}}] message={{message}} data={{data}}\\n\"\n```\n\nChange template:\n\n```go\nmyTemplate := \"[{{datetime}}] [{{level}}] {{message}}\"\n\nf := slog.NewTextFormatter()\nf.SetTemplate(myTemplate)\n```\n\n## Custom logger\n\nCustom `Processor` and `Formatter` are relatively simple, just implement a corresponding method.\n\n### Create new logger\n\n`slog.Info, slog.Warn` and other methods use the default logger and output logs to the console by default.\n\nYou can create a brand-new instance of `slog.Logger`:\n\n**Method 1**：\n\n```go\nl := slog.New()\n// add handlers ...\nh1 := handler.NewConsoleHandler(slog.AllLevels)\nl.AddHandlers(h1)\n```\n\n**Method 2**：\n\n```go\nl := slog.NewWithName(\"myLogger\")\n// add handlers ...\nh1 := handler.NewConsoleHandler(slog.AllLevels)\nl.AddHandlers(h1)\n```\n\n**Method 3**：\n\n```go\npackage main\n\nimport (\n\t\"github.com/gookit/slog\"\n\t\"github.com/gookit/slog/handler\"\n)\n\nfunc main() {\n\tl := slog.NewWithHandlers(handler.NewConsoleHandler(slog.AllLevels))\n\tl.Info(\"message\")\n}\n```\n\n### Create custom Handler\n\nYou only need to implement the `slog.Handler` interface to create a custom `Handler`.\n\nYou can quickly assemble your own Handler through the built-in `handler.LevelsWithFormatter` `handler.LevelWithFormatter` and other fragments of slog.\n\nExamples:\n\n\u003e Use `handler.LevelsWithFormatter`, only need to implement `Close, Flush, Handle` methods\n\n```go\ntype MyHandler struct {\n\thandler.LevelsWithFormatter\n    Output io.Writer\n}\n\nfunc (h *MyHandler) Handle(r *slog.Record) error {\n\t// you can write log message to file or send to remote.\n}\n\nfunc (h *MyHandler) Flush() error {}\nfunc (h *MyHandler) Close() error {}\n```\n\nAdd `Handler` to the logger to use:\n\n```go\n// add to default logger\nslog.AddHander(\u0026MyHandler{})\n\n// or, add to custom logger:\nl := slog.New()\nl.AddHander(\u0026MyHandler{})\n```\n\n## Use the built-in handlers\n\n[./handler](handler) package has built-in common log handlers, which can basically meet most scenarios.\n\n```go\n// Output logs to console, allow render color.\nfunc NewConsoleHandler(levels []slog.Level) *ConsoleHandler\n// Send logs to email\nfunc NewEmailHandler(from EmailOption, toAddresses []string) *EmailHandler\n// Send logs to syslog\nfunc NewSysLogHandler(priority syslog.Priority, tag string) (*SysLogHandler, error)\n// A simple handler implementation that outputs logs to a given io.Writer\nfunc NewSimpleHandler(out io.Writer, level slog.Level) *SimpleHandler\n```\n\n**Output log to file**:\n\n```go\n// Output log to the specified file, without buffering by default\nfunc NewFileHandler(logfile string, fns ...ConfigFn) (h *SyncCloseHandler, err error)\n// Output logs to the specified file in JSON format, without buffering by default\nfunc JSONFileHandler(logfile string, fns ...ConfigFn) (*SyncCloseHandler, error)\n// Buffered output log to specified file\nfunc NewBuffFileHandler(logfile string, buffSize int, fns ...ConfigFn) (*SyncCloseHandler, error)\n```\n\n\u003e TIP: `NewFileHandler` `JSONFileHandler` can also enable write buffering by passing in fns `handler.WithBuffSize(buffSize)`\n\n**Output log to file and rotate automatically**:\n\n```go\n// Automatic rotating according to file size\nfunc NewSizeRotateFile(logfile string, maxSize int, fns ...ConfigFn) (*SyncCloseHandler, error)\n// Automatic rotating according to time\nfunc NewTimeRotateFile(logfile string, rt rotatefile.RotateTime, fns ...ConfigFn) (*SyncCloseHandler, error)\n// It supports configuration to rotate according to size and time. \n// The default setting file size is 20M, and the default automatic splitting time is 1 hour (EveryHour).\nfunc NewRotateFileHandler(logfile string, rt rotatefile.RotateTime, fns ...ConfigFn) (*SyncCloseHandler, error)\n```\n\n\u003e TIP: By passing in `fns ...ConfigFn`, more options can be set, such as log file retention time, log write buffer size, etc. For detailed settings, see the `handler.Config` structure\n\n### Logs to file\n\nOutput log to the specified file, `buffer` buffered writing is not enabled by default. Buffering can also be enabled by passing in a parameter.\n\n```go\npackage mypkg\n\nimport (\n\t\"github.com/gookit/slog\"\n\t\"github.com/gookit/slog/handler\"\n)\n\nfunc main() {\n\tdefer slog.MustClose()\n\n\t// DangerLevels contains: slog.PanicLevel, slog.ErrorLevel, slog.WarnLevel\n\th1 := handler.MustFileHandler(\"/tmp/error.log\", handler.WithLogLevels(slog.DangerLevels))\n\t// custom log format\n\t// f := h1.Formatter().(*slog.TextFormatter)\n\tf := slog.AsTextFormatter(h1.Formatter())\n\tf.SetTemplate(\"your template format\\n\")\n\n\t// NormalLevels contains: slog.InfoLevel, slog.NoticeLevel, slog.DebugLevel, slog.TraceLevel\n\th2 := handler.MustFileHandler(\"/tmp/info.log\", handler.WithLogLevels(slog.NormalLevels))\n\n\t// register handlers\n\tslog.PushHandler(h1)\n\tslog.PushHandler(h2)\n\n\t// add logs\n\tslog.Info(\"info message text\")\n\tslog.Error(\"error message text\")\n}\n```\n\n\u003e **Note**: If write buffering `buffer` is enabled, be sure to call `logger.Close()` at the end of the program to flush the contents of the buffer to the file.\n\n### Log to file with automatic rotating\n\n`slog/handler` also has a built-in output log to a specified file, and supports splitting files by time and size at the same time.\nBy default, `buffer` buffered writing is enabled\n\n```go\nfunc Example_rotateFileHandler() {\n\th1 := handler.MustRotateFile(\"/tmp/error.log\", handler.EveryHour, handler.WithLogLevels(slog.DangerLevels))\n\th2 := handler.MustRotateFile(\"/tmp/info.log\", handler.EveryHour, handler.WithLogLevels(slog.NormalLevels))\n\n\tslog.PushHandler(h1)\n\tslog.PushHandler(h2)\n\n\t// add logs\n\tslog.Info(\"info message\")\n\tslog.Error(\"error message\")\n}\n```\n\nExample of file name sliced by time:\n\n```text\ntime-rotate-file.log\ntime-rotate-file.log.20201229_155753\ntime-rotate-file.log.20201229_155754\n```\n\nExample of a filename cut by size, in the format `filename.log.HIS_000N`. For example:\n\n```text\nsize-rotate-file.log\nsize-rotate-file.log.122915_0001\nsize-rotate-file.log.122915_0002\n```\n\n### Use rotatefile on another logger\n\n`rotatefile.Writer` can also be used with other logging packages, such as: `log`, `glog`, etc. \n\nFor example, using `rotatefile` on golang `log`:\n\n```go\npackage main\n\nimport (\n  \"log\"\n\n  \"github.com/gookit/slog/rotatefile\"\n)\n\nfunc main() {\n\tlogFile := \"testdata/go_logger.log\"\n\twriter, err := rotatefile.NewConfig(logFile).Create()\n\tif err != nil {\n\t\tpanic(err) \n\t}\n\n\tlog.SetOutput(writer)\n\tlog.Println(\"log message\")\n}\n```\n\n### Quickly create a Handler based on config\n\nThis is config struct for create a Handler:\n\n```go\n// Config struct\ntype Config struct {\n\t// Logfile for write logs\n\tLogfile string `json:\"logfile\" yaml:\"logfile\"`\n\t// LevelMode for filter log record. default LevelModeList\n\tLevelMode uint8 `json:\"level_mode\" yaml:\"level_mode\"`\n\t// Level value. use on LevelMode = LevelModeValue\n\tLevel slog.Level `json:\"level\" yaml:\"level\"`\n\t// Levels for log record\n\tLevels []slog.Level `json:\"levels\" yaml:\"levels\"`\n\t// UseJSON for format logs\n\tUseJSON bool `json:\"use_json\" yaml:\"use_json\"`\n\t// BuffMode type name. allow: line, bite\n\tBuffMode string `json:\"buff_mode\" yaml:\"buff_mode\"`\n\t// BuffSize for enable buffer, unit is bytes. set 0 to disable buffer\n\tBuffSize int `json:\"buff_size\" yaml:\"buff_size\"`\n\t// RotateTime for rotate file, unit is seconds.\n\tRotateTime rotatefile.RotateTime `json:\"rotate_time\" yaml:\"rotate_time\"`\n\t// MaxSize on rotate file by size, unit is bytes.\n\tMaxSize uint64 `json:\"max_size\" yaml:\"max_size\"`\n\t// Compress determines if the rotated log files should be compressed using gzip.\n\t// The default is not to perform compression.\n\tCompress bool `json:\"compress\" yaml:\"compress\"`\n\t// BackupNum max number for keep old files.\n\t// 0 is not limit, default is 20.\n\tBackupNum uint `json:\"backup_num\" yaml:\"backup_num\"`\n\t// BackupTime max time for keep old files. unit is hours\n\t// 0 is not limit, default is a week.\n\tBackupTime uint `json:\"backup_time\" yaml:\"backup_time\"`\n\t// RenameFunc build filename for rotate file\n\tRenameFunc func(filepath string, rotateNum uint) string\n}\n```\n\n**Examples**:\n\n```go\n\ttestFile := \"testdata/error.log\"\n\n\th := handler.NewEmptyConfig(\n\t\t\thandler.WithLogfile(testFile),\n\t\t\thandler.WithBuffSize(1024*8),\n\t\t\thandler.WithRotateTimeString(\"1hour\"),\n\t\t\thandler.WithLogLevels(slog.DangerLevels),\n\t\t).\n\t\tCreateHandler()\n\n\tl := slog.NewWithHandlers(h)\n```\n\n**About BuffMode**\n\n`Config.BuffMode` The name of the BuffMode type to use. Allow: line, bite\n\n- `BuffModeBite`: Buffer by bytes, when the number of bytes in the buffer reaches the specified size, write the contents of the buffer to the file\n- `BuffModeLine`: Buffer by line, when the buffer size is reached, always ensure that a complete line of log content is written to the file (to avoid log content being truncated)\n\n### Use Builder to quickly create Handler\n\nUse `handler.Builder` to easily and quickly create Handler instances.\n\n```go\n\ttestFile := \"testdata/info.log\"\n\n\th := handler.NewBuilder().\n\t\tWithLogfile(testFile).\n\t\tWithLogLevels(slog.NormalLevels).\n\t\tWithBuffSize(1024*8).\n\t\tWithRotateTime(rotatefile.Every30Min).\n\t\tWithCompress(true).\n\t\tBuild()\n\n\tl := slog.NewWithHandlers(h)\n```\n\n## Extension packages\n\nPackage `bufwrite`:\n\n- `bufwrite.BufIOWriter` additionally implements `Sync(), Close()` methods by wrapping go's `bufio.Writer`, which is convenient to use\n- `bufwrite.LineWriter` refer to the implementation of `bufio.Writer` in go, which can support flushing the buffer by line, which is more useful for writing log files\n\nPackage `rotatefile`:\n\n- `rotatefile.Writer` implements automatic cutting of log files according to size and specified time, and also supports automatic cleaning of log files\n  - `handler/rotate_file` is to use it to cut the log file\n\n### Use rotatefile on other log package\n\nOf course, the rotatefile.Writer can be use on other log package, such as: `log`, `glog` and more.\n\nExamples, use rotatefile on golang `log`:\n\n```go\npackage main\n\nimport (\n  \"log\"\n\n  \"github.com/gookit/slog/rotatefile\"\n)\n\nfunc main() {\n\tlogFile := \"testdata/another_logger.log\"\n\twriter, err := rotatefile.NewConfig(logFile).Create()\n\tif err != nil {\n\t\tpanic(err) \n\t}\n\n\tlog.SetOutput(writer)\n\tlog.Println(\"log message\")\n}\n```\n\n## Testing and benchmark\n\n### Unit tests\n\nrun unit tests:\n\n```bash\ngo test ./...\n```\n\n### Benchmarks\n\nBenchmark code at [_example/bench_loglibs_test.go](_example/bench_loglibs_test.go)\n\n```bash\nmake test-bench\n```\n\nBenchmarks for `slog` and other log packages:\n\n\u003e **Note**: test and record ad 2023.04.13\n\n```shell\ngoos: darwin\ngoarch: amd64\ncpu: Intel(R) Core(TM) i7-3740QM CPU @ 2.70GHz\nBenchmarkZapNegative\nBenchmarkZapNegative-4                   8381674              1429 ns/op             216 B/op          3 allocs/op\nBenchmarkZapSugarNegative\nBenchmarkZapSugarNegative-4              8655980              1383 ns/op             104 B/op          4 allocs/op\nBenchmarkZeroLogNegative\nBenchmarkZeroLogNegative-4              14173719               849.8 ns/op             0 B/op          0 allocs/op\nBenchmarkPhusLogNegative\nBenchmarkPhusLogNegative-4              27456256               451.2 ns/op             0 B/op          0 allocs/op\nBenchmarkLogrusNegative\nBenchmarkLogrusNegative-4                2550771              4784 ns/op             608 B/op         17 allocs/op\nBenchmarkGookitSlogNegative\n\u003e\u003e\u003e\u003e BenchmarkGookitSlogNegative-4       8798220              1375 ns/op             120 B/op          3 allocs/op\nBenchmarkZapPositive\nBenchmarkZapPositive-4                  10302483              1167 ns/op             192 B/op          1 allocs/op\nBenchmarkZapSugarPositive\nBenchmarkZapSugarPositive-4              3833311              3154 ns/op             344 B/op          7 allocs/op\nBenchmarkZeroLogPositive\nBenchmarkZeroLogPositive-4              14120524               846.7 ns/op             0 B/op          0 allocs/op\nBenchmarkPhusLogPositive\nBenchmarkPhusLogPositive-4              27152686               434.9 ns/op             0 B/op          0 allocs/op\nBenchmarkLogrusPositive\nBenchmarkLogrusPositive-4                2601892              4691 ns/op             608 B/op         17 allocs/op\nBenchmarkGookitSlogPositive\n\u003e\u003e\u003e\u003e BenchmarkGookitSlogPositive-4            8997104              1340 ns/op             120 B/op          3 allocs/op\nPASS\nok      command-line-arguments  167.095s\n```\n\n## Gookit packages\n\n  - [gookit/ini](https://github.com/gookit/ini) Go config management, use INI files\n  - [gookit/rux](https://github.com/gookit/rux) Simple and fast request router for golang HTTP \n  - [gookit/gcli](https://github.com/gookit/gcli) Build CLI application, tool library, running CLI commands\n  - [gookit/slog](https://github.com/gookit/slog) Lightweight, extensible, configurable logging library written in Go\n  - [gookit/color](https://github.com/gookit/color) A command-line color library with true color support, universal API methods and Windows support\n  - [gookit/event](https://github.com/gookit/event) Lightweight event manager and dispatcher implements by Go\n  - [gookit/cache](https://github.com/gookit/cache) Generic cache use and cache manager for golang. support File, Memory, Redis, Memcached.\n  - [gookit/config](https://github.com/gookit/config) Go config management. support JSON, YAML, TOML, INI, HCL, ENV and Flags\n  - [gookit/filter](https://github.com/gookit/filter) Provide filtering, sanitizing, and conversion of golang data\n  - [gookit/validate](https://github.com/gookit/validate) Use for data validation and filtering. support Map, Struct, Form data\n  - [gookit/goutil](https://github.com/gookit/goutil) Some utils for the Go: string, array/slice, map, format, cli, env, filesystem, test and more\n  - More, please see https://github.com/gookit\n\n## Acknowledgment\n\nThe projects is heavily inspired by follow packages:\n\n- https://github.com/phuslu/log\n- https://github.com/golang/glog\n- https://github.com/sirupsen/logrus\n- https://github.com/Seldaek/monolog\n- https://github.com/syyongx/llog\n- https://github.com/uber-go/zap\n- https://github.com/rs/zerolog\n- https://github.com/natefinch/lumberjack\n  \n## LICENSE\n\n[MIT](LICENSE)\n","funding_links":[],"categories":["Logging","日志记录","Go"],"sub_categories":["Search and Analytic Databases","Advanced Console UIs","检索及分析资料库"],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fgookit%2Fslog","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fgookit%2Fslog","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fgookit%2Fslog/lists"}