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
Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
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

Integrating PostgreSQL Databases with ANF: Join this workshop to learn how to create a PostgreSQL server using Instaclustr’s managed service

Mobile Database Essentials: Assess data needs, storage requirements, and more when leveraging databases for cloud and edge applications.

Monitoring and Observability for LLMs: Datadog and Google Cloud discuss how to achieve optimal AI model performance.

Automated Testing: The latest on architecture, TDD, and the benefits of AI and low-code tools.

Related

  • How To Get and Set PDF Form Fields in Java
  • How To Validate Archives and Identify Invalid Documents in Java
  • How To Check Office Files for Macros Using Java
  • How to Automatically Detect Multiple Cybersecurity Threats from an Input Text String in Java

Trending

  • What Is Good Database Design?
  • Designing Databases for Distributed Systems
  • How to Submit a Post to DZone
  • DZone's Article Submission Guidelines
  1. DZone
  2. Testing, Deployment, and Maintenance
  3. Monitoring and Observability
  4. Send Your Logs to Loki

Send Your Logs to Loki

This blog post explores logging in Loki. Options are virtually unlimited. Be careful to choose the one that fits your context the best.

Nicolas Fränkel user avatar by
Nicolas Fränkel
CORE ·
Aug. 31, 23 · Analysis
Like (8)
Save
Tweet
Share
5.71K Views

Join the DZone community and get the full member experience.

Join For Free

One of my current talks focuses on Observability in general and Distributed Tracing in particular, with an OpenTelemetry implementation. In the demo, I show how you can see the traces of a simple distributed system consisting of the Apache APISIX API Gateway, a Kotlin app with Spring Boot, a Python app with Flask, and a Rust app with Axum.

Earlier this year, I spoke and attended the Observability room at FOSDEM. One of the talks demoed the Grafana stack: Mimir for metrics, Tempo for traces, and Loki for logs. I was pleasantly surprised how one could move from one to the other. Thus, I wanted to achieve the same in my demo but via OpenTelemetry to avoid coupling to the Grafana stack.

In this blog post, I want to focus on logs and Loki.

Loki Basics and Our First Program

At its core, Loki is a log storage engine:

Loki is a horizontally scalable, highly available, multi-tenant log aggregation system inspired by Prometheus. It is designed to be very cost effective and easy to operate. It does not index the contents of the logs, but rather a set of labels for each log stream.

Loki

Loki provides a RESTful API to store and read logs. Let's push a log from a Java app. Loki expects the following payload structure:

payload structure

I'll use Java, but you can achieve the same result with a different stack. The most straightforward code is the following:

Java
 
public static void main(String[] args) throws URISyntaxException, IOException, InterruptedException {
    var template = "'{' \"streams\": ['{' \"stream\": '{' \"app\": \"{0}\" '}', \"values\": [[ \"{1}\", \"{2}\" ]]'}']'}'"; //1
    var now = LocalDateTime.now().atZone(ZoneId.systemDefault()).toInstant();
    var nowInEpochNanos = NANOSECONDS.convert(now.getEpochSecond(), SECONDS) + now.getNano();
    var payload = MessageFormat.format(template, "demo", String.valueOf(nowInEpochNanos), "Hello from Java App");           //1
    var request = HttpRequest.newBuilder()                                                                                  //2
            .uri(new URI("http://localhost:3100/loki/api/v1/push"))
            .header("Content-Type", "application/json")
            .POST(HttpRequest.BodyPublishers.ofString(payload))
            .build();
    HttpClient.newHttpClient().send(request, HttpResponse.BodyHandlers.ofString());                                         //3
}


  1. This is how we did String interpolation in the old days
  2. Create the request
  3. Send it

The prototype works, as seen in Grafana:

Grafana payload

