Data and monitoring · Intermediate · 25 min
Collect server logs with Grafana Loki and Alloy
By Padding · Updated 18 Nov 2026
Ubuntu 26.04 LTS · Grafana Loki 3.7.10 · Grafana Alloy 1.22.0
You will run Loki 3.7 with a seven-day retention limit and an Alloy 1.22 pipeline that ships your server's log files and journal to it with job, host and level labels, drops debug lines, and answers queries from logcli.
On this page
Logs answer the questions metrics cannot: which request failed, what the error said, which service restarted at 02:14. Reading them with less on one server works until you have several log files, a journal and a deadline. This tutorial collects them into one searchable store on the same server.
Two programs do the work. Loki stores log lines. Unlike a full-text search engine it indexes only a small set of labels, such as job="demo-app", and keeps the lines themselves compressed in chunks on disk. That keeps it cheap to run, and it means your choice of labels matters. Grafana Alloy is the collector: it tails files and the systemd journal, reshapes each line through a pipeline, and pushes the result to Loki. Alloy replaces Promtail, which reached end of life on 2 March 2026 and gets no more fixes.
Both are installed from the official release files and run as locked-down systemd services that listen on 127.0.0.1 only. Keeping the store on the same machine also means no log data crosses the network, which helps when a server sits behind a metered or prepaid data link, common for small offices across Africa and elsewhere.
Step 1 · Install the tools and set the versions
Install the two tools the downloads need, then record the versions and your CPU architecture in shell variables. Every later command uses them, so stay in this terminal, or set them again in a new one:
sudo apt update
sudo apt install -y curl unzip
LOKI_VERSION=3.7.10
ALLOY_VERSION=1.22.0
ARCH="$(dpkg --print-architecture)"
echo "$ARCH"The last line prints amd64 on most servers and arm64 on ARM servers; both projects publish release files under those names. Check https://github.com/grafana/loki/releases and https://github.com/grafana/alloy/releases for newer versions before you start. Loki 4.0 is in release candidates at the time of writing; stay on 3.7 until 4.0 is final and you have read its upgrade notes.
Check it worked
echo "$LOKI_VERSION $ALLOY_VERSION" prints 3.7.10 1.22.0, and the architecture is one of amd64 or arm64.
Step 2 · Install Loki and logcli
Download the Loki server, the logcli query tool and the release's checksum list into a work folder, then check both files against the list. The check catches a damaged download; it cannot prove who published the file, so download only from the official GitHub release address:
mkdir -p ~/logging-install
cd ~/logging-install
BASE="https://github.com/grafana/loki/releases/download/v${LOKI_VERSION}"
curl -fsSLO "${BASE}/loki-linux-${ARCH}.zip"
curl -fsSLO "${BASE}/logcli-linux-${ARCH}.zip"
curl -fsSL -o loki-SHA256SUMS "${BASE}/SHA256SUMS"
sha256sum --ignore-missing -c loki-SHA256SUMSThe last command prints two lines ending in OK. If either says FAILED, delete that file and download it again.
Unpack both and install the programs. Then create a system user for Loki with no password, home folder or shell, and the folders it needs. /var/lib/loki holds the log data, so only Loki can read it:
unzip -o "loki-linux-${ARCH}.zip"
unzip -o "logcli-linux-${ARCH}.zip"
sudo install -o root -g root -m 0755 "loki-linux-${ARCH}" /usr/local/bin/loki
sudo install -o root -g root -m 0755 "logcli-linux-${ARCH}" /usr/local/bin/logcli
sudo useradd --system --no-create-home --shell /usr/sbin/nologin loki
sudo install -d -o loki -g loki -m 0750 /var/lib/loki
sudo install -d -o root -g root -m 0755 /etc/lokiCheck it worked
loki --version | head -n 1
logcli --version 2>&1 | head -n 1Both lines mention version 3.7.10, something like loki, version 3.7.10 (branch: ...).
Step 3 · Configure Loki with retention and run it
Write the configuration. It runs every part of Loki in one process, stores chunks and the index on the local disk, and listens on 127.0.0.1 only. Loki has no login when auth_enabled is false, so it must not be reachable from the internet:
sudo tee /etc/loki/config.yaml > /dev/null <<'YAML'
auth_enabled: false
server:
http_listen_address: 127.0.0.1
http_listen_port: 3100
grpc_listen_address: 127.0.0.1
grpc_listen_port: 9096
log_level: info
common:
instance_addr: 127.0.0.1
path_prefix: /var/lib/loki
storage:
filesystem:
chunks_directory: /var/lib/loki/chunks
rules_directory: /var/lib/loki/rules
replication_factor: 1
ring:
kvstore:
store: inmemory
schema_config:
configs:
- from: 2026-01-01
store: tsdb
object_store: filesystem
schema: v13
index:
prefix: index_
period: 24h
limits_config:
retention_period: 168h
compactor:
working_directory: /var/lib/loki/compactor
retention_enabled: true
delete_request_store: filesystem
analytics:
reporting_enabled: false
YAMLThree parts decide how much disk Loki uses. Without retention_enabled: true in compactor, Loki keeps logs for ever. retention_period: 168h keeps seven days; raise it if you have the disk, lower it on a small VPS. Retention needs the 24-hour index period shown in schema_config, and Loki deletes expired chunks a couple of hours after marking them, not at the exact second. analytics turns off the anonymous usage report Loki sends to Grafana Labs by default.
Check the file before you run it:
loki -config.file=/etc/loki/config.yaml -verify-configIt prints a log line containing msg="config is valid" and exits. A typo in a key name stops it with a message naming the key.
Now the systemd unit. The [Service] options run Loki as its own user, restart it if it crashes, and stop it gaining privileges, reading home folders or sharing /tmp:
sudo tee /etc/systemd/system/loki.service > /dev/null <<'UNIT'
[Unit]
Description=Grafana Loki log store
After=network-online.target
Wants=network-online.target
[Service]
User=loki
Group=loki
ExecStart=/usr/local/bin/loki -config.file=/etc/loki/config.yaml
Restart=on-failure
NoNewPrivileges=true
ProtectHome=true
PrivateTmp=true
[Install]
WantedBy=multi-user.target
UNITsudo systemctl daemon-reload
sudo systemctl enable --now loki
sudo systemctl status loki --no-pagerThe status shows active (running).
Check it worked
Loki takes about 15 to 30 seconds after starting before it accepts data. Ask whether it is ready, and confirm the retention settings it loaded:
curl -s http://127.0.0.1:3100/ready
curl -s http://127.0.0.1:3100/config | grep -E '^ *retention_(enabled|period):'
ss -tln | grep 3100The first line is ready; if it says something like Ingester not ready, wait and try again. Among the config lines are retention_enabled: true and retention_period: 1w (Loki writes 168 hours as one week). The ss line shows 127.0.0.1:3100, not 0.0.0.0:3100 or *:3100.
If Loki does not start, run sudo journalctl -u loki -n 30 --no-pager. A permission denied on /var/lib/loki means the folder is not owned by the loki user.
Step 4 · Install Alloy
Download, check and install Alloy the same way:
cd ~/logging-install
BASE="https://github.com/grafana/alloy/releases/download/v${ALLOY_VERSION}"
curl -fsSLO "${BASE}/alloy-linux-${ARCH}.zip"
curl -fsSL -o alloy-SHA256SUMS "${BASE}/SHA256SUMS"
sha256sum --ignore-missing -c alloy-SHA256SUMS
unzip -o "alloy-linux-${ARCH}.zip"
sudo install -o root -g root -m 0755 "alloy-linux-${ARCH}" /usr/local/bin/alloyAlloy needs to read logs that belong to other programs. On Ubuntu, files such as /var/log/syslog and /var/log/auth.log are readable by the adm group, and the journal by systemd-journal. Create the alloy user in both groups, plus its data folder (where it remembers how far it has read each file) and its configuration folder:
sudo useradd --system --no-create-home --shell /usr/sbin/nologin --groups adm,systemd-journal alloy
sudo install -d -o alloy -g alloy -m 0750 /var/lib/alloy
sudo install -d -o root -g root -m 0755 /etc/alloyMembership of adm lets Alloy read your authentication log, which records login attempts. That is the point, but it is also why Loki must stay private.
Check it worked
alloy --version | head -n 1
id alloyThe first line is something like alloy, version v1.22.0 (branch: ...). The id output lists adm and systemd-journal among the groups.
Step 5 · Write the pipeline for log files
An Alloy configuration is a set of components wired together: a source sends lines to a processor, which sends them to a writer. You refer to another component by its type and name, as in loki.write.local.receiver.
Labels need care. Each distinct combination of label values is a separate stream in Loki, with its own index entry and chunks. A label with a handful of values, such as job, host or level, is cheap. A label with an order number, user ID or IP address creates a stream per value and makes Loki slow and large. Keep those in the line, and filter on them at query time.
For this tutorial, a demo application writes logfmt lines (key=value pairs) to its own folder. Create the folder and an empty file now. On your own server, point the path at your application's real log folder instead:
sudo install -d -o root -g root -m 0755 /var/log/demo-app
sudo touch /var/log/demo-app/app.logNow the main configuration. It has three parts: a writer that adds the host label to everything it sends, a source for the system's log files, and a source plus processor for the application, which reads level from each line, drops debug lines and makes level a label:
sudo tee /etc/alloy/config.alloy > /dev/null <<'ALLOY'
// Everything ends up here. host is added to every stream.
loki.write "local" {
endpoint {
url = "http://127.0.0.1:3100/loki/api/v1/push"
}
external_labels = { host = constants.hostname }
}
// System log files. /var/log/syslog exists only if rsyslog is installed.
loki.source.file "system_files" {
targets = [
{ __path__ = "/var/log/*.log", job = "varlogs" },
{ __path__ = "/var/log/syslog", job = "varlogs" },
]
forward_to = [loki.write.local.receiver]
file_match {
enabled = true
sync_period = "10s"
}
}
// The demo application writes logfmt lines such as: level=info msg="..."
loki.source.file "demo_app" {
targets = [
{ __path__ = "/var/log/demo-app/*.log", job = "demo-app" },
]
forward_to = [loki.process.demo_app.receiver]
file_match {
enabled = true
sync_period = "5s"
}
}
loki.process "demo_app" {
stage.logfmt {
mapping = { level = "" }
}
stage.drop {
source = "level"
value = "debug"
drop_counter_reason = "debug"
}
stage.labels {
values = { level = "" }
}
forward_to = [loki.write.local.receiver]
}
ALLOYloki.source.file also adds a filename label to every line by itself, so varlogs becomes one stream per file under /var/log (auth.log, kern.log, dpkg.log, syslog and so on). That is fine: the number of log files is small and fixed. These streams have no level label, because only the demo application goes through the processor.
file_match makes Alloy look for new files matching each __path__ pattern every few seconds, so a log file created tomorrow is picked up without a restart. On its first run Alloy reads each file from the start. On a server with large old logs, add tail_from_end = true to system_files to send only new lines. The level extracted by stage.logfmt is a temporary value; only stage.labels turns it into a label.
Check it worked
sudo alloy validate /etc/alloy/config.alloy
echo "exit code $?"It prints exit code 0 and no error. A mistake, such as a missing brace or a misspelt component, is printed with its line number.
Step 6 · Add the systemd journal
Services managed by systemd log to the journal, not to files. Put the journal source in its own file in the same folder; Alloy loads every .alloy file in the folder as one configuration, so you can remove this file later to switch the journal off:
sudo tee /etc/alloy/journal.alloy > /dev/null <<'ALLOY'
// Turn journal fields into labels, and skip debug entries.
loki.relabel "journal" {
forward_to = []
rule {
source_labels = ["__journal__systemd_unit"]
target_label = "unit"
}
rule {
source_labels = ["__journal_priority_keyword"]
target_label = "level"
}
rule {
source_labels = ["__journal_priority_keyword"]
regex = "debug"
action = "drop"
}
}
loki.source.journal "system" {
max_age = "12h"
labels = { job = "journal" }
relabel_rules = loki.relabel.journal.rules
forward_to = [loki.write.local.receiver]
}
ALLOYEach journal field arrives as a hidden label such as __journal__systemd_unit and is thrown away unless a rule copies it to a visible one. The rules keep the unit name as unit and the priority word (error, warning, info and so on) as level, then drop debug entries. A server has a few dozen units, so unit stays low-cardinality. max_age stops Alloy sending more than the last 12 hours of journal on its first start.
Check it worked
Validate the whole folder, which checks both files together, including the reference from journal.alloy to loki.write.local in the other file:
sudo alloy validate /etc/alloy
echo "exit code $?"It prints exit code 0.
Step 7 · Run Alloy as a service
The unit runs Alloy against the whole folder, keeps its data in /var/lib/alloy, keeps its web interface on 127.0.0.1:12345 and turns off its anonymous usage report. ExecReload lets systemctl reload apply a changed configuration without restarting:
sudo tee /etc/systemd/system/alloy.service > /dev/null <<'UNIT'
[Unit]
Description=Grafana Alloy log collector
After=network-online.target loki.service
Wants=network-online.target
[Service]
User=alloy
Group=alloy
ExecStart=/usr/local/bin/alloy run --storage.path=/var/lib/alloy --server.http.listen-addr=127.0.0.1:12345 --disable-reporting /etc/alloy
ExecReload=/bin/kill -HUP $MAINPID
Restart=on-failure
NoNewPrivileges=true
ProtectHome=true
PrivateTmp=true
[Install]
WantedBy=multi-user.target
UNITsudo systemctl daemon-reload
sudo systemctl enable --now alloy
sudo systemctl status alloy --no-pagerThe status shows active (running). If Alloy exits straight away, the configuration has an error: Alloy refuses to start on a bad file, and sudo journalctl -u alloy -n 30 --no-pager shows the line.
Check it worked
curl -s http://127.0.0.1:12345/-/readyIt prints Alloy is ready.
Change the pipeline later
Edit a file in /etc/alloy, validate the folder, and reload only if it passes. If a reload does contain an error, Alloy keeps running with the last good configuration:
sudo alloy validate /etc/alloy && sudo systemctl reload alloyStep 8 · Send test lines and read them back with logcli
Append three lines to the demo application's log, one at each of info, debug and error:
printf '%s\n' \
'level=info msg="order created" order=1042' \
'level=debug msg="cache hit" key=user:7' \
'level=error msg="payment failed" order=1042' \
| sudo tee -a /var/log/demo-app/app.log > /dev/nullGive Alloy about ten seconds to send them. Then point logcli at Loki and ask for the demo application's lines from the last 15 minutes. --quiet hides the query details and --output=raw prints only the lines, newest first:
export LOKI_ADDR=http://127.0.0.1:3100
logcli query --since=15m --quiet --output=raw '{job="demo-app"}'You see the payment failed and order created lines, but not cache hit: the pipeline dropped the debug line before it reached Loki.
Check it worked
Use the labels. Ask only for errors, list the level, host and filename values Loki has seen, and look at a few system log lines:
logcli query --since=15m --quiet --output=raw '{job="demo-app", level="error"}'
logcli labels --since=15m level
logcli labels --since=15m host
logcli labels --since=15m filename
logcli query --since=15m --limit=5 --quiet --output=raw '{job="varlogs"}'The first command prints only the payment failed line. level includes error and info (plus journal levels such as notice and warning), but never debug. host lists your server's hostname, the same as the hostname command prints. filename lists /var/log/demo-app/app.log and one entry per system log file Alloy read. The last command prints five lines from files such as /var/log/dpkg.log.
Alloy also counts what it drops. Its metrics page shows the counter named after drop_counter_reason:
curl -s http://127.0.0.1:12345/metrics | grep '^loki_process_dropped_lines_total'You get a line containing reason="debug" with the value 1. If that number climbs fast on a busy server, the drop is saving you real disk space.
Journal entries are queried the same way, for example logcli query --since=1h '{job="journal", unit="ssh.service"}' for SSH logins. To see these logs in Grafana instead, add Loki as a data source at http://127.0.0.1:3100, as in the Grafana dashboard tutorial.
Step 9 · Upgrade or remove the stack
Hand-installed programs get no updates from apt, so apt upgrade never touches them. Watch the two GitHub release pages for security fixes. To upgrade, set the new version, repeat the download and checksum commands, then replace the program while its service is stopped:
ALLOY_VERSION=<new version>
# download, check and unzip as in the install step, then:
sudo systemctl stop alloy
sudo install -o root -g root -m 0755 "alloy-linux-${ARCH}" /usr/local/bin/alloy
sudo systemctl start alloyDo the same for loki and logcli. Read the release notes before moving to a new major version such as Loki 4, because configuration keys can change.
Loki stores data only from this server, and only Alloy on this server can reach it. To collect from several servers, run Alloy on each, change Loki's http_listen_address to a private network address, and open port 3100 to those servers only with your firewall.
To remove everything instead, run the commands below. Warning: the rm -r line deletes all stored logs in /var/lib/loki. The LogQL tutorial runs its own practice Loki, so it works with or without this setup:
sudo systemctl disable --now alloy loki
sudo rm /etc/systemd/system/alloy.service /etc/systemd/system/loki.service
sudo systemctl daemon-reload
sudo rm /usr/local/bin/alloy /usr/local/bin/loki /usr/local/bin/logcli
sudo rm -r /etc/alloy /etc/loki /var/lib/alloy /var/lib/loki /var/log/demo-app
sudo userdel alloy
sudo userdel loki
rm -rf ~/logging-installCheck it worked
After an upgrade, alloy --version or loki --version shows the new version and the service status is active (running). After removal, curl -s http://127.0.0.1:3100/ready fails to connect and id loki reports no such user.
Next steps
- Search, parse and count these logs: search and count logs with LogQL.
- Graph error counts next to your metrics: build your first Grafana dashboard.
- Stop the application's own log files filling the disk: manage log files with logrotate.
- Add CPU, memory and disk metrics: monitor a server with Prometheus and Node Exporter.
Related tutorials
- Search and count logs with LogQLYou will push JSON and logfmt logs into a practice Loki 3.7, then use logcli to filter them, parse their fields, reformat lines and turn them into counts, rates and a p95 latency.
- How to Build Your First Grafana Dashboard from Prometheus DataYou will install Grafana 13.3 from its apt repository on Ubuntu 26.04, set the admin password before the first start, keep it on localhost, connect it to Prometheus, and build a server overview dashboard with uptime, memory and CPU panels that lives in a file you can keep in Git.
- How to Stop Log Files Filling Your Disk with logrotateYou will write a logrotate 3.22 rule for an application's log on Ubuntu 26.04, rotate it by size or age, compress and expire old copies, and fix the classic problem where a program keeps writing to the rotated file, using copytruncate and a signal to reopen the log.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials