DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Stop Poisoning Your Models: How I Built a CV Dataset Quality Toolkit I Can Reuse Forever
  • Lambda-Driven API Design: Building Composable Node.js Endpoints With Functional Primitives
  • The Update Problem REST Doesn't Solve
  • Designing a Production-Grade Multi-Agent LLM Architecture for Structured Data Extraction

Trending

  • Designing Effective Meetings in Tech: From Time Wasters to Strategic Tools
  • Your API Authentication Isn’t Broken; It’s Quietly Failing in These 6 Ways
  • Edge Computing in Utility IoT: Two Architecture Patterns That Actually Work
  • 8 RAG Patterns You Should Stop Ignoring
  1. DZone
  2. Coding
  3. Frameworks
  4. Structured Logging in Grails 6.2.3

Structured Logging in Grails 6.2.3

Comparison of traditional logging with structured logging, its advantages, and enhancements in the latest version of Grails 6.2x.

By 
Karthik Kamarapu user avatar
Karthik Kamarapu
·
Jan. 30, 25 · Tutorial
Likes (1)
Comment
Save
Tweet
Share
3.5K Views

Join the DZone community and get the full member experience.

Join For Free

Traditionally, logging has been unstructured and relies on plain text messages to file. This approach is not suitable for large-scale distributed systems emitting tons of events, and parsing unstructured logs is cumbersome for extracting any meaningful insights.

Structured logging offers a solution to the above problem by capturing logs in a machine-readable format such as JSON, and it becomes easier to query and analyze log data in a system where logs are aggregated into centralized platforms like ELK (ElasticSearch, Logstash, Kibana). 

Traditional Logging in Grails

Before structured logging, Grails application used unstructured logs using methods like  log.info, log.debug and log. error. These logs lacked a consistent format and were difficult to integrate with log management systems, and required manual effort to correlate logs across different parts of the application.

For example, consider a simple controller method for listing books:

Groovy
 
class BookController {
    def list() {
        log.info("Fetching list of books")
        try {
            def books = Book.list()
            log.debug("Books retrieved: ${books}")
            render books as JSON
        } catch (Exception e) {
            log.error("Error fetching books: ${e.message}")
            render status: 500, text: "Internal Server Error"
        }
    }
}


In the above approach, logs are plain text, and analyzing logs for patterns or errors requires manual parsing or the use of complex tools. Additionally, important context information such as User IDs or timestamps often needed to be added explicitly.

Structured Logging in Grails

Grails 6.1x introduced structured logging capabilities and it was further enhanced in Grails 6.2x with default support for JSON-encoded logs that makes it easier to adopt the structured logging practices. The new approach allows developers to log information in a structured format, and there is no need to specify the metadata such as timestamps, log levels, and contextual data manually.

With structured logging, the same controller method can be written as follows:

Groovy
 
import org.slf4j.Logger
import org.slf4j.LoggerFactory

class BookController {
    private static final Logger log = LoggerFactory.getLogger(BookController.class)

    def list() {
        log.info("action=list_books", [userId: session.userId, timestamp: System.currentTimeMillis()])
        try {
            def books = Book.list()
            log.debug("action=books_retrieved", [count: books.size()])
            render books as JSON
        } catch (Exception e) {
            log.error("action=error_fetching_books", [message: e.message, timestamp: System.currentTimeMillis()])
            render status: 500, text: "Internal Server Error"
        }
    }
}


Here, logs are structured key-value pairs that are machine-readable and easy to analyze with log aggregation tools.

Simplified Configuration

With Grails 6.2.x, enabling structured logging is straightforward with the configuration options in application.yml and developers can define JSON-based logging patterns without a huge manual setup. The configuration looks like this:

YAML
 
logging:
  level:
    grails.app: DEBUG
  appenders:
    console:
      name: STDOUT
      target: SYSTEM_OUT
      encoder:
        pattern: '{"timestamp": "%d{yyyy-MM-dd HH:mm:ss}", "level": "%-5level", "logger": "%logger{36}", "message": "%msg", "thread": "%thread"}%n'


These logs output in a structured format that makes them suitable for integrating with tools like ElasticSearch or Splunk.

Comparison of Traditional and Structured Logging

A traditional log might look like this:

VB.NET
 
INFO: Fetching list of books
DEBUG: Books retrieved: [Book1, Book2, Book3]
ERROR: Error fetching books: NullPointerException


Similar logs in structured logging look like below:

JSON
 
{
  "timestamp": "2025-01-20 14:23:45",
  "level": "INFO",
  "logger": "BookController",
  "message": "action=list_books",
  "userId": "12345",
  "thread": "http-nio-8080-exec-3"
}


Conclusion

By transitioning from traditional logging to structured logging developers can make use of modern log analysis tools to their advantage. With Grails 6.1.x and 6.2.x, structured logging has become more accessible that developers can easily use in their applications.

JSON Log analysis Grails (framework)

Opinions expressed by DZone contributors are their own.

Related

  • Stop Poisoning Your Models: How I Built a CV Dataset Quality Toolkit I Can Reuse Forever
  • Lambda-Driven API Design: Building Composable Node.js Endpoints With Functional Primitives
  • The Update Problem REST Doesn't Solve
  • Designing a Production-Grade Multi-Agent LLM Architecture for Structured Data Extraction

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook