參考資源
--
建立服務
vi /etc/systemd/system/app.service
1 2 3 4 5 6 7 8 9 10 11 12 |
[Unit] Description=Gateway System Service [Service] Type=idle Restart=on-failure RestartSec=3s ExecStart=/usr/bin/python3 /opt/Gateway/app.py ExecStop=/bin/kill $MAINPID [Install] WantedBy=multi-user.target |
- Type=idle
systemd會等待所有工作處理完成後,才開始執行idle類型的單元。其他行為和Type=simple 類似 - Restart=on-failure
什麼情況下重啟 "always", "on-success", "on-failure", "on-abnormal", "on-abort", or "on-watchdog" - RestartSec=3s
指定在嘗試重新啟動服務之前等待的時間 - WantedBy=multi-user.target
在多人模式時開機啟動
1 2 3 |
# systemctl enable app Created symlink from /etc/systemd/system/multi-user.target.wants/app.service to /lib/systemd/system/app.service. # systemctl start app |
對 service 有異動時,記得重新 enabled 或 disable 該服務
--
監看輸出訊息
Python 程式碼
1 2 |
import logging logging.basicConfig(level=logging.INFO, format='%(pathname)s:%(lineno)d %(message)s', datefmt='%Y-%m-%d %H:%M:%S') |
使用 journalctl 可查看 python 輸出訊息
1 |
journalctl -u service -f |
1 2 3 |
Jun 09 08:59:02 CC31 python3[1289]: /opt/Gateway/python/App.py:1106 [1, 3, 0, 133, 0, 2, 213, 226] Jun 09 08:59:02 CC31 python3[1289]: /opt/Gateway/python/App.py:1106 [1, 3, 0, 20, 0, 60, 5, 223] Jun 09 08:59:04 CC31 python3[1289]: /opt/Gateway/python/App.py:596 0 |
開頭這段「Jun 09 08:59:02 CC31 python3[1289]:」是 journalctl 預設的顯示,如果不需要可以加上 -o cat 來過濾,預設的輸出格式是 short
1 |
journalctl -u service -f -o cat |
1 2 3 |
/opt/Gateway/python/App.py:1106 [1, 3, 0, 133, 0, 2, 213, 226] /opt/Gateway/python/App.py:1106 [1, 3, 0, 20, 0, 60, 5, 223] /opt/Gateway/python/App.py:596 0 |
--
1,051 total views, 1 views today