Grails filters for logging and monitoring
Grails filters let you run reusable Groovy code around an HTTP request, before a controller action and again as the response completes. That makes them a natural home for cross-cutting operational work such as assigning a request identifier, timing an endpoint, recording failures, and attaching user context to log events. Instead of scattering the same code through controllers, one filter can apply the policy consistently across the application.
The need is sharper in Australia. A booking platform may serve customers in Sydney and Melbourne while its developers sit in Brisbane, and a sudden rise in 5xx responses can reach an on-call engineer before anyone checks a dashboard. Filters can preserve that local context without turning every controller into an operations system. They also help teams using REST APIs distinguish one request from the next during a busy trading period or a deploy.
Filters become useful when their output fits a broader operational workflow: Grails should emit consistent, low-noise signals that work with the log aggregator, metrics backend, cloud platform, and incident process already used by the team. The goal is not to create a second monitoring platform inside Grails, but to provide reliable context for the tools that already exist.
Put filters at the request boundary
A controller should describe business behaviour, while a filter describes what should happen around every matching request. Grails filters can match by URI, controller, model, content type, or other criteria, so one class can cover selected endpoints rather than the whole application. The filter DSL is Groovy-based and therefore familiar to Java developers, while still allowing ordinary helper classes and tested services to do the heavier lifting.
Their lifecycle offers useful hooks. A before block can create context, a response header can make a request identifier visible to callers, and an after block can inspect the final status and elapsed time. The important distinction is that a filter sees transport and framework concerns; it does not know why an order was rejected or whether a background job later failed. Keep those domain facts in services or domain events.
A filter is therefore ideal for request-level logging and monitoring, but not a universal event bus. It can record that /orders/123 returned 500 in 842 milliseconds. A separate service event can explain that a database constraint was violated. Joining those records through the same request ID produces a useful trail without forcing unrelated concerns into one giant interceptor.
Build a structured request logging filter
Start with a small set of stable fields. The following filter generates a UUID, places it in the logging context, adds a response header, and logs one completion event. Package placement and servlet imports vary between Grails releases, so test the filter in the version used by your project rather than assuming every namespace is identical.
package filters
import org.slf4j.MDC
import java.util.UUID
class RequestLoggingFilters {
def filters = {
uri(config: '/**') {
before = {
def requestId = UUID.randomUUID().toString()
MDC.put('requestId', requestId)
MDC.put('service', 'billing-api')
MDC.put('startedAt', System.currentTimeMillis().toString())
response.setHeader('X-Request-ID', requestId)
}
after = {
def elapsed = System.currentTimeMillis() -
Long.valueOf(MDC.get('startedAt'))
log.info(
'request_completed method={} path={} status={} duration_ms={}',
request.method,
request.requestURI,
response.status,
elapsed
)
MDC.remove('startedAt')
MDC.remove('service')
MDC.remove('requestId')
}
}
}
}
MDC means Mapped Diagnostic Context, and Logback can include its values in every line written while handling the request. That avoids repeating the request ID in each log call. The generated value also gives support staff something concrete to quote: when someone in Adelaide reports “the checkout failed”, the team can search one unique identifier instead of guessing from timestamps and customer descriptions.
Use a finally-capable cleanup path so the thread-local context cannot leak into a later request, especially after an exception. Some Grails filter lifecycle combinations do not guarantee that every after hook runs on failure, so verify this behaviour in a test and use an error hook or servlet-level wrapper where needed. Remove named MDC entries rather than clearing unrelated values owned by another component.
Emit logs that machines can query
Human-friendly console output is rarely enough once requests arrive from several instances. Emit one structured event with a UTC timestamp, service name, environment, event name, request ID, method, normalised route, status, and duration. JSON or another consistent encoding lets the log platform group by fields instead of relying on brittle regular expressions. Keep the event name stable, such as http_request_completed, and record optional values only when present.
Normalisation matters. A raw path containing an order number should not become a metrics label or dashboard dimension because every value creates another time series. Log the identifier separately when it is safe and useful, but label the route as /orders/{id}. Apply the same rule to query parameters, user IDs, and exception messages: they can be sensitive, and arbitrary values are expensive to index.
Do not log request bodies, authorisation headers, cookies, access tokens, or full card details by default. Debug logging is still production data, particularly in a cloud environment where stdout is retained and broadly accessible. In a container deployment, write JSON to standard output and let the platform collect it; local file appenders can work for development but often create misleading gaps between instances.
Measure latency errors and traffic
Turn the filter into a measurement source as well as a logging source. Record a timer for matching requests and increment counters for traffic and server errors. In Micrometer, bind tags such as method, normalised route, status family, and environment, but not raw URL, exception text, or user identifier. High-cardinality labels can overwhelm a metrics backend and make the dashboard slower than the application.
Separate useful signals from noise. A 404 caused by a bot can be counted without paging anyone, while a rising proportion of 503 responses from the orders route deserves attention. Track latency distributions rather than averages, because a fast average can conceal a slow tail. Percentiles over recent windows show whether a change affects only a small segment or most users.
Give health checks and static assets separate treatment. A liveness endpoint should stay quiet and fast, while readiness checks may need useful failure reasons elsewhere. Static images should not distort API latency, yet requests to a missing critical JavaScript bundle may be operationally significant. Define matching rules from service objectives rather than from a blanket preference for less logging.
Protect sensitive data in operational records
Operational logs can contain personal information even when the application does not store it in the database. The Australian Privacy Act 1988 and the Australian Privacy Principles provide a useful compliance baseline for organisations covered by them, while health, financial, employment, and state-based records may attract additional obligations. Treat request logs as governed data when they include identifiers, IP addresses, search terms, or support details.
Minimise at collection time. Hash or pseudonymise user identifiers, redact known secret fields before serialisation, and restrict access to log indexes. Apply a documented retention period rather than keeping operational records indefinitely. Australian buyers commonly expect hosting region, retention, and incident-access terms to be stated plainly in vendor agreements, so log handling should match those commercial commitments.
Store timestamps in UTC and render them in Australian local time when people need them. Sydney, Melbourne, Adelaide, and Perth observe different offsets, while daylight-saving changes can create repeated or missing local hours on transition nights. A dashboard that labels “AEST” during daylight saving is operationally misleading; use Australia/Sydney or Australia/Perth for display and retain the original UTC instant.
Control scope order and duplicate signals
Broad filters are easy to start and difficult to maintain. Scope a request filter to /api/** when it serves only an API, and exclude assets, favicons, and health probes when they would add no value. Keep exclusions visible in configuration and review them as routes change. A filter that logs every static file can bury a genuine error under thousands of routine events.
Teams working with versioned REST endpoints should decide deliberately whether both /v1 and /v2 participate in the same metric. Useful dimensions are the logical route and API version, not a full path such as /v2/customers/928. During a migration, a separate counter for each version can show which clients still rely on the old contract.
Ordering is just as important. Give the context filter an early position, and let components that need its MDC declare that dependency. Security filters determine whether a user identity is safe to log. Use the Grails dependsOn mechanism to make ordering explicit and avoid dependency cycles. Finally, account for signals already emitted by an ingress or API gateway so one request does not become three near-identical error alerts.
Turn signals into action and ownership
Logs explain individual events, while metrics show patterns across the estate. Put the request ID in logs, use a trace ID when distributed tracing is available, and link the two in the dashboard. Visual cues work similarly to those in saturated spice markets, where distinct colours let people scan a busy display quickly, but operational dashboards need stable labels and legends rather than decoration for its own sake.
Build alerts around user impact and agreed thresholds, not every warning emitted by a library. A sustained rise in checkout latency, a payment endpoint returning 5xx responses, or a queue backing up beyond its recovery window is actionable. A small Australian operations team cannot triage a firehose of alerts, so route severity clearly and group related events. Staff in Perth may describe a partial outage as “all crook”, but the runbook should translate that everyday report into precise service signals rather than expect the same technical vocabulary.
Start on a branch today: add one request filter, choose a small JSON event schema, send it to the existing log platform, and publish latency and error metrics. Exercise it with a success, a rejected request, and an exception, then verify the request ID appears in all three records. Give the runbook a named owner, define retention, and rehearse the dashboard with a colleague from another Australian office. Once that path is dependable, extend it rather than adding noisy instrumentation by reflex.