![bash 或 python 脚本中的日志如何附加到特定的日志单元名称?](https://linux22.com/image/165292/bash%20%E6%88%96%20python%20%E8%84%9A%E6%9C%AC%E4%B8%AD%E7%9A%84%E6%97%A5%E5%BF%97%E5%A6%82%E4%BD%95%E9%99%84%E5%8A%A0%E5%88%B0%E7%89%B9%E5%AE%9A%E7%9A%84%E6%97%A5%E5%BF%97%E5%8D%95%E5%85%83%E5%90%8D%E7%A7%B0%EF%BC%9F.png)
脚本(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而不按单位过滤时,我可以看到日志行:s
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]”是脚本关联的默认单元名称还是默认值是什么?