However, the code has many limitations:

  • The label is hard-coded. You can and must send a single-label
  • Everything is hard-coded; nothing is configurable, e.g., the URL
  • The code sends one request for every log; it's hugely inefficient as there's no buffering
  • HTTP client is synchronous, thus blocking the thread while waiting for Loki
  • No error handling whatsoever
  • Loki offers both gzip compression and Protobuf; none are supported with my code
  • Finally, it's completely unrelated to how we use logs, e.g.:

    Java
     
    var logger = // Obtain logger
    logger.info("My message with parameters {}, {}", foo, bar);

Regular Logging on Steroids

To use the above statement, we need to choose a logging implementation. Because I'm more familiar with it, I'll use SLF4J and Logback. Don't worry; the same approach works for Log4J2.

We need to add relevant dependencies:

XML
 
<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-api</artifactId>             <!--1-->
    <version>2.0.7</version>
</dependency>
<dependency>
    <groupId>ch.qos.logback</groupId>
    <artifactId>logback-classic</artifactId>       <!--2-->
    <version>1.4.8</version>
    <scope>runtime</scope>
</dependency>
<dependency>
    <groupId>com.github.loki4j</groupId>
    <artifactId>loki-logback-appender</artifactId> <!--3-->
    <version>1.4.0</version>
    <scope>runtime</scope>
</dependency>


  1. SLF4J is the interface
  2. Logback is the implementation
  3. Logback appender dedicated to SLF4J

Now, we add a specific Loki appender:

XML
 
<appender name="LOKI" class="com.github.loki4j.logback.Loki4jAppender">                   <!--1-->
    <http>
        <url>http://localhost:3100/loki/api/v1/push</url>                                 <!--2-->
    </http>
    <format>
        <label>
            <pattern>app=demo,host=${HOSTNAME},level=%level</pattern>                     <!--3-->
        </label>
        <message>
            <pattern>l=%level h=${HOSTNAME} c=%logger{20} t=%thread | %msg %ex</pattern>  <!--4-->
        </message>
        <sortByTime>true</sortByTime>
    </format>
</appender>
<root level="DEBUG">
    <appender-ref ref="STDOUT" />
</root>


  1. The loki appender
  2. Loki URL
  3. As many labels as wanted
  4. Regular Logback pattern

Our program has become much more straightforward:

Java
 
var who = //...
var logger = LoggerFactory.getLogger(Main.class.toString());
logger.info("Hello from {}!", who);


Grafana displays the following:

Display in Grafana

Docker Logging

I'm running most of my demos on Docker Compose, so I'll mention the Docker logging trick. When a container writes on the standard out, Docker saves it to a local file. The docker logs  command can access the file content.

However, other options than saving to a local file are available, e.g., syslog, Google Cloud, Splunk, etc. To choose a different option, one sets a logging driver. One can configure the driver at the overall Docker level or per container.

Loki offers its own plugin. To install it:

Shell
 
docker plugin install grafana/loki-docker-driver:latest --alias loki --grant-all-permissions


At this point, we can use it on our container app:

YAML
 
services:
  app:
    build: .
    logging:
      driver: loki                                                    #1
      options:
        loki-url: http://localhost:3100/loki/api/v1/push              #2
        loki-external-labels: container_name={{.Name}},app=demo       #3


  1. Loki logging driver
  2. URL to push to
  3. Additional labels

The result is the following. Note the default labels.

Result

Conclusion

From a bird's eye view, Loki is nothing extraordinary: it's a plain storage engine with a RESTful API on top.

Several approaches are available to use the API. Beyond the naive one, we have seen a Java logging framework appender and Docker. Other approaches include scraping the log files, e.g., Promtail, via a Kubernetes sidecar. You could also add an OpenTelemetry Collector between your app and Loki to perform transformations.

Options are virtually unlimited. Be careful to choose the one that fits your context the best.

To go further:

  • Push log entries to Loki via API
  • Loki Clients
API Grafana Java (programming language) Loki (C++)

Published at DZone with permission of Nicolas Fränkel, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • How To Get and Set PDF Form Fields in Java
  • How To Validate Archives and Identify Invalid Documents in Java
  • How To Check Office Files for Macros Using Java
  • How to Automatically Detect Multiple Cybersecurity Threats from an Input Text String in Java

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • 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: