401 Error on writing logs to Loki with logging_loki python library

Hi,

I am a complete noob on grafana. I am trying to send some logs from my VM to my loki data source. I have followed this documentation:
#### Using Grafana with Logs

Whether you are using Grafana on-prem or Grafana Cloud, adding a Data Source for Logs works the same way:

** Log into your Grafana instance with Admin rights.*
** Add a “Loki” type Data Source with the following details:*

Grafana Data Source settings

After setting up the loki instance with the username and password/grafana token and setting up the below python code I was always getting 401 error. After some investigating I noticed that the token I generated in Grafana Data Source settings only has read permissions. So I saw that a bit below on the page I can generate a grafana api token that has write permissions. However, when I copy that token and set it as password in my loki setting I always get: Unable to connect with Loki. Please check the server logs for more details.

Does anybody know how to make it work so I can write my logs directly to loki?

Thanks for your help in advance.

Regards,

import logging
import logging_loki

user=user
passw=passw
auth=(user, passw)

logging_loki.emitter.LokiEmitter.level_tag = "level"
# assign to a variable named handler 
handler = logging_loki.LokiHandler(
   url=grafana_url/loki/api/v1/push",
   auth=auth,
   version="1",
)
# create a new logger instance, name it whatever you want
logger = logging.getLogger("my-logger")
logger.setLevel(logging.DEBUG)
logger.addHandler(handler)
logger.warning(
   "Something bad happened but we can keep going",
   extra={"tags": {"service": "my-service"}},
)

I’d say try to write your own handler or just perform the API call in a function. As far as I know most of the Python Loki module aren’t being kept up-to-date.

1 Like

401 indicates wrong credentials. But try to wait a moment. It may take a few minutes until new token is recognised properly by all components in Grafana Cloud.