DEV Community

Cover image for AccessLog Middleware for Iris
Gerasimos (Makis) Maropoulos
Gerasimos (Makis) Maropoulos

Posted on

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"
)
Enter fullscreen mode Exit fullscreen mode

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")
}
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

Log Format

The default log format is:

Time|Latency|Code|Method|Path|IP|Path Params Query Fields|Bytes Received|Bytes Sent|Request|Response|
Enter fullscreen mode Exit fullscreen mode

You can customize the log format using different formatters:

JSON Formatter

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

CSV Formatter

ac.SetFormatter(&accesslog.CSV{})
Enter fullscreen mode Exit fullscreen mode

Custom Template Formatter

ac.SetFormatter(&accesslog.Template{Text: "{{.Code}}"})
Enter fullscreen mode Exit fullscreen mode

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)
    }
})
Enter fullscreen mode Exit fullscreen mode

Asynchronous Logging

Enable asynchronous logging to improve performance:

ac.Async = true
Enter fullscreen mode Exit fullscreen mode

Conditional Logging

You can skip logging for specific routes or conditions:

app.UseRouter(accesslog.SkipHandler)
Enter fullscreen mode Exit fullscreen mode

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")))
Enter fullscreen mode Exit fullscreen mode

Custom Clock

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

ac.Clock = accesslog.TClock(time.Now())
Enter fullscreen mode Exit fullscreen mode

Middleware Integration

Integrate the accesslog middleware with other middlewares:

app.UseRouter(ac.Handler)
app.UseRouter(otherMiddleware)
Enter fullscreen mode Exit fullscreen mode

Examples

Log Requests to a JSON File

ac := accesslog.File("access_log.json")
ac.SetFormatter(&accesslog.JSON{
    Indent:    "  ",
    HumanTime: true,
})
app.UseRouter(ac.Handler)
Enter fullscreen mode Exit fullscreen mode

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.

Top comments (0)