Python logging with Supervisor

2019-08-15 03:43发布

I'm currently using supervisor to monit and daemonize some python scripts easily. However, it seems that supervisor won't log properly. The scripts I'm executing is as simple as this :

#!/usr/bin/env python
import pushybullet as pb
import sys, time, logging

# INIT LOGGING
logging.basicConfig(format='%(asctime)s @%(name)s [%(levelname)s]:    %(message)s', level = logging.DEBUG)

if __name__ == '__main__':
    try:
            logging.info('Custom service started')
            while True:
                    #here for the sake of example, actually doing real stuff here
                    time.sleep(2)
    finally:
            logging.info('Custom service stopped')

And here is the corresponding conf file :

[program:myscript]
directory=/home/pi/Documents/Scripts_py
command=python -u myscript.py
autostart=true
autorestart=true

So I've tested many things based on many researched on google. Replacing logging lines by print and then flushing stdout indeeds works; same with -u option to launche the script. But print is not adequate for my needs, Python's logging module is. So I tried to flush after each logging line, and to launch the script in unbuffered mod, but nothing appears!

Thanks in advance for any help!

1条回答
戒情不戒烟
2楼-- · 2019-08-15 04:12

Thanks to Pedro Rodrigues, I've found. For anyone struggling like me, well just know that you just create a fileHandler like this :

fh = logging.FileHandler('/var/log/supervisor/your_program_name.log') 

And add to your program conf file :

stdout_logfile=/var/log/supervisor/%(program_name)s.log 

The scripts will write in the log, then read by supervisor, visible on the web interface. One issue it might create is a permission denied if you try to start your script without supervisor.

查看更多
登录 后发表回答