BashまたはPythonスクリプトのログを特定のログユニット名にどのように追加できますか?

BashまたはPythonスクリプトのログを特定のログユニット名にどのように追加できますか?

スクリプト(bash、pythonなど)私のロギングと印刷はデバイス名とどのように関連していますか?

非常に単純な単位ファイルtest-service.serviceがあるとしましょう。

[Unit]
Description=Test Unit

[Service]
Type=simple
User=myuser
Group=myuser
ExecStart=/usr/bin/bash /home/myuser/hello.sh

[Install]
WantedBy=default.target

hello.sh には以下が含まれます。

#!/bin/bash
echo "Hello World"

その特定のユニットファイルのログを表示しようとすると、「Hello World」ログ行は表示されません。

journalctl -u test-service -f
-- Logs begin at Mon 2019-12-09 10:07:15 CET. -- Dec 09 10:10:51 localhost.localdomain systemd[1]: Started Test Unit.

単位でフィルタリングせずに Journalctl を実行すると、次のログ行が表示されます。

journalctl -f
-- Logs begin at Mon 2019-12-09 10:07:15 CET. --
Dec 09 10:14:07 localhost.localdomain bash[4776]: Hello World

これで、このユニットファイルでも同じことが起こります。

[Unit]
Description=Test Unit

[Service]
Type=simple
User=myuser
Group=myuser
ExecStart=/usr/bin/python /home/myuser/test.py

[Install]
WantedBy=default.target

test.py には以下が含まれます。

import logging

class TestService(object):
    def __init__(self):
        logging.basicConfig()
        self.log = logging.getLogger("test-service")
        self.log.setLevel(logging.INFO)

    def hello_world(self):
        exit_code = 0
        print("Hello world, exit_code = {}".format(exit_code))
        self.log.info("Hello world!!!")
        exit(exit_code)


if __name__ == "__main__":
    print("starting up..")
    r = TestService()
    r.hello_world()

その特定のユニットファイルのログを再表示しようとすると、「Hello World」ログ行は表示されません。

journalctl -u test-service -f
-- Logs begin at Mon 2019-12-09 10:07:15 CET. --
Dec 09 10:10:51 localhost.localdomain systemd[1]: Started Test Unit.

単位でフィルタリングせずにJournalctlを実行すると、次のログ行が表示されます。

systemd[1]: Started Test Unit.
Dec 09 10:28:52 localhost.localdomain python[5449]: INFO:test-service:Hello world!!!
Dec 09 10:28:52 localhost.localdomain python[5449]: starting up..
Dec 09 10:28:52 localhost.localdomain python[5449]: Hello world, exit_code = 0

BashとPythonスクリプトのスクリプトは、ユニットファイルとどのような関係がありますか? "bash[4776]" と "python[5449]" はスクリプトに関連するデフォルトのユニット名ですか、それともデフォルトは何ですか?

ベストアンサー1

おすすめ記事