When you want to redirect the output of a systemd service to a file, you can achieve this by modifying the service's Unit file. Here are the specific steps and examples:
Step 1: Create or modify the service configuration file
First, ensure you have permissions to edit or create the system's Unit file. These files are typically located in the /etc/systemd/system/ directory.
Step 2: Configure log output
In the service's configuration file, you can redirect output by configuring StandardOutput and StandardError. By default, this output is sent to the journal (systemd's logging system), but you can modify it to redirect output to a specified file.
StandardOutput=file:/path/to/output_file.logStandardError=file:/path/to/error_file.log
Example
Suppose we have a service named my_service.service, and we want to redirect its standard output and error output to different files.
-
Open or create the service's Unit file:
bashsudo nano /etc/systemd/system/my_service.service -
Add or modify the following lines:
ini[Service] ExecStart=/usr/bin/my_service StandardOutput=file:/var/log/my_service_output.log StandardError=file:/var/log/my_service_error.log -
Save and close the file.
Step 3: Reload systemd and restart the service
After modifying the systemd configuration file, you need to reload systemd to apply the changes.
bashsudo systemctl daemon-reload sudo systemctl restart my_service.service
Step 4: Verify
Check the log files you specified to ensure the output is correctly redirected.
bashcat /var/log/my_service_output.log cat /var/log/my_service_error.log
Using this method, you can conveniently manage and view the service's runtime output, which aids in debugging and monitoring the service status. Remember that choosing the appropriate log file path and managing file permissions are also very important.