gpt4 book ai didi

logging - 带有 gorilla 复用器的 Go 记录器装饰器

转载 作者:IT王子 更新时间:2023-10-29 02:24:03 25 4
gpt4 key购买 nike

我是 Go 的新手,并在 http://thenewstack.io/make-a-restful-json-api-go/ 之后使用 mux 来创建一些 REST API。 .虽然它大部分工作正常,但我没有看到使用 Log.Println 记录 HTTP 请求的 Logger 装饰器按预期进行控制台记录。

我错过了什么吗?此外,看起来在遍历路由列表时调用了 Logger,这是为每个请求记录日志的正确方法吗?

最佳答案

日志默认流向 stderr。如果您想查看服务器的输出(例如,名为“testAPI”),您需要将 stderr 重定向到 stdout(您的终端):

// If already compiled
/path/to/testAPI 2>&1
// Without building / installing
go run testAPI.go 2>&1

如果您只是想让它记录到一个日志文件:

// If already compiled
/path/to/testAPI 2> /path/to/logs/testAPI.log
// Without building / installing
go run testAPI.go 2> /path/to/logs/testAPI.log

The pkg/log source在内部定义输出:

var std = New(os.Stderr, "", LstdFlags)

最后,来自the standard lib docs :

Package log implements a simple logging package. It defines a type, Logger, with methods for formatting output. It also has a predefined 'standard' Logger accessible through helper functions Print[f|ln], Fatal[f|ln], and Panic[f|ln], which are easier to use than creating a Logger manually. That logger writes to standard error and prints the date and time of each logged message. The Fatal functions call os.Exit(1) after writing the log message. The Panic functions call panic after writing the log message.

关于logging - 带有 gorilla 复用器的 Go 记录器装饰器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28731594/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com