Question

I'm using the logging function inside a module. It works fine on the outside of the function "set" but inside it says that logger is not defined. Help?

from peewee import *
import datetime
import logging
import json

#...

# Start up logging
logger = logging.getLogger(__name__)
logger.info("State library started...")

# ...

def set(module, device, state, attributes=None):
    """ Set the state of the specified device"""
    try:
        acquire_lock(device)
    except:
        #state object doesn't exist yet
        pass
    try:
        state_object = StateTable.select().where(StateTable.device == device).get()
    except:
        state_object = StateTable()

    state_object.device = device
    state_object.state = state
    state_object.attributes = attributes
    state_object.lastChange = datetime.datetime.now()
    state_object.save()
    logger.debug("Setting state for", device, "with state", state, "and attributes", attributes)
    release_lock(device)
    logger.debug("SETTING MQTT STATE")
    attributes_mqtt = {"device" : device, "module" : module, "state" : state, "attributes" : json.loads(attributes)}
    logger.debug("MQTT:", attributes_mqtt)
    mqttc.publish("state", json.dumps(attributes_mqtt))

I've put it on pastie because SO won't let me post the full code.

http://pastie.org/9125006

Was it helpful?

Solution

Hi I according to your code on pastie, the logger is defined outside of the function set (think of it as a variable) therefore for you to use it within a function you have to pass it to the function i.e. the function your definition should be like this

def set(module, device, state, logger, attributes=None):
    """ Set the state of the specified device"""
    try:
            acquire_lock(device)
    except:
            #state object doesn't exist yet
            pass
    try:
            state_object = StateTable.select().where(StateTable.device == device).get()
    except:
            state_object = StateTable()

    state_object.device = device
    state_object.state = state
    state_object.attributes = attributes
    state_object.lastChange = datetime.datetime.now()
    state_object.save()
    logger.debug("Setting state for", device, "with state", state, "and attributes", attributes)
    release_lock(device)
    logger.debug("SETTING MQTT STATE")
    attributes_mqtt = {"device" : device, "module" : module, "state" : state, "attributes" : json.loads(attributes)}
    logger.debug("MQTT:", attributes_mqtt)
    mqttc.publish("state", json.dumps(attributes_mqtt))

then when you call the set function pass the logger as a parameter.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top