Skip to content

Commit 32f17a2

Browse files
committed
feat: improve HTTP request logging functionality and customization
- Convert comments to block comments for consistency and readability. - Add a new function type `EventFn` for modifying or enhancing the logger event within a Gin HTTP request. - Add descriptions for struct fields and methods using block comments in `logger.go`. - Add additional `Option` functions to customize middleware behavior in `options.go`, such as `WithLogger`, `WithSkipPathRegexps`, `WithUTC`, `WithSkipPath`, `WithPathLevel`, `WithWriter`, `WithDefaultLevel`, `WithClientErrorLevel`, `WithServerErrorLevel`, `WithSkipper`, `WithContext`, and `WithMessage`. Signed-off-by: appleboy <appleboy.tw@gmail.com>
1 parent 37aaf5d commit 32f17a2

File tree

2 files changed

+274
-146
lines changed

2 files changed

+274
-146
lines changed

logger.go

Lines changed: 106 additions & 63 deletions
Original file line numberDiff line numberDiff line change
@@ -12,77 +12,116 @@ import (
1212
"github.com/rs/zerolog"
1313
)
1414

15-
// Fn is a function type that takes a gin.Context and a zerolog.Logger as parameters,
16-
// and returns a zerolog.Logger. It is typically used to modify or enhance the logger
17-
// within the context of a Gin HTTP request.
15+
/*
16+
Fn is a function type that takes a gin.Context and a zerolog.Logger as parameters,
17+
and returns a zerolog.Logger. It is typically used to modify or enhance the logger
18+
within the context of a Gin HTTP request.
19+
*/
1820
type Fn func(*gin.Context, zerolog.Logger) zerolog.Logger
1921

22+
/*
23+
EventFn is a function type that takes a gin.Context and a zerolog.Event as parameters,
24+
and returns a zerolog.Event. It is typically used to modify or enhance the event
25+
within the context of a Gin HTTP request.
26+
*/
2027
type EventFn func(*gin.Context, *zerolog.Event) *zerolog.Event
2128

22-
// Skipper defines a function to skip middleware. It takes a gin.Context as input
23-
// and returns a boolean indicating whether to skip the middleware for the given context.
29+
/*
30+
Skipper defines a function to skip middleware. It takes a gin.Context as input
31+
and returns a boolean indicating whether to skip the middleware for the given context.
32+
*/
2433
type Skipper func(c *gin.Context) bool
2534

26-
// config holds the configuration for the logger middleware.
35+
/*
36+
config holds the configuration for the logger middleware.
37+
*/
2738
type config struct {
28-
// logger is a function that defines the logging behavior.
39+
/*
40+
logger is a function that defines the logging behavior.
41+
*/
2942
logger Fn
30-
// context is a function that defines the logging behavior of gin.Context data
43+
/*
44+
context is a function that defines the logging behavior of gin.Context data
45+
*/
3146
context EventFn
32-
// utc is a boolean stating whether to use UTC time zone or local.
47+
/*
48+
utc is a boolean stating whether to use UTC time zone or local.
49+
*/
3350
utc bool
34-
// skipPath is a list of paths to be skipped from logging.
51+
/*
52+
skipPath is a list of paths to be skipped from logging.
53+
*/
3554
skipPath []string
36-
// skipPathRegexps is a list of regular expressions to match paths to be skipped from logging.
55+
/*
56+
skipPathRegexps is a list of regular expressions to match paths to be skipped from logging.
57+
*/
3758
skipPathRegexps []*regexp.Regexp
38-
// skip is a Skipper that indicates which logs should not be written. Optional.
59+
/*
60+
skip is a Skipper that indicates which logs should not be written. Optional.
61+
*/
3962
skip Skipper
40-
// output is a writer where logs are written. Optional. Default value is gin.DefaultWriter.
63+
/*
64+
output is a writer where logs are written. Optional. Default value is gin.DefaultWriter.
65+
*/
4166
output io.Writer
42-
// defaultLevel is the log level used for requests with status code < 400.
67+
/*
68+
defaultLevel is the log level used for requests with status code < 400.
69+
*/
4370
defaultLevel zerolog.Level
44-
// clientErrorLevel is the log level used for requests with status code between 400 and 499.
71+
/*
72+
clientErrorLevel is the log level used for requests with status code between 400 and 499.
73+
*/
4574
clientErrorLevel zerolog.Level
46-
// serverErrorLevel is the log level used for requests with status code >= 500.
75+
/*
76+
serverErrorLevel is the log level used for requests with status code >= 500.
77+
*/
4778
serverErrorLevel zerolog.Level
48-
// pathLevels is a map of specific paths to log levels for requests with status code < 400.
79+
/*
80+
pathLevels is a map of specific paths to log levels for requests with status code < 400.
81+
*/
4982
pathLevels map[string]zerolog.Level
50-
// message is a custom string that sets a log-message when http-request has finished
83+
/*
84+
message is a custom string that sets a log-message when http-request has finished
85+
*/
5186
message string
52-
// specificLevelByStatusCode is a map of specific status codes to log levels every request
87+
/*
88+
specificLevelByStatusCode is a map of specific status codes to log levels every request
89+
*/
5390
specificLevelByStatusCode map[int]zerolog.Level
5491
}
5592

5693
const loggerKey = "_gin-contrib/logger_"
5794

