I would like to directly access to syslog
messages from Python by reading /dev/log
.
My (very limited) understanding is that the correct way is to read from there is to bind a datagram socket.
import socketsock = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM)sock.bind('/dev/log')sock.listen(1)while True:data, addr = sock.recvfrom(1024)print(data)
Apparently /dev/log
is in use:
Traceback (most recent call last):File "readlog.py", line 4, in <module>sock.bind('/dev/log')OSError: [Errno 98] Address already in use
How should I read /dev/log
from Python?
EDIT: per @Barmar's comment - only one process can access /dev/log
so that part is clear, the device must be clean before reading from it. sudo lsof /dev/log
does not show anything.
A answer in a Java thread around this subject mentioned that syslog
should be shut down before. I also tried that, lsof | grep "/dev/log"
was empty but I got the error nevertheless.
Isn't it possible to have several processes reading from /dev/log
?
Best Answer
There is a socket flag to set, in order to prevent this:
socket.SO_REUSEADDR
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
This flag tells the kernel to reuse a local socket in TIME_WAIT state, without waiting for its natural timeout to expire.
Ref: https://docs.python.org/3/library/socket.html