Search code examples
pythonpython-2.7syslog

Python 2.7: setlogmask(0) not disabling syslog


I'm a Python newbie, and the following code wrote the following messages to /var/log/syslog

May  8 22:14:22.531833 almach <info>./test.txt: HELLO 01
May  8 22:14:22.531853 almach <info>./test.txt: HELLO 02
May  8 22:14:22.531860 almach <info>./test.txt: HELLO 03

So, why

  1. Messages were written to /var/log/syslog and not ./test.txt?

  2. setlogmask(0) was ineffective, and message "HELLO 02" was written to syslog?

Also, I tested the code in a Linux machine that had demon rsyslogd running, and it might have affected my code somehow.

from syslog import syslog, setlogmask, LOG_INFO, openlog

openlog('./test.txt')

syslog(LOG_INFO, "HELLO 01")

setlogmask(0)
syslog(LOG_INFO, "HELLO 02")

setlogmask(255)
syslog(LOG_INFO, "HELLO 03")

Solution

  • You need to use LOG_MASK(0) to avoid writing HELLO 02 and remember previous value of mask to restore it before writing HELLO 03:

    from syslog import syslog, setlogmask, LOG_INFO, LOG_MASK, openlog
    
    openlog('./test.txt')
    
    syslog(LOG_INFO, "HELLO 01")
    
    mask = setlogmask(LOG_MASK(0))
    syslog(LOG_INFO, "HELLO 02")
    
    setlogmask(mask)
    syslog(LOG_INFO, "HELLO 03")
    

    Result in /var/log/syslog:

    May  9 01:49:39 sanyash-ub16 ./test.txt: HELLO 01
    May  9 01:49:39 sanyash-ub16 ./test.txt: HELLO 03