Appearance
日志器中间件
🌐 Logger Middleware
这是一个简单的日志器。
🌐 It's a simple logger.
导入
🌐 Import
ts
import { Hono } from 'hono'
import { logger } from 'hono/logger'用法
🌐 Usage
ts
const app = new Hono()
app.use(logger())
app.get('/', (c) => c.text('Hello Hono!'))日志详细信息
🌐 Logging Details
Logger 中间件记录每个请求的以下详细信息:
🌐 The Logger Middleware logs the following details for each request:
- 接收请求:记录 HTTP 方法、请求路径和接收的请求。
- 外发响应:记录 HTTP 方法、请求路径、响应状态码以及请求/响应时间。
- 状态码着色:响应状态码使用颜色编码,以便更好地可见性和快速识别状态类别。不同的状态码类别用不同的颜色表示。
- 耗时:请求/响应周期所花费的时间以人类可读的格式记录,单位可以是毫秒(ms)或秒(s)。
通过使用 Logger 中间件,你可以轻松监控 Hono 应用中的请求和响应流,并快速识别任何问题或性能瓶颈。
🌐 By using the Logger Middleware, you can easily monitor the flow of requests and responses in your Hono application and quickly identify any issues or performance bottlenecks.
你还可以通过提供你自己的 PrintFunc 函数来进一步扩展中间件,以实现定制的日志记录行为。
🌐 You can also extend the middleware further by providing your own PrintFunc function for tailored logging behavior.
TIP
要禁用_status code coloring_,你可以设置一个 NO_COLOR 环境变量。这是在日志库中禁用 ANSI 颜色转义代码的常用方法,并在 https://no-color.org/ 中有所描述。请注意,Cloudflare Workers 没有 process.env 对象,因此将默认为纯文本日志输出。:::
PrintFunc
Logger 中间件接受一个可选的 PrintFunc 函数作为参数。该函数允许你自定义日志记录器并添加额外的日志。
🌐 The Logger Middleware accepts an optional PrintFunc function as a parameter. This function allows you to customize the logger and add additional logs.
选项
🌐 Options
optional 函数: PrintFunc(str: string, ...rest: string[])
str:由日志器传递。...rest:要打印到控制台的其他字符串属性。
示例
🌐 Example
为 Logger 中间件设置自定义 PrintFunc 函数:
🌐 Setting up a custom PrintFunc function to the Logger Middleware:
ts
export const customLogger = (message: string, ...rest: string[]) => {
console.log(message, ...rest)
}
app.use(logger(customLogger))在路由中设置自定义日志器:
🌐 Setting up the custom logger in a route:
ts
app.post('/blog', (c) => {
// Routing logic
customLogger('Blog saved:', `Path: ${blog.url},`, `ID: ${blog.id}`)
// Output
// <-- POST /blog
// Blog saved: Path: /blog/example, ID: 1
// --> POST /blog 201 93ms
// Return Context
})