Is there a way to send logs to Loki directly without having to use one of it's agents?
For example, if I have an API, is it possible to send request/response logs directly to Loki from an API, without the interference of, for example, Promtail?
Is there a way to send logs to Loki directly without having to use one of it's agents?
For example, if I have an API, is it possible to send request/response logs directly to Loki from an API, without the interference of, for example, Promtail?
Yes. You can send logs directly from a Java application to loki.
It can be done using the loki4j configuration in your java springboot project. Add these below dependencies to pom.xml
<dependency>
<groupId>com.github.loki4j</groupId>
<artifactId>loki-logback-appender</artifactId>
<version>1.2.0</version>
</dependency>
Run loki either directly or from docker depending on how you have installed loki on your system. I use docker instances of loki and grafana.
Create a logback.xml in your springboot project with the following contents
<property name="HOME_LOG" value="app.log" />
<appender name="FILE-ROLLING"
class="com.github.loki4j.logback.Loki4jAppender">
<http>
<url>http://localhost:3100/loki/api/v1/push</url>
</http>
<format>
<label>
<pattern>app=my-app,host=${HOSTNAME},level=%level</pattern>
</label>
<message>
<pattern>l=%level h=${HOSTNAME} c=%logger{20} t=%thread | %msg %ex
</pattern>
</message>
<sortByTime>true</sortByTime>
</format>
</appender>
<logger name="com.vasanth.loki" level="debug" additivity="false">
<appender-ref ref="FILE-ROLLING" />
</logger>
<root level="error">
<appender-ref ref="FILE-ROLLING" />
</root>
</configuration>
Configure your logger names in the above example and make sure you have given the proper loki URL - You are basically telling the application to write logs into an output stream going directly to the loki URL instead of the traditional way of writing logs to a file through log4j configuration and then using promtail to fetch these logs and load into loki.
Logs can be pushed to Loki in JSON or compresses protobuf format via /loki/api/v1/push. Note that it isn't recommended storing log messages with labels containing big number of unique values (such as trace_id, user_id, ip, etc.), since this may lead to high memory usage and slowdown for Grafana Loki (aka high cardinality issues). See these docs for details.
Loki HTTP API
Loki HTTP API allows pushing messages directly to Grafana Loki server:
So it is easy to create JSON-formatted string with logs and send it to the Grafana Loki.
Libraries
There are some libraries implementing several Grafana Loki protocols.
There is also (my) zero-dependency library in pure Java 1.8, which implements pushing logs in JSON format to Grafana Loki. Works on Java SE and Android platform:
Security
Above API doesn't support any access restrictions as written here - when using over public network, consider e.g. configuring Nginx proxy with HTTPS from Certbot and Basic Authentication.