AccessLog Middleware for Iris

AccessLog Middleware for Iris

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"
)        

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")
}        

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)        

Log Format

The default log format is:

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

You can customize the log format using different formatters:

JSON Formatter

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

CSV Formatter

ac.SetFormatter(&accesslog.CSV{})        

Custom Template Formatter

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

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)
    }
})        

Asynchronous Logging

Enable asynchronous logging to improve performance:

ac.Async = true        

Conditional Logging

You can skip logging for specific routes or conditions:

app.UseRouter(accesslog.SkipHandler)        

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")))        

Custom Clock

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

ac.Clock = accesslog.TClock(time.Now())        

Middleware Integration

Integrate the accesslog middleware with other middlewares:

app.UseRouter(ac.Handler)
app.UseRouter(otherMiddleware)        

Examples

Log Requests to a JSON File

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

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.

To view or add a comment, sign in

More articles by Gerasimos Maropoulos

  • RFC: HTTP Wire Errors

    Overview This RFC proposes a standardized approach for handling and representing HTTP wire errors in a consistent and…

  • HTTP Method Override for Iris

    Introduction HTTP method override is a technique used to support clients that do not support certain HTTP methods such…

  • Request Body Limit Middleware for Iris

    Overview The Iris Body Limit middleware is a powerful tool for controlling the size of incoming request bodies in your…

  • Basic Authentication Middleware for Iris

    Overview The Basic Authentication middleware provides a robust and flexible way to secure your Iris web applications…

  • Request Rate Limiting Middleware for Iris

    Overview The middleware provides rate limiting capabilities for the Iris web framework. It allows developers to control…

  • How to use hCAPTCHA with Iris

    In this article, we will learn how to use hCAPTCHA with Iris, a web framework for Go that provides fast and easy…

  • How to use JWT authentication with Iris

    In this tutorial, we will learn how to use JWT (JSON Web Token) authentication with Iris, a fast and simple web…

  • Rewrite: A Simple and Powerful URL Rewriter for Go

    Rewrite is a Go package that lets you rewrite URL paths, subdomains or hosts based on regular expressions. It is…

  • How to use Iris and Basic authentication

    Iris is a fast, simple yet fully featured and very efficient web framework for Go. It provides a beautifully expressive…

  • How to Use Iris and PostgreSQL for Web Development

    A guide to using PG middleware, a package for Iris that provides easy and type-safe access to PostgreSQL database. Iris…

Insights from the community

Others also viewed

Explore topics