Of course! This is a classic and powerful setup. I'll guide you through the process step-by-step.
Your intuition to "pass the log folder to Grafana" is correct in spirit, but there's a small but important detail. Grafana doesn't read log files directly. It queries a data source. For logs, the industry-standard data source to use with Grafana is Loki.
So, our stack will be:
- Your Application (with Loguru): Writes JSON-formatted logs to
./log/app.log.
- Promtail: An agent that "tails" (watches) your log files, adds labels, and ships them to Loki. This is the component that reads your
./log folder.
- Loki: A log aggregation system. It receives logs from Promtail, indexes them efficiently, and makes them queryable.
- Grafana: The visualization tool. We will configure it to use Loki as a data source, and then we'll build the "interface" (a dashboard) to view the logs.
We'll run all of this using Docker Compose to make it easy to start and stop everything together.
The Plan
- Prepare Your Python App: Ensure Loguru is configured to output structured (JSON) logs.
- Create a
docker-compose.yml: Define the app, loki, promtail, and grafana services.
- Create Configuration Files: We'll need simple config files for Promtail, Loki, and Grafana's provisioning.
- Run the Stack: A single command to bring everything up.
- Visualize in Grafana: Access Grafana, see the automatically configured data source, and explore your logs.
Step 1: Prepare Your Python Application
For Loki to work best, your logs should be structured. JSON is the perfect format. Let's configure Loguru to write JSON logs to a file.
Create a simple Python app for our example.
main.py
import sys
import time
from loguru import logger
# 1. Remove the default handler to prevent duplicate console output.
logger.remove()
# 2. Add a handler for structured JSON logging to a file.
# - serialize=True turns the log record into a JSON string.
# - rotation/retention are good practices for log file management.
logger.add(
"./log/app.log", # The file to write to
level="INFO", # The minimum level to log
format="{message}", # Use a simple format, the magic is in serialize
serialize=True, # THIS IS THE KEY!
rotation="10 MB", # Rotate the log file when it reaches 10 MB
retention="7 days", # Keep logs for 7 days
catch=True # Catch exceptions from your code
)
# 3. (Optional) Add a human-readable logger to the console for development.
logger.add(sys.stdout, level="DEBUG", format="<green>{time:YYYY-MM-DD HH:mm:ss}</green> | <level>{level: <8}</level> | <cyan>{name}</cyan>:<cyan>{function}</cyan>:<cyan>{line}</cyan> - <level>{message}</level>")
def main():
logger.info("Application starting up.", component="startup")
for i in range(10):
try:
if i % 4 == 0:
# This will raise a ValueError
result = 10 / (i - 4)
logger.info("Processing item.", item_id=i, user_id="user-123")
time.sleep(1)
except Exception as e:
# The 'catch=True' in the logger setup will handle this automatically.
# Or you can log it explicitly:
logger.exception("An error occurred during processing.")
time.sleep(2)
logger.warning("Application shutting down.", component="shutdown")
if __name__ == "__main__":
main()
requirements.txt
loguru
Dockerfile (for your app)
FROM python:3.9-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY main.py .
# Create the log directory
RUN mkdir -p /app/log
CMD ["python", "main.py"]
Step 2: Create Configuration Files
Now, let's create the necessary configuration files.
Project Structure:
.
├── log/ <-- Promtail will read from here
├── grafana/
│ └── provisioning/
│ └── datasources/
│ └── datasource.yml
├── docker-compose.yml
├── Dockerfile
├── loki-config.yml
├── main.py
├── promtail-config.yml
└── requirements.txt
promtail-config.yml
This tells Promtail where to find Loki and which files to watch.
server:
http_listen_port: 9080
grpc_listen_port: 0
positions:
filename: /tmp/positions.yaml
clients:
- url: http://loki:3100/loki/api/v1/push
scrape_configs:
- job_name: my-python-app
static_configs:
- targets:
- localhost
labels:
job: my-app # This label will be attached to every log line
__path__: /var/log/*.log # The path INSIDE the Promtail container
IMPORTANT: __path__: /var/log/*.log refers to the path inside the Promtail container. In the next step, we will mount our host's ./log folder to /var/log in the Promtail container.
loki-config.yml
A minimal Loki config that uses the local filesystem.
auth_enabled: false
server:
http_listen_port: 3100
ingester:
lifecycler:
address: 127.0.0.1
ring:
kvstore:
store: inmemory
replication_factor: 1
final_sleep: 0s
chunk_idle_period: 5m
chunk_retain_period: 1m
max_transfer_retries: 0
schema_config:
configs:
- from: 2020-10-24
store: boltdb-shipper
object_store: filesystem
schema: v11
index:
prefix: index_
period: 24h
storage_config:
boltdb_shipper:
active_index_directory: /loki/boltdb-shipper-active
cache_location: /loki/boltdb-shipper-cache
cache_ttl: 24h
shared_store: filesystem
filesystem:
directory: /loki/chunks
grafana/provisioning/datasources/datasource.yml
This is the magic for automatic configuration. Grafana will read this file on startup and automatically add Loki as a data source.
apiVersion: 1
datasources:
- name: Loki
type: loki
access: proxy
url: http://loki:3100
isDefault: true
jsonData:
# Use the 'my-app' label we defined in promtail-config.yml
derivedFields:
- datasourceUid: '${__datasource.uid}'
matcherRegex: 'level=info'
name: 'TraceID'
url: 'http://localhost:16686/trace/${__value.raw}'
Step 3: Create the docker-compose.yml File
This file is the orchestra conductor. It defines all our services and connects them.
docker-compose.yml
version: '3.8'
services:
# Our Python Application
app:
build: .
volumes:
- ./log:/app/log # Mount the log folder to the host
# Loki: The log aggregator
loki:
image: grafana/loki:2.9.1
ports:
- "3100:3100"
volumes:
- ./loki-config.yml:/etc/loki/local-config.yaml
command: -config.file=/etc/loki/local-config.yaml
# Promtail: The log shipper
promtail:
image: grafana/promtail:2.9.1
volumes:
- ./log:/var/log # Mount the host log folder to where Promtail expects it
- ./promtail-config.yml:/etc/promtail/config.yml
command: -config.file=/etc/promtail/config.yml
depends_on:
- loki
# Grafana: The visualization tool
grafana:
image: grafana/grafana:latest
ports:
- "3000:3000"
volumes:
- ./grafana/provisioning:/etc/grafana/provisioning
depends_on:
- loki
Step 4: Run the Stack
Make sure you are in the root directory of your project where docker-compose.yml is located.
-
Create the log directory:
mkdir log
-
Start all services:
docker-compose up --build -d
This will build your Python app image and start all four containers in the background.
Step 5: Visualize Your Logs in Grafana
-
Open Grafana: Navigate to http://localhost:3000 in your browser.
-
Login: The default credentials are admin / admin. You'll be prompted to change the password.
-
Explore Logs:
- On the left-hand menu, click the compass icon (Explore).
- At the top, the Loki data source should already be selected (because we set
isDefault: true).
- Click on the "Log browser" button. You should see our label
job with the value my-app. Click on it.
- The query bar will be populated with
{job="my-app"}. Click "Run query" in the top right.
You will now see your log lines!
-
Leverage Structured Logs:
This is where the power of JSON logging shines.
- Click on any log line to expand it. You will see all the fields from your JSON log (
level, message, component, item_id, etc.) as "Detected fields".
- To filter based on these fields, you can use a filter expression. Add
| json to your query to parse the log line as JSON, then you can filter.
Example Queries:
- Show only error logs:
{job="my-app"} | json | level="ERROR"
- Show only startup/shutdown messages:
{job="my-app"} | json | component="startup" or component="shutdown"
- Find logs for a specific item:
{job="my-app"} | json | item_id=7
You have now successfully created an automatic log visualization pipeline! You just write logs to the ./log folder, and they automatically appear in Grafana, ready to be searched and analyzed.