FLAT
CouperSevenval TechnologiesDocker ImageGithub
master
master
  • Changelog
  • FLAT
  • Administration
    • Configuration
    • Docker
    • Logging
  • Cookbook
    • Using the Built-in Mocking
    • Performing Additional Checks on JWT Access Tokens
    • Logging Custom Fields
    • Using Environment Variables
    • Handling Errors with an Error Flow
    • File Serving
    • Forwarding a Request to an Upstream API
    • Extracting Common Initialization Flow Tasks
    • Encoding and Decoding JWT
    • Passing Header Fields to the Client
    • How can I pass an arbitrary header field to an upstream system?
    • Performing Additional Checks on JWT Access Tokens
    • Proxying requests to Upstream APIs
    • Increasing the Request Timeout
    • How can I see what the client requested?
    • Using Swagger UI for API Documentation
    • Testing API Requests
    • Testing with Backend Requests
    • Testing Templates
    • Sending POST Requests
    • Processing Upstream Responses
    • Protecting Access using JWT Tokens
  • Reference
    • Configuration
    • Debugging
    • flat CLI
    • Flow
    • Variables
    • OpenAPI / Swagger Integration
    • OpenAPI
      • CORS - Cross-Origin Resource Sharing
    • OpenAPI
      • Differences from Swagger
    • OpenAPI
      • Mocking
    • OpenAPI
      • Routing
    • OpenAPI
      • Security
    • OpenAPI
      • Upstream APIs
    • OpenAPI
      • Validation
    • Flow Actions
      • assert Action
      • auth Action
      • backend-flow Action
      • copy Action
      • debug Action
      • dump Action
      • echo Action
      • error Action
      • eval Action
      • log Action
      • nameshave Action
      • pass-body Action
      • proxy-request Action
      • regex Action
      • request Action
      • requests Action
      • serve Action
      • set-config Action
      • set-env Action
      • set-response-headers Action
      • set-status Action
      • sub-flow Action
      • template Action
      • test-request Action
      • xslt Action
    • Functions
      • apply-codecs()
      • array-reverse()
      • array()
      • base64-decode()
      • base64-encode()
      • body()
      • calc-signature()
      • capitalize-first()
      • content()
      • decrypt-xml()
      • decrypt()
      • encrypt()
      • ends-with()
      • file-exists()
      • fit-document()
      • fit-log()
      • fit-serialize()
      • get-log()
      • has-class()
      • html-parse()
      • join()
      • json-doc()
      • json-parse()
      • json-stringify()
      • json-to-csv()
      • json-to-xml()
      • jwt-decode()
      • jwt-encode()
      • ldap-lookup()
      • ldap-query()
      • lookup()
      • matches()
      • md5()
      • replace()
      • sort()
      • split()
      • tolower()
      • toupper()
      • trim()
      • unixtime()
      • urldecode(), url-decode()
      • urlencode(), url-encode()
      • uuid3() and uuid4()
      • verify-signature()
      • verify-xmldsig()
      • xml-parse()
      • xml-to-json()
    • Templating
      • {{,}}
      • Comment {{// …}}
      • Dot {{.}}
      • Conditional `{{if <condition>}} … {{elseif <condition> }} … {{else}} … {{end}}
      • loop
      • ?? Operator
      • Object XML Notation (OXN)
      • Pair Producer {{: …}}
      • Placeholder
      • Template Variables
      • with
    • Testing
  • Tutorial
Powered by GitBook
On this page
  • Reading Logs
  • Adding a Log Field
  • Adding Dynamic Log Fields
  • Structured Log Fields
  • Using Request Data
  • Testing
  • See also

Was this helpful?

  1. Cookbook

Logging Custom Fields

PreviousPerforming Additional Checks on JWT Access TokensNextUsing Environment Variables

Last updated 4 years ago

Was this helpful?

FLAT writes for events like client access or upstream requests. The structured log events are easily extensible.

The already provides a basic set of information about the incoming request. However, when inspecting (any) logs quickly the wish for more contextual information will arise.

Here are some ideas for fields to augment your logs with:

  • A random "Tab" ID sent by the client to correlate API requests to a single SPA instance

  • The version or git revision of your FLAT project

  • A message to distinguish reasons for errors

  • The staging role (dev/test/prod) or data center identifier passed in by

  • The client's real IP address as advertised by a downstream system (e.g. your load balancer)

  • User and Role from a

  • …

We want all of that!

To play with logging, you need a FLAT project. If you don't have on, yet, have a look into the to .

Reading Logs

Before start customizing our logs, we need to setup our workplace in order to see what we are doing. Where can we inspect FLAT logs?

FLAT runs in and writes its log lines to stdout and stderr. (If you don't know the two, don't fear.) In a development setup, we usually start FLAT with the . If you run

$ flat start
…

However, once you call your API with curl you will see JSON lines in your terminal:

$ curl localhost:8080/api/…
{"timestamp":"2019-10-15T15:49:13+00:00","type":"flat_access",…}
$ flat start | jq -R -r '. as $line | try fromjson catch $line'

Now, the access log will be nicely readable on your terminal:

…
{
  "timestamp": "2019-10-15T15:49:13+00:00",
  "type": "flat_access",
  "requestID": "XaXqeccky00IowY@OUgG8AAAAAA",
  "url": "http://localhost:8080/api/…",
  "path": "/api/…",
  "status": 200,
  "method": "GET",
  "agent": "curl/7.54.0",
  "referrer": "",
  "mime": "application/json",
  "realtime": 0.08935,
  "bytes": 1387,
  "requestbytes": 0,
  "flow": "flow.xml",
  "requestmime": "",
  "location": ""
}

Adding a Log Field

Now that we know where our logs go, we're finally ready to add fields!

We will start with a simple task: Let's add a field to our log that contains a fixed string.

This can actually be useful: if you share a log server with other FLAT projects, the field let's you identify the originating project. (In production, your log shipper will probably provide this information already in its log envelope.)

<log>
{
  "project": "myAPIProject"
}
</log>

Call your FLAT API again and watch the logs:

$ curl localhost:8080/api/…
{
  "timestamp": "2019-10-15T15:49:13+00:00",
  "type": "flat_access",
  …
  "project": "myAPIProject"
}

Our first custom log field has hit the terminal!

Adding Dynamic Log Fields

To include this information into the log, we add more fields to our log action:

<log>
{
  "project": "myAPIProject",
  "stage": {{ $env/FLAT_STAGE ?? "unknown" }},
  "location": {{ $env/FLAT_DC }}
}
</log>

Notice, how we can provide default values for missing data. If both of the variables are not set, a log may look like this:

{
  "timestamp": "2019-10-15T15:49:13+00:00",
  "type": "flat_access",
  …
  "project": "myAPIProject",
  "stage": "unknown"
}

stage is always defined. But location is missing, because its expression has evaluated to null. Nulled fields don't show up in the log.

Structured Log Fields

Your custom log fields are not restricted to the top-level field-list. If you have more fields, that belong together, you can group them in an object.

In our case, we might want to gather information about the environment:

<log>
{
  "project": "myAPIProject",
  "env": {
    "stage": {{ $env/FLAT_STAGE ?? "unknown" }},
    "location": {{ $env/FLAT_DC }}
  }
}
</log>
{
  "timestamp": "2019-10-15T15:49:13+00:00",
  "type": "flat_access",
  …
  "project": "myAPIProject",
  "env": {
    "stage": "production",
    "location": "CGN"
  }
}

Using Request Data

Clients provide a lot of useful information in the HTTP request headers. We can easily use them to augment our log:

<log>
{
  "project": "myAPIProject",
  "env": {
    "stage": {{ $env/FLAT_STAGE ?? "unknown" }},
    "location": {{ $env/FLAT_DC }}
  },
  "request": {
    {{: $request/headers/x-real-ip | $request/headers/x-forwarded-proto }}
  }
}
</log>
$ curl -H "X-Forwarded-Proto: https" localhost:8080/api/…
{
  "timestamp": "2019-10-15T15:49:13+00:00",
  "type": "flat_access",
  …
  "project": "myAPIProject",
  "env": {
    "stage": "production",
    "location": "CGN"
  },
  "request": {
    "x-forwarded-proto": "https"
  }
}

Every API has to rely on user input for its operation. But we should do so with care. (Every client could sent a X-Forwarded-Proto header. The administrator should take measures to override this header in the SSL offloader.)

Testing

Put this into tests/loggging.xml:

<flat-test>
  <eval out="$user">"alice"</eval>
  <log>
  {
    "user": {
      "name": {{ $user }}
    }
  }
  </log>
  <assert>
  [
    [ "get-log()/user/name", "alice", "user/name was logged" ]
  ]
  </assert>
</flat-test>

You can run the test with this command:

$ flat test tests/logging.xml
1..1
ok 1 tests/logging.xml: 1 assertions

In a real project, you would rather send a request to your FLAT API and check if the log was written as expected:

<flat-test>
  <!-- fake env vars -->
  <set-env>
  {
    "FLAT_STAGE": "test",
    "FLAT_DC": "myLaptop"
  }
  </set-env>

  <test-request>
  {
    "path": "/api/path",
    "headers": {
      "X-Forwarded-Proto": "https"
    }
  }
  </test-request>

  <eval out="$log">get-log()</eval>
  <assert>
  [
    [ "$log/env/stage", "test", "FLAT_STAGE was logged" ],
    [ "$log/env/location", "myLaptop", "FLAT_DC was logged" ],
    [ "$log/request/x-forwarded-proto", "https", "XFP was logged" ]
  ]
  </assert>
</flat-test>

See also

you will see the log output in your terminal. Some startup messages are plain text lines. The will be text, too.

You can have the JSON colored and pretty printed by piping the output to the :

Log fields can be registered with the . The action takes a as its argument. For our fixed field, we write:

A good place for this action is the because it is started for all API flows.

With you can use expressions to dynamically set field names and values.

Let's assume, you use the FLAT_STAGE to tell your project in which deployment stage it is running. Possible values could be dev, qa and prod. Another variable FLAT_DC holds the airport code of the data center, e.g. CGN or LON.

Here, we use the to create log fields from headers. If present, the headers will show up in the log:

For logging alone, the JSON armor prevents format breakouts and log attacks. HTTP request headers and query strings are limited in size. However, you could use to further validate a parameter's format.

Log augmentation with the belongs to our project code. Therefore, we would like to test that! This can be done by using the in a .

(Administration)

(Reference)

(Reference)

debug output
jq command
log action
JSON template
JSON templates
environment variable
pair producer {{:
Swagger
log action
get-log() function
FLAT test
Logging
log action
get-log() function
JSON logs
environment variables
JWT token
tutorial
Docker
flat cli
access log
init flow
get started