

0 / 2 embers
0 / 3000 xp
click for more info
Complete a lesson to start your streak
click for more info
Difficulty: 6
click for more info
Not enough gems
Cost: 6 gems
1: Log Storage
incomplete
2: Logging to the Console
incomplete
3: Filesystem Logging
incomplete
4: Log Rotation
incomplete
5: Syslog
incomplete
This lesson's interactive features are locked, please to keep using them
Click to play video
When logging to a file, it's important to rotate it occasionally. Otherwise, it grows forever and eventually fills your disk. Log rotation needs to:
linko.log to linko.log.0.We typically keep a set number of old log files, renaming them all in sequence. For example:
linko.log is the active file, currently being written tolinko.log.0 is the previous log filelinko.log.1 is an older onelinko.log.2 is even olderlinko.log.99 is the oldest log file (assuming we keep 100 log files)It's a bit trickier than it sounds. We need to ensure that:
Fortunately, Nate Finch created gopkg.in/natefinch/lumberjack.v2, which handles this complexity across operating systems. We just need a few changes to log initialization:
logger := &lumberjack.Logger{
Filename: logFile,
MaxSize: 1,
MaxAge: 28,
MaxBackups: 10,
LocalTime: false,
Compress: true,
}
handlers = append(handlers, slog.NewJSONHandler(logger, &slog.HandlerOptions{
ReplaceAttr: replaceAttr,
}))
It will use gzip compression to compress old log files, and will rotate the logs when they reach 1 megabyte in size.
Log rotation is usually not handled by application servers themselves. Servers focus on business logic. Rotation is often handled by the infrastructure running the app, such as:
We're gonna make it our application's responsibility in this course simply for the learning experience!
Switch file logging to a rotating writer.
#!/usr/bin/env bash
set -euo pipefail
for i in {1..3500}; do
curl -sS "http://localhost:8899" > /dev/null
if (( i % 100 == 0 )); then
echo "Completed $i requests"
fi
done
After running the script, you should have:
linko.access.log filelinko.access*.gz fileWith your server running, run and submit the CLI tests from the root of the Linko repo.