5895
var isTerm = isatty.IsTerminal(os.Stdout.Fd())
5996

60-
// SetLogger returns a gin.HandlerFunc (middleware) that logs requests using zerolog.
61-
// It accepts a variadic number of Option functions to customize the logger's behavior.
62-
//
63-
// The logger configuration includes:
64-
// - defaultLevel: the default logging level (default: zerolog.InfoLevel).
65-
// - clientErrorLevel: the logging level for client errors (default: zerolog.WarnLevel).
66-
// - serverErrorLevel: the logging level for server errors (default: zerolog.ErrorLevel).
67-
// - output: the output writer for the logger (default: gin.DefaultWriter).
68-
// - skipPath: a list of paths to skip logging.
69-
// - skipPathRegexps: a list of regular expressions to skip logging for matching paths.
70-
// - logger: a custom logger function to use instead of the default logger.
71-
//
72-
// The middleware logs the following request details:
73-
// - method: the HTTP method of the request.
74-
// - path: the URL path of the request.
75-
// - ip: the client's IP address.
76-
// - user_agent: the User-Agent header of the request.
77-
// - status: the HTTP status code of the response.
78-
// - latency: the time taken to process the request.
79-
// - body_size: the size of the response body.
80-
//
81-
// The logging level for each request is determined based on the response status code:
82-
// - clientErrorLevel for 4xx status codes.
83-
// - serverErrorLevel for 5xx status codes.
84-
// - defaultLevel for other status codes.
85-
// - Custom levels can be set for specific paths using the pathLevels configuration.
97+
/*
98+
SetLogger returns a gin.HandlerFunc (middleware) that logs requests using zerolog.
99+
It accepts a variadic number of Option functions to customize the logger's behavior.
100+
101+
The logger configuration includes:
102+
- defaultLevel: the default logging level (default: zerolog.InfoLevel).
103+
- clientErrorLevel: the logging level for client errors (default: zerolog.WarnLevel).
104+
- serverErrorLevel: the logging level for server errors (default: zerolog.ErrorLevel).
105+
- output: the output writer for the logger (default: gin.DefaultWriter).
106+
- skipPath: a list of paths to skip logging.
107+
- skipPathRegexps: a list of regular expressions to skip logging for matching paths.
108+
- logger: a custom logger function to use instead of the default logger.
109+
110+
The middleware logs the following request details:
111+
- method: the HTTP method of the request.
112+
- path: the URL path of the request.
113+
- ip: the client's IP address.
114+
- user_agent: the User-Agent header of the request.
115+
- status: the HTTP status code of the response.
116+
- latency: the time taken to process the request.
117+
- body_size: the size of the response body.
118+
119+
The logging level for each request is determined based on the response status code:
120+
- clientErrorLevel for 4xx status codes.
121+
- serverErrorLevel for 5xx status codes.
122+
- defaultLevel for other status codes.
123+
- Custom levels can be set for specific paths using the pathLevels configuration.
124+
*/
86125
func SetLogger(opts ...Option) gin.HandlerFunc {
87126
cfg := &config{
88127
defaultLevel: zerolog.InfoLevel,
@@ -167,13 +206,15 @@ func SetLogger(opts ...Option) gin.HandlerFunc {
167206
}
168207
}
169208

170-
// ParseLevel parses a string representation of a log level and returns the corresponding zerolog.Level.
171-
// It takes a single argument:
172-
// - levelStr: a string representing the log level (e.g., "debug", "info", "warn", "error").
173-
//
174-
// It returns:
175-
// - zerolog.Level: the parsed log level.
176-
// - error: an error if the log level string is invalid.
209+
/*
210+
ParseLevel parses a string representation of a log level and returns the corresponding zerolog.Level.
211+
It takes a single argument:
212+
- levelStr: a string representing the log level (e.g., "debug", "info", "warn", "error").
213+
214+
It returns:
215+
- zerolog.Level: the parsed log level.
216+
- error: an error if the log level string is invalid.
217+
*/
177218
func ParseLevel(levelStr string) (zerolog.Level, error) {
178219
return zerolog.ParseLevel(levelStr)
179220
}
@@ -208,17 +249,19 @@ func getLogEvent(rl zerolog.Logger, cfg *config, c *gin.Context, path string) *z
208249
}
209250
}
210251

211-
// GetLogger retrieves the zerolog.Logger instance from the given gin.Context.
212-
// It assumes that the logger has been previously set in the context with the key loggerKey.
213-
// If the logger is not found, it will panic.
214-
//
215-
// Parameters:
216-
//
217-
// c - the gin.Context from which to retrieve the logger.
218-
//
219-
// Returns:
220-
//
221-
// zerolog.Logger - the logger instance stored in the context.
252+
/*
253+
GetLogger retrieves the zerolog.Logger instance from the given gin.Context.
254+
It assumes that the logger has been previously set in the context with the key loggerKey.
255+
If the logger is not found, it will panic.
256+
257+
Parameters:
258+
259+
c - the gin.Context from which to retrieve the logger.
260+
261+
Returns:
262+
263+
zerolog.Logger - the logger instance stored in the context.
264+
*/
222265
func Get(c *gin.Context) zerolog.Logger {
223266
return c.MustGet(loggerKey).(zerolog.Logger)
224267
}

0 commit comments

Comments
 (0)