{"id":13413339,"url":"https://github.com/rs/zerolog","last_synced_at":"2025-09-09T21:17:17.287Z","repository":{"id":37949412,"uuid":"91054480","full_name":"rs/zerolog","owner":"rs","description":"Zero Allocation JSON Logger","archived":false,"fork":false,"pushed_at":"2025-04-18T11:14:43.000Z","size":1369,"stargazers_count":11330,"open_issues_count":134,"forks_count":588,"subscribers_count":72,"default_branch":"master","last_synced_at":"2025-05-03T08:35:11.677Z","etag":null,"topics":["golang","json","logging","structured-logging","zerolog"],"latest_commit_sha":null,"homepage":"","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/rs.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":"CONTRIBUTING.md","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,"zenodo":null}},"created_at":"2017-05-12T05:24:39.000Z","updated_at":"2025-05-03T00:09:10.000Z","dependencies_parsed_at":"2023-10-14T22:14:18.929Z","dependency_job_id":"847d9f02-6283-4983-aa2b-f7ca483c0574","html_url":"https://github.com/rs/zerolog","commit_stats":{"total_commits":361,"total_committers":161,"mean_commits":"2.2422360248447206","dds":0.6149584487534626,"last_synced_commit":"1869fa55bea5c09e93a06368c6a8756780dca5f7"},"previous_names":[],"tags_count":52,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/rs%2Fzerolog","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/rs%2Fzerolog/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/rs%2Fzerolog/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/rs%2Fzerolog/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/rs","download_url":"https://codeload.github.com/rs/zerolog/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":252522182,"owners_count":21761685,"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":["golang","json","logging","structured-logging","zerolog"],"created_at":"2024-07-30T20:01:38.149Z","updated_at":"2025-05-05T15:22:04.635Z","avatar_url":"https://github.com/rs.png","language":"Go","readme":"# Zero Allocation JSON Logger\n\n[![godoc](http://img.shields.io/badge/godoc-reference-blue.svg?style=flat)](https://godoc.org/github.com/rs/zerolog) [![license](http://img.shields.io/badge/license-MIT-red.svg?style=flat)](https://raw.githubusercontent.com/rs/zerolog/master/LICENSE) [![Build Status](https://github.com/rs/zerolog/actions/workflows/test.yml/badge.svg)](https://github.com/rs/zerolog/actions/workflows/test.yml) [![Go Coverage](https://github.com/rs/zerolog/wiki/coverage.svg)](https://raw.githack.com/wiki/rs/zerolog/coverage.html)\n\nThe zerolog package provides a fast and simple logger dedicated to JSON output.\n\nZerolog's API is designed to provide both a great developer experience and stunning [performance](#benchmarks). Its unique chaining API allows zerolog to write JSON (or CBOR) log events by avoiding allocations and reflection.\n\nUber's [zap](https://godoc.org/go.uber.org/zap) library pioneered this approach. Zerolog is taking this concept to the next level with a simpler to use API and even better performance.\n\nTo keep the code base and the API simple, zerolog focuses on efficient structured logging only. Pretty logging on the console is made possible using the provided (but inefficient) [`zerolog.ConsoleWriter`](#pretty-logging).\n\n![Pretty Logging Image](pretty.png)\n\n## Who uses zerolog\n\nFind out [who uses zerolog](https://github.com/rs/zerolog/wiki/Who-uses-zerolog) and add your company / project to the list.\n\n## Features\n\n* [Blazing fast](#benchmarks)\n* [Low to zero allocation](#benchmarks)\n* [Leveled logging](#leveled-logging)\n* [Sampling](#log-sampling)\n* [Hooks](#hooks)\n* [Contextual fields](#contextual-logging)\n* [`context.Context` integration](#contextcontext-integration)\n* [Integration with `net/http`](#integration-with-nethttp)\n* [JSON and CBOR encoding formats](#binary-encoding)\n* [Pretty logging for development](#pretty-logging)\n* [Error Logging (with optional Stacktrace)](#error-logging)\n\n## Installation\n\n```bash\ngo get -u github.com/rs/zerolog/log\n```\n\n## Getting Started\n\n### Simple Logging Example\n\nFor simple logging, import the global logger package **github.com/rs/zerolog/log**\n\n```go\npackage main\n\nimport (\n    \"github.com/rs/zerolog\"\n    \"github.com/rs/zerolog/log\"\n)\n\nfunc main() {\n    // UNIX Time is faster and smaller than most timestamps\n    zerolog.TimeFieldFormat = zerolog.TimeFormatUnix\n\n    log.Print(\"hello world\")\n}\n\n// Output: {\"time\":1516134303,\"level\":\"debug\",\"message\":\"hello world\"}\n```\n\u003e Note: By default log writes to `os.Stderr`\n\u003e Note: The default log level for `log.Print` is *trace*\n\n### Contextual Logging\n\n**zerolog** allows data to be added to log messages in the form of key:value pairs. The data added to the message adds \"context\" about the log event that can be critical for debugging as well as myriad other purposes. An example of this is below:\n\n```go\npackage main\n\nimport (\n    \"github.com/rs/zerolog\"\n    \"github.com/rs/zerolog/log\"\n)\n\nfunc main() {\n    zerolog.TimeFieldFormat = zerolog.TimeFormatUnix\n\n    log.Debug().\n        Str(\"Scale\", \"833 cents\").\n        Float64(\"Interval\", 833.09).\n        Msg(\"Fibonacci is everywhere\")\n    \n    log.Debug().\n        Str(\"Name\", \"Tom\").\n        Send()\n}\n\n// Output: {\"level\":\"debug\",\"Scale\":\"833 cents\",\"Interval\":833.09,\"time\":1562212768,\"message\":\"Fibonacci is everywhere\"}\n// Output: {\"level\":\"debug\",\"Name\":\"Tom\",\"time\":1562212768}\n```\n\n\u003e You'll note in the above example that when adding contextual fields, the fields are strongly typed. You can find the full list of supported fields [here](#standard-types)\n\n### Leveled Logging\n\n#### Simple Leveled Logging Example\n\n```go\npackage main\n\nimport (\n    \"github.com/rs/zerolog\"\n    \"github.com/rs/zerolog/log\"\n)\n\nfunc main() {\n    zerolog.TimeFieldFormat = zerolog.TimeFormatUnix\n\n    log.Info().Msg(\"hello world\")\n}\n\n// Output: {\"time\":1516134303,\"level\":\"info\",\"message\":\"hello world\"}\n```\n\n\u003e It is very important to note that when using the **zerolog** chaining API, as shown above (`log.Info().Msg(\"hello world\"`), the chain must have either the `Msg` or `Msgf` method call. If you forget to add either of these, the log will not occur and there is no compile time error to alert you of this.\n\n**zerolog** allows for logging at the following levels (from highest to lowest):\n\n* panic (`zerolog.PanicLevel`, 5)\n* fatal (`zerolog.FatalLevel`, 4)\n* error (`zerolog.ErrorLevel`, 3)\n* warn (`zerolog.WarnLevel`, 2)\n* info (`zerolog.InfoLevel`, 1)\n* debug (`zerolog.DebugLevel`, 0)\n* trace (`zerolog.TraceLevel`, -1)\n\nYou can set the Global logging level to any of these options using the `SetGlobalLevel` function in the zerolog package, passing in one of the given constants above, e.g. `zerolog.InfoLevel` would be the \"info\" level.  Whichever level is chosen, all logs with a level greater than or equal to that level will be written. To turn off logging entirely, pass the `zerolog.Disabled` constant.\n\n#### Setting Global Log Level\n\nThis example uses command-line flags to demonstrate various outputs depending on the chosen log level.\n\n```go\npackage main\n\nimport (\n    \"flag\"\n\n    \"github.com/rs/zerolog\"\n    \"github.com/rs/zerolog/log\"\n)\n\nfunc main() {\n    zerolog.TimeFieldFormat = zerolog.TimeFormatUnix\n    debug := flag.Bool(\"debug\", false, \"sets log level to debug\")\n\n    flag.Parse()\n\n    // Default level for this example is info, unless debug flag is present\n    zerolog.SetGlobalLevel(zerolog.InfoLevel)\n    if *debug {\n        zerolog.SetGlobalLevel(zerolog.DebugLevel)\n    }\n\n    log.Debug().Msg(\"This message appears only when log level set to Debug\")\n    log.Info().Msg(\"This message appears when log level set to Debug or Info\")\n\n    if e := log.Debug(); e.Enabled() {\n        // Compute log output only if enabled.\n        value := \"bar\"\n        e.Str(\"foo\", value).Msg(\"some debug message\")\n    }\n}\n```\n\nInfo Output (no flag)\n\n```bash\n$ ./logLevelExample\n{\"time\":1516387492,\"level\":\"info\",\"message\":\"This message appears when log level set to Debug or Info\"}\n```\n\nDebug Output (debug flag set)\n\n```bash\n$ ./logLevelExample -debug\n{\"time\":1516387573,\"level\":\"debug\",\"message\":\"This message appears only when log level set to Debug\"}\n{\"time\":1516387573,\"level\":\"info\",\"message\":\"This message appears when log level set to Debug or Info\"}\n{\"time\":1516387573,\"level\":\"debug\",\"foo\":\"bar\",\"message\":\"some debug message\"}\n```\n\n#### Logging without Level or Message\n\nYou may choose to log without a specific level by using the `Log` method. You may also write without a message by setting an empty string in the `msg string` parameter of the `Msg` method. Both are demonstrated in the example below.\n\n```go\npackage main\n\nimport (\n    \"github.com/rs/zerolog\"\n    \"github.com/rs/zerolog/log\"\n)\n\nfunc main() {\n    zerolog.TimeFieldFormat = zerolog.TimeFormatUnix\n\n    log.Log().\n        Str(\"foo\", \"bar\").\n        Msg(\"\")\n}\n\n// Output: {\"time\":1494567715,\"foo\":\"bar\"}\n```\n\n### Error Logging\n\nYou can log errors using the `Err` method\n\n```go\npackage main\n\nimport (\n\t\"errors\"\n\n\t\"github.com/rs/zerolog\"\n\t\"github.com/rs/zerolog/log\"\n)\n\nfunc main() {\n\tzerolog.TimeFieldFormat = zerolog.TimeFormatUnix\n\n\terr := errors.New(\"seems we have an error here\")\n\tlog.Error().Err(err).Msg(\"\")\n}\n\n// Output: {\"level\":\"error\",\"error\":\"seems we have an error here\",\"time\":1609085256}\n```\n\n\u003e The default field name for errors is `error`, you can change this by setting `zerolog.ErrorFieldName` to meet your needs.\n\n#### Error Logging with Stacktrace\n\nUsing `github.com/pkg/errors`, you can add a formatted stacktrace to your errors. \n\n```go\npackage main\n\nimport (\n\t\"github.com/pkg/errors\"\n\t\"github.com/rs/zerolog/pkgerrors\"\n\n\t\"github.com/rs/zerolog\"\n\t\"github.com/rs/zerolog/log\"\n)\n\nfunc main() {\n\tzerolog.TimeFieldFormat = zerolog.TimeFormatUnix\n\tzerolog.ErrorStackMarshaler = pkgerrors.MarshalStack\n\n\terr := outer()\n\tlog.Error().Stack().Err(err).Msg(\"\")\n}\n\nfunc inner() error {\n\treturn errors.New(\"seems we have an error here\")\n}\n\nfunc middle() error {\n\terr := inner()\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc outer() error {\n\terr := middle()\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\n// Output: {\"level\":\"error\",\"stack\":[{\"func\":\"inner\",\"line\":\"20\",\"source\":\"errors.go\"},{\"func\":\"middle\",\"line\":\"24\",\"source\":\"errors.go\"},{\"func\":\"outer\",\"line\":\"32\",\"source\":\"errors.go\"},{\"func\":\"main\",\"line\":\"15\",\"source\":\"errors.go\"},{\"func\":\"main\",\"line\":\"204\",\"source\":\"proc.go\"},{\"func\":\"goexit\",\"line\":\"1374\",\"source\":\"asm_amd64.s\"}],\"error\":\"seems we have an error here\",\"time\":1609086683}\n```\n\n\u003e zerolog.ErrorStackMarshaler must be set in order for the stack to output anything.\n\n#### Logging Fatal Messages\n\n```go\npackage main\n\nimport (\n    \"errors\"\n\n    \"github.com/rs/zerolog\"\n    \"github.com/rs/zerolog/log\"\n)\n\nfunc main() {\n    err := errors.New(\"A repo man spends his life getting into tense situations\")\n    service := \"myservice\"\n\n    zerolog.TimeFieldFormat = zerolog.TimeFormatUnix\n\n    log.Fatal().\n        Err(err).\n        Str(\"service\", service).\n        Msgf(\"Cannot start %s\", service)\n}\n\n// Output: {\"time\":1516133263,\"level\":\"fatal\",\"error\":\"A repo man spends his life getting into tense situations\",\"service\":\"myservice\",\"message\":\"Cannot start myservice\"}\n//         exit status 1\n```\n\n\u003e NOTE: Using `Msgf` generates one allocation even when the logger is disabled.\n\n\n### Create logger instance to manage different outputs\n\n```go\nlogger := zerolog.New(os.Stderr).With().Timestamp().Logger()\n\nlogger.Info().Str(\"foo\", \"bar\").Msg(\"hello world\")\n\n// Output: {\"level\":\"info\",\"time\":1494567715,\"message\":\"hello world\",\"foo\":\"bar\"}\n```\n\n### Sub-loggers let you chain loggers with additional context\n\n```go\nsublogger := log.With().\n                 Str(\"component\", \"foo\").\n                 Logger()\nsublogger.Info().Msg(\"hello world\")\n\n// Output: {\"level\":\"info\",\"time\":1494567715,\"message\":\"hello world\",\"component\":\"foo\"}\n```\n\n### Pretty logging\n\nTo log a human-friendly, colorized output, use `zerolog.ConsoleWriter`:\n\n```go\nlog.Logger = log.Output(zerolog.ConsoleWriter{Out: os.Stderr})\n\nlog.Info().Str(\"foo\", \"bar\").Msg(\"Hello world\")\n\n// Output: 3:04PM INF Hello World foo=bar\n```\n\nTo customize the configuration and formatting:\n\n```go\noutput := zerolog.ConsoleWriter{Out: os.Stdout, TimeFormat: time.RFC3339}\noutput.FormatLevel = func(i interface{}) string {\n    return strings.ToUpper(fmt.Sprintf(\"| %-6s|\", i))\n}\noutput.FormatMessage = func(i interface{}) string {\n    return fmt.Sprintf(\"***%s****\", i)\n}\noutput.FormatFieldName = func(i interface{}) string {\n    return fmt.Sprintf(\"%s:\", i)\n}\noutput.FormatFieldValue = func(i interface{}) string {\n    return strings.ToUpper(fmt.Sprintf(\"%s\", i))\n}\n\nlog := zerolog.New(output).With().Timestamp().Logger()\n\nlog.Info().Str(\"foo\", \"bar\").Msg(\"Hello World\")\n\n// Output: 2006-01-02T15:04:05Z07:00 | INFO  | ***Hello World**** foo:BAR\n```\n\nTo use custom advanced formatting:\n\n```go\noutput := zerolog.ConsoleWriter{Out: os.Stdout, NoColor: true,\n    PartsOrder:    []string{\"level\", \"one\", \"two\", \"three\", \"message\"},\n    FieldsExclude: []string{\"one\", \"two\", \"three\"}}\noutput.FormatLevel = func(i interface{}) string { return strings.ToUpper(fmt.Sprintf(\"%-6s\", i)) }\noutput.FormatFieldName = func(i interface{}) string { return fmt.Sprintf(\"%s:\", i) }\noutput.FormatPartValueByName = func(i interface{}, s string) string {\n    var ret string\n    switch s {\n    case \"one\":\n        ret = strings.ToUpper(fmt.Sprintf(\"%s\", i))\n    case \"two\":\n        ret = strings.ToLower(fmt.Sprintf(\"%s\", i))\n    case \"three\":\n        ret = strings.ToLower(fmt.Sprintf(\"(%s)\", i))\n    }\n    return ret\n}\nlog := zerolog.New(output)\n\nlog.Info().Str(\"foo\", \"bar\").\n    Str(\"two\", \"TEST_TWO\").\n    Str(\"one\", \"test_one\").\n    Str(\"three\", \"test_three\").\n    Msg(\"Hello World\")\n    \n// Output: INFO   TEST_ONE test_two (test_three) Hello World foo:bar\n```\n\n### Sub dictionary\n\n```go\nlog.Info().\n    Str(\"foo\", \"bar\").\n    Dict(\"dict\", zerolog.Dict().\n        Str(\"bar\", \"baz\").\n        Int(\"n\", 1),\n    ).Msg(\"hello world\")\n\n// Output: {\"level\":\"info\",\"time\":1494567715,\"foo\":\"bar\",\"dict\":{\"bar\":\"baz\",\"n\":1},\"message\":\"hello world\"}\n```\n\n### Customize automatic field names\n\n```go\nzerolog.TimestampFieldName = \"t\"\nzerolog.LevelFieldName = \"l\"\nzerolog.MessageFieldName = \"m\"\n\nlog.Info().Msg(\"hello world\")\n\n// Output: {\"l\":\"info\",\"t\":1494567715,\"m\":\"hello world\"}\n```\n\n### Add contextual fields to the global logger\n\n```go\nlog.Logger = log.With().Str(\"foo\", \"bar\").Logger()\n```\n\n### Add file and line number to log\n\nEquivalent of `Llongfile`:\n\n```go\nlog.Logger = log.With().Caller().Logger()\nlog.Info().Msg(\"hello world\")\n\n// Output: {\"level\": \"info\", \"message\": \"hello world\", \"caller\": \"/go/src/your_project/some_file:21\"}\n```\n\nEquivalent of `Lshortfile`:\n\n```go\nzerolog.CallerMarshalFunc = func(pc uintptr, file string, line int) string {\n    return filepath.Base(file) + \":\" + strconv.Itoa(line)\n}\nlog.Logger = log.With().Caller().Logger()\nlog.Info().Msg(\"hello world\")\n\n// Output: {\"level\": \"info\", \"message\": \"hello world\", \"caller\": \"some_file:21\"}\n```\n\n### Thread-safe, lock-free, non-blocking writer\n\nIf your writer might be slow or not thread-safe and you need your log producers to never get slowed down by a slow writer, you can use a `diode.Writer` as follows:\n\n```go\nwr := diode.NewWriter(os.Stdout, 1000, 10*time.Millisecond, func(missed int) {\n\t\tfmt.Printf(\"Logger Dropped %d messages\", missed)\n\t})\nlog := zerolog.New(wr)\nlog.Print(\"test\")\n```\n\nYou will need to install `code.cloudfoundry.org/go-diodes` to use this feature.\n\n### Log Sampling\n\n```go\nsampled := log.Sample(\u0026zerolog.BasicSampler{N: 10})\nsampled.Info().Msg(\"will be logged every 10 messages\")\n\n// Output: {\"time\":1494567715,\"level\":\"info\",\"message\":\"will be logged every 10 messages\"}\n```\n\nMore advanced sampling:\n\n```go\n// Will let 5 debug messages per period of 1 second.\n// Over 5 debug message, 1 every 100 debug messages are logged.\n// Other levels are not sampled.\nsampled := log.Sample(zerolog.LevelSampler{\n    DebugSampler: \u0026zerolog.BurstSampler{\n        Burst: 5,\n        Period: 1*time.Second,\n        NextSampler: \u0026zerolog.BasicSampler{N: 100},\n    },\n})\nsampled.Debug().Msg(\"hello world\")\n\n// Output: {\"time\":1494567715,\"level\":\"debug\",\"message\":\"hello world\"}\n```\n\n### Hooks\n\n```go\ntype SeverityHook struct{}\n\nfunc (h SeverityHook) Run(e *zerolog.Event, level zerolog.Level, msg string) {\n    if level != zerolog.NoLevel {\n        e.Str(\"severity\", level.String())\n    }\n}\n\nhooked := log.Hook(SeverityHook{})\nhooked.Warn().Msg(\"\")\n\n// Output: {\"level\":\"warn\",\"severity\":\"warn\"}\n```\n\n### Pass a sub-logger by context\n\n```go\nctx := log.With().Str(\"component\", \"module\").Logger().WithContext(ctx)\n\nlog.Ctx(ctx).Info().Msg(\"hello world\")\n\n// Output: {\"component\":\"module\",\"level\":\"info\",\"message\":\"hello world\"}\n```\n\n### Set as standard logger output\n\n```go\nlog := zerolog.New(os.Stdout).With().\n    Str(\"foo\", \"bar\").\n    Logger()\n\nstdlog.SetFlags(0)\nstdlog.SetOutput(log)\n\nstdlog.Print(\"hello world\")\n\n// Output: {\"foo\":\"bar\",\"message\":\"hello world\"}\n```\n\n### context.Context integration\n\nGo contexts are commonly passed throughout Go code, and this can help you pass\nyour Logger into places it might otherwise be hard to inject.  The `Logger`\ninstance may be attached to Go context (`context.Context`) using\n`Logger.WithContext(ctx)` and extracted from it using `zerolog.Ctx(ctx)`.\nFor example:\n\n```go\nfunc f() {\n    logger := zerolog.New(os.Stdout)\n    ctx := context.Background()\n\n    // Attach the Logger to the context.Context\n    ctx = logger.WithContext(ctx)\n    someFunc(ctx)\n}\n\nfunc someFunc(ctx context.Context) {\n    // Get Logger from the go Context. if it's nil, then\n    // `zerolog.DefaultContextLogger` is returned, if\n    // `DefaultContextLogger` is nil, then a disabled logger is returned.\n    logger := zerolog.Ctx(ctx)\n    logger.Info().Msg(\"Hello\")\n}\n```\n\nA second form of `context.Context` integration allows you to pass the current\ncontext.Context into the logged event, and retrieve it from hooks.  This can be\nuseful to log trace and span IDs or other information stored in the go context,\nand facilitates the unification of logging and tracing in some systems:\n\n```go\ntype TracingHook struct{}\n\nfunc (h TracingHook) Run(e *zerolog.Event, level zerolog.Level, msg string) {\n    ctx := e.GetCtx()\n    spanId := getSpanIdFromContext(ctx) // as per your tracing framework\n    e.Str(\"span-id\", spanId)\n}\n\nfunc f() {\n    // Setup the logger\n    logger := zerolog.New(os.Stdout)\n    logger = logger.Hook(TracingHook{})\n\n    ctx := context.Background()\n    // Use the Ctx function to make the context available to the hook\n    logger.Info().Ctx(ctx).Msg(\"Hello\")\n}\n```\n\n### Integration with `net/http`\n\nThe `github.com/rs/zerolog/hlog` package provides some helpers to integrate zerolog with `http.Handler`.\n\nIn this example we use [alice](https://github.com/justinas/alice) to install logger for better readability.\n\n```go\nlog := zerolog.New(os.Stdout).With().\n    Timestamp().\n    Str(\"role\", \"my-service\").\n    Str(\"host\", host).\n    Logger()\n\nc := alice.New()\n\n// Install the logger handler with default output on the console\nc = c.Append(hlog.NewHandler(log))\n\n// Install some provided extra handler to set some request's context fields.\n// Thanks to that handler, all our logs will come with some prepopulated fields.\nc = c.Append(hlog.AccessHandler(func(r *http.Request, status, size int, duration time.Duration) {\n    hlog.FromRequest(r).Info().\n        Str(\"method\", r.Method).\n        Stringer(\"url\", r.URL).\n        Int(\"status\", status).\n        Int(\"size\", size).\n        Dur(\"duration\", duration).\n        Msg(\"\")\n}))\nc = c.Append(hlog.RemoteAddrHandler(\"ip\"))\nc = c.Append(hlog.UserAgentHandler(\"user_agent\"))\nc = c.Append(hlog.RefererHandler(\"referer\"))\nc = c.Append(hlog.RequestIDHandler(\"req_id\", \"Request-Id\"))\n\n// Here is your final handler\nh := c.Then(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n    // Get the logger from the request's context. You can safely assume it\n    // will be always there: if the handler is removed, hlog.FromRequest\n    // will return a no-op logger.\n    hlog.FromRequest(r).Info().\n        Str(\"user\", \"current user\").\n        Str(\"status\", \"ok\").\n        Msg(\"Something happened\")\n\n    // Output: {\"level\":\"info\",\"time\":\"2001-02-03T04:05:06Z\",\"role\":\"my-service\",\"host\":\"local-hostname\",\"req_id\":\"b4g0l5t6tfid6dtrapu0\",\"user\":\"current user\",\"status\":\"ok\",\"message\":\"Something happened\"}\n}))\nhttp.Handle(\"/\", h)\n\nif err := http.ListenAndServe(\":8080\", nil); err != nil {\n    log.Fatal().Err(err).Msg(\"Startup failed\")\n}\n```\n\n## Multiple Log Output\n`zerolog.MultiLevelWriter` may be used to send the log message to multiple outputs. \nIn this example, we send the log message to both `os.Stdout` and the in-built ConsoleWriter.\n```go\nfunc main() {\n\tconsoleWriter := zerolog.ConsoleWriter{Out: os.Stdout}\n\n\tmulti := zerolog.MultiLevelWriter(consoleWriter, os.Stdout)\n\n\tlogger := zerolog.New(multi).With().Timestamp().Logger()\n\n\tlogger.Info().Msg(\"Hello World!\")\n}\n\n// Output (Line 1: Console; Line 2: Stdout)\n// 12:36PM INF Hello World!\n// {\"level\":\"info\",\"time\":\"2019-11-07T12:36:38+03:00\",\"message\":\"Hello World!\"}\n```\n\n## Global Settings\n\nSome settings can be changed and will be applied to all loggers:\n\n* `log.Logger`: You can set this value to customize the global logger (the one used by package level methods).\n* `zerolog.SetGlobalLevel`: Can raise the minimum level of all loggers. Call this with `zerolog.Disabled` to disable logging altogether (quiet mode).\n* `zerolog.DisableSampling`: If argument is `true`, all sampled loggers will stop sampling and issue 100% of their log events.\n* `zerolog.TimestampFieldName`: Can be set to customize `Timestamp` field name.\n* `zerolog.LevelFieldName`: Can be set to customize level field name.\n* `zerolog.MessageFieldName`: Can be set to customize message field name.\n* `zerolog.ErrorFieldName`: Can be set to customize `Err` field name.\n* `zerolog.TimeFieldFormat`: Can be set to customize `Time` field value formatting. If set with `zerolog.TimeFormatUnix`, `zerolog.TimeFormatUnixMs` or `zerolog.TimeFormatUnixMicro`, times are formatted as UNIX timestamp.\n* `zerolog.DurationFieldUnit`: Can be set to customize the unit for time.Duration type fields added by `Dur` (default: `time.Millisecond`).\n* `zerolog.DurationFieldInteger`: If set to `true`, `Dur` fields are formatted as integers instead of floats (default: `false`). \n* `zerolog.ErrorHandler`: Called whenever zerolog fails to write an event on its output. If not set, an error is printed on the stderr. This handler must be thread safe and non-blocking.\n* `zerolog.FloatingPointPrecision`: If set to a value other than -1, controls the number\nof digits when formatting float numbers in JSON. See\n[strconv.FormatFloat](https://pkg.go.dev/strconv#FormatFloat)\nfor more details.\n\n## Field Types\n\n### Standard Types\n\n* `Str`\n* `Bool`\n* `Int`, `Int8`, `Int16`, `Int32`, `Int64`\n* `Uint`, `Uint8`, `Uint16`, `Uint32`, `Uint64`\n* `Float32`, `Float64`\n\n### Advanced Fields\n\n* `Err`: Takes an `error` and renders it as a string using the `zerolog.ErrorFieldName` field name.\n* `Func`: Run a `func` only if the level is enabled.\n* `Timestamp`: Inserts a timestamp field with `zerolog.TimestampFieldName` field name, formatted using `zerolog.TimeFieldFormat`.\n* `Time`: Adds a field with time formatted with `zerolog.TimeFieldFormat`.\n* `Dur`: Adds a field with `time.Duration`.\n* `Dict`: Adds a sub-key/value as a field of the event.\n* `RawJSON`: Adds a field with an already encoded JSON (`[]byte`)\n* `Hex`: Adds a field with value formatted as a hexadecimal string (`[]byte`)\n* `Interface`: Uses reflection to marshal the type.\n\nMost fields are also available in the slice format (`Strs` for `[]string`, `Errs` for `[]error` etc.)\n\n## Binary Encoding\n\nIn addition to the default JSON encoding, `zerolog` can produce binary logs using [CBOR](https://cbor.io) encoding. The choice of encoding can be decided at compile time using the build tag `binary_log` as follows:\n\n```bash\ngo build -tags binary_log .\n```\n\nTo Decode binary encoded log files you can use any CBOR decoder. One has been tested to work\nwith zerolog library is [CSD](https://github.com/toravir/csd/).\n\n## Related Projects\n\n* [grpc-zerolog](https://github.com/cheapRoc/grpc-zerolog): Implementation of `grpclog.LoggerV2` interface using `zerolog`\n* [overlog](https://github.com/Trendyol/overlog): Implementation of `Mapped Diagnostic Context` interface using `zerolog`\n* [zerologr](https://github.com/go-logr/zerologr): Implementation of `logr.LogSink` interface using `zerolog`\n\n## Benchmarks\n\nSee [logbench](http://bench.zerolog.io/) for more comprehensive and up-to-date benchmarks.\n\nAll operations are allocation free (those numbers *include* JSON encoding):\n\n```text\nBenchmarkLogEmpty-8        100000000    19.1 ns/op     0 B/op       0 allocs/op\nBenchmarkDisabled-8        500000000    4.07 ns/op     0 B/op       0 allocs/op\nBenchmarkInfo-8            30000000     42.5 ns/op     0 B/op       0 allocs/op\nBenchmarkContextFields-8   30000000     44.9 ns/op     0 B/op       0 allocs/op\nBenchmarkLogFields-8       10000000     184 ns/op      0 B/op       0 allocs/op\n```\n\nThere are a few Go logging benchmarks and comparisons that include zerolog.\n\n* [imkira/go-loggers-bench](https://github.com/imkira/go-loggers-bench)\n* [uber-common/zap](https://github.com/uber-go/zap#performance)\n\nUsing Uber's zap comparison benchmark:\n\nLog a message and 10 fields:\n\n| Library | Time | Bytes Allocated | Objects Allocated |\n| :--- | :---: | :---: | :---: |\n| zerolog | 767 ns/op | 552 B/op | 6 allocs/op |\n| :zap: zap | 848 ns/op | 704 B/op | 2 allocs/op |\n| :zap: zap (sugared) | 1363 ns/op | 1610 B/op | 20 allocs/op |\n| go-kit | 3614 ns/op | 2895 B/op | 66 allocs/op |\n| lion | 5392 ns/op | 5807 B/op | 63 allocs/op |\n| logrus | 5661 ns/op | 6092 B/op | 78 allocs/op |\n| apex/log | 15332 ns/op | 3832 B/op | 65 allocs/op |\n| log15 | 20657 ns/op | 5632 B/op | 93 allocs/op |\n\nLog a message with a logger that already has 10 fields of context:\n\n| Library | Time | Bytes Allocated | Objects Allocated |\n| :--- | :---: | :---: | :---: |\n| zerolog | 52 ns/op | 0 B/op | 0 allocs/op |\n| :zap: zap | 283 ns/op | 0 B/op | 0 allocs/op |\n| :zap: zap (sugared) | 337 ns/op | 80 B/op | 2 allocs/op |\n| lion | 2702 ns/op | 4074 B/op | 38 allocs/op |\n| go-kit | 3378 ns/op | 3046 B/op | 52 allocs/op |\n| logrus | 4309 ns/op | 4564 B/op | 63 allocs/op |\n| apex/log | 13456 ns/op | 2898 B/op | 51 allocs/op |\n| log15 | 14179 ns/op | 2642 B/op | 44 allocs/op |\n\nLog a static string, without any context or `printf`-style templating:\n\n| Library | Time | Bytes Allocated | Objects Allocated |\n| :--- | :---: | :---: | :---: |\n| zerolog | 50 ns/op | 0 B/op | 0 allocs/op |\n| :zap: zap | 236 ns/op | 0 B/op | 0 allocs/op |\n| standard library | 453 ns/op | 80 B/op | 2 allocs/op |\n| :zap: zap (sugared) | 337 ns/op | 80 B/op | 2 allocs/op |\n| go-kit | 508 ns/op | 656 B/op | 13 allocs/op |\n| lion | 771 ns/op | 1224 B/op | 10 allocs/op |\n| logrus | 1244 ns/op | 1505 B/op | 27 allocs/op |\n| apex/log | 2751 ns/op | 584 B/op | 11 allocs/op |\n| log15 | 5181 ns/op | 1592 B/op | 26 allocs/op |\n\n## Caveats\n\n### Field duplication\n\nNote that zerolog does no de-duplication of fields. Using the same key multiple times creates multiple keys in final JSON:\n\n```go\nlogger := zerolog.New(os.Stderr).With().Timestamp().Logger()\nlogger.Info().\n       Timestamp().\n       Msg(\"dup\")\n// Output: {\"level\":\"info\",\"time\":1494567715,\"time\":1494567715,\"message\":\"dup\"}\n```\n\nIn this case, many consumers will take the last value, but this is not guaranteed; check yours if in doubt.\n\n### Concurrency safety\n\nBe careful when calling UpdateContext. It is not concurrency safe. Use the With method to create a child logger:\n\n```go\nfunc handler(w http.ResponseWriter, r *http.Request) {\n    // Create a child logger for concurrency safety\n    logger := log.Logger.With().Logger()\n\n    // Add context fields, for example User-Agent from HTTP headers\n    logger.UpdateContext(func(c zerolog.Context) zerolog.Context {\n        ...\n    })\n}\n```\n","funding_links":[],"categories":["Popular","HarmonyOS","Go","开源类库","Misc","Logging","Uncategorized","Open source library","0x0A. rs/zerolog","语言资源库","日志","Logging 日志库","Relational Databases","\u003cspan id=\"日志-logging\"\u003e日志 Logging\u003c/span\u003e","日志记录","日誌","日志库","Dependencies"],"sub_categories":["Windows Manager","日志","Search and Analytic Databases","Advanced Console UIs","Uncategorized","Logs","go","SQL 查询语句构建库","\u003cspan id=\"高级控制台用户界面-advanced-console-uis\"\u003e高级控制台用户界面 Advanced Console UIs\u003c/span\u003e","检索及分析资料库","高级控制台界面","高級控制台界面","Potential Issues","交流"],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Frs%2Fzerolog","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Frs%2Fzerolog","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Frs%2Fzerolog/lists"}