4
votes

I'm trying to filter Python logging messages coming over UDP, but for some reason setting loglevel on the receiving end doesn't seem to affect the incoming messages.

The receiving end's code is as follows:

import cPickle
import logging
import socket

logging.basicConfig(format='%(asctime)s %(levelname)-8s %(message)s')
logger = logging.getLogger()
logger.setLevel(logging.INFO)

s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind(('', 51010))

while True:
    d, _ = s.recvfrom(1024)
    log = cPickle.loads(d[4:])
    logger.handle(logging.makeLogRecord(log))

Despite the fact that I've set the logging level to logging.INFO, I am still seeing debug messages. If I add

logging.debug("Debug")
logging.info("Info")

before the while loop, I see the info message, but not the debug one, indicating that the setLevel is working locally, but doesn't affect messages coming over the UDP socket.

Any ideas why this would occur? If I manually check the 'levelno' field of the dict that is received (which is then turned into a log record), it is 10 (debug), but filtering doesn't seem to care...

Thanks!

EDIT:

For reference, the code generating the packets being sent over UDP is simply

import logging
import logging.handlers
import time

logging.basicConfig(level=logging.DEBUG,
    format='%(asctime)s %(levelname)-8s %(message)s')

logging.getLogger().addHandler(logging.handlers.DatagramHandler('', 51010))

while True:
    logging.debug("This shouldn't show up")
    logging.info("This should show up")
    time.sleep(3)
1

1 Answers

3
votes

Logger.handle() is a method that is meant to be called after level checking, which is why the level set on the logger is ineffective. It's generally better to do level setting at the source end (to avoid wasting network bandwidth), or else you can set a level on the handler at the receiving end (not possible using basicConfig(), which is meant for the simplest usages - and your's isn't, IMO). So you can do (on the receiving end):

handler = logging.StreamHandler()
handler.setLevel(logging.INFO)
# setting a Formatter to customise the logs is not shown, but
# you can add it here
logging.getLogger().addHandler(handler)

The above is instead of the basicConfig() call.