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 方法、请求路径和传入请求。
¥Incoming Request: Logs the HTTP method, request path, and incoming request.
传出响应:记录 HTTP 方法、请求路径、响应状态代码和请求/响应时间。
¥Outgoing Response: Logs the HTTP method, request path, response status code, and request/response times.
状态代码着色:响应状态代码采用颜色编码,以便更好地查看和快速识别状态类别。不同的状态代码类别由不同的颜色表示。
¥Status Code Coloring: Response status codes are color-coded for better visibility and quick identification of status categories. Different status code categories are represented by different colors.
已用时间:请求/响应周期所花费的时间以人性化的形式记录,以毫秒 (ms) 或秒 (s) 为单位。
¥Elapsed Time: The time taken for the request/response cycle is logged in a human-readable format, either in milliseconds (ms) or seconds (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.
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 fn:PrintFunc(str: string, ...rest: string[])
str
:由日志器传递。¥
str
: Passed by the logger....rest
:要打印到控制台的其他字符串属性。¥
...rest
: Additional string props to be printed to console.
示例
¥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
})