1

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")
Andre K
  • 185
  • 1
  • 10
  • 1
    You cannot `setlogmask(0)`. The mask must be a bitwise combination of the [symbolic constants](https://docs.python.org/3.3/library/syslog.html). – DYZ May 08 '19 at 22:44

2 Answers2

2

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
sanyassh
  • 8,100
  • 13
  • 36
  • 70
1

From syslog.openlog manual:

The optional ident keyword argument is a string which is prepended to every message, and defaults to sys.argv[0] with leading path components stripped

To save logs in a separate file, use logging.handlers.SysLogHandler: How to configure logging to syslog in Python?

a small orange
  • 560
  • 2
  • 16