Swatch Linux Log File Watcher: How to Use It
In this article
Swatch (the Simple WATCHer) is a command-line log file watcher for Linux that monitors log files in real time and triggers actions when lines match patterns you define. It is a practical tool for system administrators and developers who need to react to errors, security events, or specific application messages without manually tailing logs. This article explains how Swatch works, how to install and configure it, and how to use it effectively.
What Is Swatch?
Swatch is a Perl-based utility that originated in the early 1990s as a tool to monitor log files and alert administrators. It reads log files continuously, applies pattern-matching rules, and executes actions such as printing to the terminal, sending email, or running a script. Swatch is especially useful for watching multiple logs simultaneously and for filtering out noise so you only see what matters.
Unlike a simple tail -f, Swatch lets you define complex rules: you can match regular expressions, ignore certain lines, throttle alerts, and even run external commands when a pattern appears. It is a classic tool that remains relevant for many legacy systems and for users who prefer a lightweight, scriptable solution.
How Swatch Works
Swatch reads a configuration file (usually .swatchrc) that contains one or more rule blocks. Each rule specifies a regular expression to match against incoming log lines, and one or more actions to take when a match occurs. Actions can include:
- Printing the matched line to the console (the default).
- Sending an email to a specified address.
- Executing a shell command or script.
- Writing to a separate output file.
- Playing a sound or sending a desktop notification (if configured).
Swatch can run in the foreground or as a daemon. In daemon mode, it runs in the background and can be managed with a PID file. It also supports multiple log files, each with its own set of rules.
Installing Swatch on Linux
Swatch is available in the official repositories of most major Linux distributions. Installation is straightforward:
- Debian/Ubuntu:
sudo apt install swatch - RHEL/CentOS/Fedora:
sudo dnf install swatch(oryumon older systems) - Arch Linux:
sudo pacman -S swatch
If it is not in your distribution's repositories, you can install it from CPAN using cpan Swatch, but the packaged version is usually simpler. After installation, verify with swatch --version.
Basic Configuration and Usage
The configuration file uses a simple syntax. A minimal .swatchrc might look like this:
watchfor /ERROR/ echo=red mail=admin@example.com,subject=Error Alert
This tells Swatch to watch for lines containing "ERROR", print them in red, and send an email to admin@example.com. To run Swatch on a specific log file:
swatch -c ~/.swatchrc -t /var/log/syslog
The -t option makes Swatch start at the end of the file (like tail -f). Without it, Swatch reads from the beginning. You can also use -r to restart from the last saved position, and -p to specify a PID file for daemon mode.
Advanced Features and Patterns
Swatch supports several advanced features that make it more than a simple grep:
- Multiple patterns: You can have multiple
watchforblocks, each with different actions. - Ignore patterns: Use
ignoreto skip lines that match a pattern, even if they also match awatchfor. - Throttling: The
throttleoption limits how often an action triggers for the same pattern (e.g.,throttle 00:05:00to wait 5 minutes). - Context lines: The
windowoption lets you include lines before and after the match (e.g.,window 2:5to show 2 lines before and 5 after). - Timeouts and continuations: You can set
timeoutto stop watching after a certain period, andcontinuationto keep watching after a match.
For example, to watch for a specific error and run a script:
watchfor /disk full/ echo=bold exec /usr/local/bin/cleanup.sh
Common Problems and Troubleshooting
Here are a few issues you might encounter and how to resolve them:
- Swatch doesn't start: Check that the configuration file is valid and that the log file path exists. Use
swatch --config-checkto validate the config. - No output: Make sure you are using
-tif you want to tail the file. Also verify that the pattern matches the log format (usegrepto test). - Email not sending: Swatch uses the system's sendmail or SMTP configuration. Ensure that a mail transfer agent (MTA) is installed and configured.
- High CPU usage: If you are watching a very active log, consider using
throttleor narrowing your patterns to reduce processing. - Patterns with special characters: Remember that patterns are Perl regular expressions. Escape characters like
.,*, and?if you want literal matches.
Alternatives to Swatch
Swatch is not the only tool for log monitoring. Depending on your needs, you might consider:
- Logwatch: A more comprehensive log analysis tool that generates daily summaries.
- Fail2ban: Specifically for blocking IPs that show malicious behavior (e.g., repeated SSH failures).
- Multitail: A terminal-based tool that displays multiple log files with color highlighting and filtering.
- Systemd journal: If your system uses systemd,
journalctl -fprovides real-time filtering with powerful options. - Prometheus and Grafana: For large-scale monitoring and alerting, these tools offer more advanced features but require more setup.
Swatch remains a good choice for simple, scriptable, low-overhead monitoring on a single machine.
Safety and Best Practices
When using Swatch, keep these points in mind:
- Test your configuration: Always test with a sample log file before relying on it in production.
- Be careful with
execactions: Only run commands you trust, and ensure they are idempotent to avoid side effects. - Secure your config file: If it contains email addresses or paths, ensure it is not world-readable.
- Monitor resource usage: Swatch is lightweight, but watching many files with complex regex can consume CPU. Use throttling and efficient patterns.
- Plan for log rotation: Swatch handles log rotation gracefully if you use the
-roption, but you may need to restart it after rotation in some setups.
Frequently Asked Questions
How do I make Swatch start automatically on boot?
You can create a systemd service unit that runs Swatch with your configuration. Write a unit file that executes swatch -c /path/to/.swatchrc -t /var/log/yourlog and enable it with systemctl enable swatch. Alternatively, add it to crontab with @reboot.
Can Swatch watch multiple log files at once?
Yes. You can run multiple Swatch processes, each with its own config and log file, or use a single config with multiple watchfor blocks and specify multiple files on the command line (though the latter is less common). A more efficient approach is to use a tool like multitail for multi-file viewing, but Swatch can handle it by launching several instances.
What is the difference between Swatch and tail -f?
tail -f simply outputs new lines as they are appended to a file. Swatch adds pattern matching, alerting, and automated actions. You can think of Swatch as a programmable tail that can filter and react to log content.
Does Swatch work with systemd journals?
Swatch works with files, not directly with the systemd journal. To monitor journal logs, you can export them to a file using journalctl -f > /tmp/journal.log and then point Swatch at that file. Alternatively, use journalctl with its own filtering options.
How do I test my Swatch configuration without waiting for a real event?
You can manually append a test line to the log file that matches your pattern. For example, echo "test ERROR" >> /var/log/syslog (if you have permission). Then watch Swatch's output to see if it triggers the expected action.
Is Swatch still maintained?
Swatch is an old tool, and its development has slowed. However, it is still packaged in many distributions and works reliably for basic monitoring. For modern systems, you may prefer alternatives like Fail2ban or Logwatch, but Swatch remains a viable option for simple tasks.