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
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Related

  • Streamlining Event Data in Event-Driven Ansible
  • Apache Doris vs Elasticsearch: An In-Depth Comparative Analysis
  • Dynamic Web Forms In React For Enterprise Platforms
  • Unlocking Oracle 23 AI's JSON Relational Duality

Trending

  • Ensuring Configuration Consistency Across Global Data Centers
  • Next-Gen IoT Performance Depends on Advanced Power Management ICs
  • Unlocking the Benefits of a Private API in AWS API Gateway
  • Introduction to Retrieval Augmented Generation (RAG)
  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.1K 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

  • Streamlining Event Data in Event-Driven Ansible
  • Apache Doris vs Elasticsearch: An In-Depth Comparative Analysis
  • Dynamic Web Forms In React For Enterprise Platforms
  • Unlocking Oracle 23 AI's JSON Relational Duality

Partner Resources

×

Comments
Oops! Something Went Wrong

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

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

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 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!