1
1

More than 3 years have passed since last update.

[CentOS8]Pythonの標準出力をsystemdのログに吐く方法

Posted at

はじめに

PythonでTwitterのボットを作ったのだが、print関数で出力したログsystemctl statusコマンドでみることができずはまったので解決方法を覚え書きです。もっといい方法があったら教えていただけると嬉しいです。

環境

CentOS Linux release 8.1.1911 (Core)

Unitファイルの記述

etc\systemd\system\におくUnitファイルの記述

bot.service
[Unit]
Description=Python Tweet Collector

[Service]
ExecStart=実行ファイル(ここではBotを起動するシェルスクリプト)のパス
Type=simple
StandardOutput=journal #標準出力をjournalctlで見られるようにする
StandardError=journal #標準エラーをjournalctlで見られるようにする

[Install]
WantedBy=multi-user.target

Pythonコマンド実行時のオプション

上記の設定だけだとPythonの標準出力がバッファされてprint文の出力が表示されないことがあるらしい...
ということでシェルスクリプトを書き、そこからBotを起動するようにしました

start_bot.sh
#!/bin/bash

cd $(dirname $0) #このファイルがあるディレクトリに移動

. venv/bin/activate #Pythonの仮想環境を有効化

python -u bot.py # -u オプションでバッファを無効化

最後にchmod 744 start_bot.shでシェルスクリプトに実行権限を付与

Botを起動

systemctl start bot.service

Botの状態を確認

systemctl status bot.service

ログを確認

journalctl -u bot.service

Pythonのプリント文で出力した内容がログに表示されているのが確認できると思います

おわり

Linuxのことはまだまだ初心者なので、不適切な箇所の指摘、アドバイス等ありましたらご教授いただけるととてもうれしいです。

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1