Application File Recorder

func main() {
    app := iris.Default()
    // Record to a file
    // Automatically disable colors when writing to a file
    f, _ := os.Create("iris.log")
    app.Logger().SetOutput(f)

    // If you need to write logs to both a file and the console, use the following code
    // app.Logger().AddOutput(os.Stdout)
    
    app.Get("/ping", func(ctx iris.Context) {
        ctx.WriteString("pong")
    })

   app.Listen(":8080")
}

Control Log Output Color

By default, the log output on the console will be colorized based on the detected TTY.

Customize level titles, text, color, and style in regular cases.

Import golog and pio:

import (
    "github.com/kataras/golog"
    "github.com/kataras/pio"
    // [...]
)

Get a level to customize, such as DebugLevel:

level := golog.Levels[golog.DebugLevel]

You have complete control over the level's text, title, and style:

// Level name
// Lowercase named will be used
// to convert the string level to the correct level type
Name string
// AlternativeNames are the names that this specific log level could be referenced with
// such as Name = "warn"
// AlternativeNames = []string{"warning"}, this is an optional field,
// so we keep the Name as a simple string and create this new field.
AlternativeNames []string
// Title is the prefix of the log level.
// There are also `ColorCode` and `Style`.
// `ColorCode` and `Style` should be consistent between writers.
Title string
// ColorCode is the color for `Title`.
ColorCode int
// Style is one or more rich options for `Title`.
Style []pio.RichOption

Example code:

level := golog.Levels[golog.DebugLevel]
level.Name = "debug" // default
level.Title = "[DBUG]" // default
level.ColorCode = pio.Yellow // default

Change the output format:

app.Logger().SetFormat("json", "    ")

Register a custom formatter:

app.Logger().RegisterFormatter(new(myFormatter))

The golog.Formatter interface is as follows:

// Formatter is responsible to print a log to a writer of the logger.
type Formatter interface {
    // The name of the formatter.
    String() string
    // Set any options and return a cloned object, if common. See `Logger.SetFormat`.
    Options(opts ...interface{}) Formatter
    // Writes the "log" to "dest" logger.
    Format(dest io.Writer, log *Log) bool
}

Change output and format by level:

app.Logger().SetLevelOutput("error", os.Stderr)
app.Logger().SetLevelFormat("json")

Request Logging

The application logger we saw above is primarily used for logging information and errors related to the application. On the other hand, the access logger we see below is mainly used to log incoming HTTP requests and responses.

package main

import (
    "os"

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

// Read the example and its comments carefully.
func makeAccessLog() *accesslog.AccessLog {
    // Initialize a new access log middleware.
    ac := accesslog.File("./access.log")
    // Remove this line to disable logging to the console:
    ac.AddOutput(os.Stdout)

    // Default configuration:
    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.BodyMinify = true
    ac.RequestBody = true
    ac.ResponseBody = false
    ac.KeepMultiLineError = true
    ac.PanicLog = accesslog.LogHandler
    
    // Use default line format if the formatter is missing:
    // Time|Delay|Status|Method|Path|IP|Path Query Parameters|Received Bytes|Sent Bytes|Request|Response|
    //
    // Set a custom formatter:
    ac.SetFormatter(&accesslog.JSON{
        Indent:    "  ",
        HumanTime: true,
    })
    // ac.SetFormatter(&accesslog.CSV{})
    // ac.SetFormatter(&accesslog.Template{Text: "{{.Code}}"})
    
    return ac
}

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

    app := iris.New()
    // Register middleware (using UseRouter can also catch HTTP errors).
    app.UseRouter(ac.Handler)
    
    app.Get("/", indexHandler)
    
    app.Listen(":8080")
}

func indexHandler(ctx iris.Context) {
    ctx.WriteString("OK")
}

Read more examples here: _examples/logging/request-logger.