AccessLog Middleware for Iris

DDD
Release: 2024-11-01 05:50:27
Original
589 people have browsed it

AccessLog Middleware for Iris

The accesslog middleware for the Iris web framework provides detailed logging for incoming HTTP requests. This middleware is highly configurable and can log various aspects of the request and response, including custom fields.

Features

  • Logs request and response details.
  • Supports multiple output formats (JSON, CSV, custom templates).
  • Can log to multiple destinations (files, stdout, etc.).
  • Asynchronous logging support.
  • Customizable log fields.
  • Middleware can be conditionally applied.

Installation

To use the accesslog middleware, you need to import it in your Iris application:

import (
    "github.com/kataras/iris/v12"
    "github.com/kataras/iris/v12/middleware/accesslog"
)
Copy after login

Basic Usage

Here is a basic example of how to use the accesslog middleware in an Iris application:

package main

import (
    "github.com/kataras/iris/v12"
    "github.com/kataras/iris/v12/middleware/accesslog"
)

func makeAccessLog() *accesslog.AccessLog {
    ac := accesslog.File("./access.log")

    ac.Delim = '|'
    ac.TimeFormat = "2006-01-02 15:04:05"
    ac.Async = false
    ac.IP = true
    ac.BytesReceivedBody = true
    ac.BytesSentBody = true
    ac.BytesReceived = false
    ac.BytesSent = false
    ac.RequestBody = true
    ac.ResponseBody = false
    ac.KeepMultiLineError = true
    ac.PanicLog = accesslog.LogHandler

    ac.SetFormatter(&accesslog.JSON{
        Indent:    "  ",
        HumanTime: true,
    })

    return ac
}

func main() {
    ac := makeAccessLog()
    defer ac.Close()

    app := iris.New()
    app.UseRouter(ac.Handler)

    app.Get("/", func(ctx iris.Context) {
        ctx.WriteString("OK")
    })

    app.Listen(":8080")
}
Copy after login

Configuration Options

Output Destination

You can set the output destination for the logs using the File or New functions:

ac := accesslog.File("./access.log")
// or
ac := accesslog.New(os.Stdout)
Copy after login

Log Format

The default log format is:

Time|Latency|Code|Method|Path|IP|Path Params Query Fields|Bytes Received|Bytes Sent|Request|Response|
Copy after login

You can customize the log format using different formatters:

JSON Formatter

ac.SetFormatter(&accesslog.JSON{
    Indent:    "  ",
    HumanTime: true,
})
Copy after login

CSV Formatter

ac.SetFormatter(&accesslog.CSV{})
Copy after login

Custom Template Formatter

ac.SetFormatter(&accesslog.Template{Text: "{{.Code}}"})
Copy after login

Custom Fields

You can add custom fields to the log entries:

ac.AddFields(func(ctx iris.Context, f *accesslog.Fields) {
    for k, v := range ctx.Request().Header {
        value := strings.Join(v, ", ")
        f.Set("request.header."+k, value)
    }
})
Copy after login

Asynchronous Logging

Enable asynchronous logging to improve performance:

ac.Async = true
Copy after login

Conditional Logging

You can skip logging for specific routes or conditions:

app.UseRouter(accesslog.SkipHandler)
Copy after login

Advanced Usage

Logging to Multiple Destinations

You can log to multiple destinations using io.MultiWriter:

ac.SetOutput(io.MultiWriter(os.Stdout, accesslog.File("./access.log")))
Copy after login

Custom Clock

You can set a custom clock for the log timestamps, useful for testing:

ac.Clock = accesslog.TClock(time.Now())
Copy after login

Middleware Integration

Integrate the accesslog middleware with other middlewares:

app.UseRouter(ac.Handler)
app.UseRouter(otherMiddleware)
Copy after login

Examples

Log Requests to a JSON File

ac := accesslog.File("access_log.json")
ac.SetFormatter(&accesslog.JSON{
    Indent:    "  ",
    HumanTime: true,
})
app.UseRouter(ac.Handler)
Copy after login

Using Log Rotation

Refer to the log rotation example for more details.

Custom Fields and Template

Refer to the custom fields and template example for more details.

Listen and Render Logs to a Client

Refer to the log broker example for more details.

Conclusion

The accesslog middleware for Iris is a powerful tool for logging HTTP requests and responses. With its flexible configuration options and support for custom fields and formats, it can be tailored to meet the needs of any application.

For more examples and detailed usage, refer to the official Iris documentation.

The above is the detailed content of AccessLog Middleware for Iris. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!