乐闻世界logo
搜索文章和话题

How to redirect output of systemd service to a file

1个答案

1

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.log
  • StandardError=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.

  1. Open or create the service's Unit file:

    bash
    sudo nano /etc/systemd/system/my_service.service
  2. 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
  3. 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.

bash
sudo 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.

bash
cat /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.

2024年8月16日 23:25 回复

你的答案