syslog.LOG_DEBUG

Here are the examples of the python api syslog.LOG_DEBUG taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

55 Examples 7

Example 1

Project: cve-portal
Source File: notif.py
View license
@notif_blueprint.route('/delnotif', methods=['GET', 'POST'])
@login_required
def delnotif():
    row = models.Notification.query.filter_by(id=request.json).first()
    models.db.session.delete(row)
    models.db.session.commit()
    flash('Notification removed ', 'info')
    syslog.syslog(syslog.LOG_DEBUG, "Notification deleted: " + current_user.email)
    return redirect(url_for("notif.notiftab"))

Example 2

Project: laikaboss
Source File: laikamilter.py
View license
    def envrcpt(self,to,*str):
        try:
            self.CUSTOMORCPT.append(to)
            log = self.uuid+" envRcpt: "
            rcpt = ' '.join(self.CUSTOMORCPT)
            log += rcpt
            self.logger.writeLog(syslog.LOG_DEBUG, "%s"%(log))
            self.receiver = rcpt
            self.receiver = self.receiver.replace("<", "") # clean the first "<" off the string 
            self.receiver = self.receiver.replace(">", "")
        except:
            log = self.uuid+" Uncaught Exception in EnvRcpt"
            self.logger.writeLog(syslog.LOG_ERR, "%s"%(str(log)))
        return Milter.CONTINUE

Example 3

Project: laikaboss
Source File: laikamilter.py
View license
    def hello(self, heloname):
        returnval = Milter.CONTINUE
        try:
            self.logger.writeLog(syslog.LOG_DEBUG, "%s hello:%s client_addr:%s if_addr:%s" %(self.uuid, str(heloname), str(self._getClientAddr()), str(self._getIfAddr())))
            self.CUSTOMHELO = heloname
        except:
            log = self.uuid+" Uncaught Exception in Hello"
            self.logger.writeLog(syslog.LOG_ERR, "%s"%(str(log)))
        return returnval

Example 4

Project: karaka
Source File: api.py
View license
def _dbg(s): _log(syslog.LOG_DEBUG, s)
##
## End
##

from apiconfig import APIConfig

Example 5

Project: laikaboss
Source File: laikamilter.py
View license
    def abort(self):
        try:
            #Try sending it to EOM for scanning and disposition.
            log = self.uuid+" Aborted QID: "+self.qid+" Attempting to send to direct to EOM"
            self.logger.writeLog(syslog.LOG_DEBUG, "%s"%(str(log)))
            self.eom()
        except:
            log = self.uuid+" Uncaught Exception in Abort"
            self.logger.writeLog(syslog.LOG_ERR, "%s"%(str(log)))
        
        return Milter.CONTINUE

Example 6

Project: laikaboss
Source File: laikamilter.py
View license
    def _zmqGetFlags(self, numRetries, milterContext):
        REQUEST_TIMEOUT = milterContext.milterConfig.zmqTimeout
        gotResponseFromScanner=-1
        if (len(self.milterConfig.servers)>0):#servers Available
            SERVER_ENDPOINT = self._getNextScanServer()
            gotResponseFromScanner=-1 #Default No Response
            gotResponseFromScanner = self._zmqSendBuffer(milterContext, numRetries, REQUEST_TIMEOUT, SERVER_ENDPOINT)
        else:
            log = "No Scan Servers Defined"
            self.logger.writeLog(syslog.LOG_DEBUG, "%s"%(str(log)))
        
        return gotResponseFromScanner

Example 7

Project: mythbox
Source File: test_syslog.py
View license
    def test_emitCustomPriority(self):
        """
        L{SyslogObserver.emit} uses the value of the C{'syslogPriority'} as the
        syslog priority, if that key is present in the event dictionary.
        """
        self.observer.emit({
                'message': ('hello, world',), 'isError': False, 'system': '-',
                'syslogPriority': stdsyslog.LOG_DEBUG})
        self.assertEqual(
            self.events,
            [(stdsyslog.LOG_DEBUG, '[-] hello, world')])

Example 8

Project: backintime
Source File: logger.py
View license
def debug(msg, parent = None, traceDepth = 0):
    if DEBUG:
        msg = '%s %s' %(_debugHeader(parent, traceDepth), msg)
        print('%sDEBUG%s: %s' %(bcolors.OKBLUE, bcolors.ENDC, msg), file = sys.stdout)
        for line in tools.wrapLine(msg):
            syslog.syslog(syslog.LOG_DEBUG, 'DEBUG: %s' %line)

Example 9

Project: karaka
Source File: api.py
View license
def _dbg(s): _log(syslog.LOG_DEBUG, s)
##
## End
##

from apiconfig import APIConfig

Example 10

Project: laikaboss
Source File: laikamilter.py
View license
    def abort(self):
        try:
            #Try sending it to EOM for scanning and disposition.
            log = self.uuid+" Aborted QID: "+self.qid+" Attempting to send to direct to EOM"
            self.logger.writeLog(syslog.LOG_DEBUG, "%s"%(str(log)))
            self.eom()
        except:
            log = self.uuid+" Uncaught Exception in Abort"
            self.logger.writeLog(syslog.LOG_ERR, "%s"%(str(log)))
        
        return Milter.CONTINUE

Example 11

Project: oslo.log
Source File: handlers.py
View license
        def emit(self, record):
            priority = self.severity_map.get(record.levelname,
                                             syslog.LOG_DEBUG)
            message = encodeutils.safe_encode(self.format(record))

            syslog.syslog(priority, message)

Example 12

Project: laikaboss
Source File: laikamilter.py
View license
    def hello(self, heloname):
        returnval = Milter.CONTINUE
        try:
            self.logger.writeLog(syslog.LOG_DEBUG, "%s hello:%s client_addr:%s if_addr:%s" %(self.uuid, str(heloname), str(self._getClientAddr()), str(self._getIfAddr())))
            self.CUSTOMHELO = heloname
        except:
            log = self.uuid+" Uncaught Exception in Hello"
            self.logger.writeLog(syslog.LOG_ERR, "%s"%(str(log)))
        return returnval

Example 13

Project: laikaboss
Source File: laikamilter.py
View license
    def _zmqGetFlags(self, numRetries, milterContext):
        REQUEST_TIMEOUT = milterContext.milterConfig.zmqTimeout
        gotResponseFromScanner=-1
        if (len(self.milterConfig.servers)>0):#servers Available
            SERVER_ENDPOINT = self._getNextScanServer()
            gotResponseFromScanner=-1 #Default No Response
            gotResponseFromScanner = self._zmqSendBuffer(milterContext, numRetries, REQUEST_TIMEOUT, SERVER_ENDPOINT)
        else:
            log = "No Scan Servers Defined"
            self.logger.writeLog(syslog.LOG_DEBUG, "%s"%(str(log)))
        
        return gotResponseFromScanner

Example 14

View license
    def test_emitCustomPriority(self):
        """
        L{SyslogObserver.emit} uses the value of the C{'syslogPriority'} as the
        syslog priority, if that key is present in the event dictionary.
        """
        self.observer.emit({
                'message': ('hello, world',), 'isError': False, 'system': '-',
                'syslogPriority': stdsyslog.LOG_DEBUG})
        self.assertEqual(
            self.events,
            [(stdsyslog.LOG_DEBUG, '[-] hello, world')])

Example 15

Project: mythbox
Source File: test_syslog.py
View license
    def test_emitCustomPriority(self):
        """
        L{SyslogObserver.emit} uses the value of the C{'syslogPriority'} as the
        syslog priority, if that key is present in the event dictionary.
        """
        self.observer.emit({
                'message': ('hello, world',), 'isError': False, 'system': '-',
                'syslogPriority': stdsyslog.LOG_DEBUG})
        self.assertEqual(
            self.events,
            [(stdsyslog.LOG_DEBUG, '[-] hello, world')])

Example 16

View license
    def test_emitCustomPriority(self):
        """
        L{SyslogObserver.emit} uses the value of the C{'syslogPriority'} as the
        syslog priority, if that key is present in the event dictionary.
        """
        self.observer.emit({
                'message': ('hello, world',), 'isError': False, 'system': '-',
                'syslogPriority': stdsyslog.LOG_DEBUG})
        self.assertEqual(
            self.events,
            [(stdsyslog.LOG_DEBUG, '[-] hello, world')])

Example 17

Project: laikaboss
Source File: laikamilter.py
View license
    def envrcpt(self,to,*str):
        try:
            self.CUSTOMORCPT.append(to)
            log = self.uuid+" envRcpt: "
            rcpt = ' '.join(self.CUSTOMORCPT)
            log += rcpt
            self.logger.writeLog(syslog.LOG_DEBUG, "%s"%(log))
            self.receiver = rcpt
            self.receiver = self.receiver.replace("<", "") # clean the first "<" off the string 
            self.receiver = self.receiver.replace(">", "")
        except:
            log = self.uuid+" Uncaught Exception in EnvRcpt"
            self.logger.writeLog(syslog.LOG_ERR, "%s"%(str(log)))
        return Milter.CONTINUE

Example 18

Project: laikaboss
Source File: laikamilter.py
View license
    def eom(self):
        try:
            self._getQID()
            checklist = "%s_%s" %(str(self._getIfAddr()), str(self._getClientAddr()))
            if checklist in global_whitelist:
                self.logger.writeLog(syslog.LOG_DEBUG, "%s ACCEPT ON WHITELIST: qid:%s client_addr:%s if_addr:%s" %(self.uuid, str(self.qid), str(self._getClientAddr()), str(self._getIfAddr())))
                self.rtnToMTA = Milter.ACCEPT
            else:
                if not self.alreadyScanned:
                    self._getBufferFromFP()#build the header
                    self._generateArchiveFileName()
                    self.rtnToMTA = self._dispositionMessage()
                    self.fph.write("%s: %s\n"%(self.milterConfig.MailscanResultHeaderString,self.disposition))
                    self.fph.write("%s: %s\n"%("X-Flags",self.rulesMatched))
                    self._getBufferFromFP()#Rebuild the buffer with the result header
                    self.fph.close()
                    self.fpb.close()
                    self._writeFileToDisk()
                    self._addHeaders()
                    self._logDetails()
                    self._logEachEnvelope()
                    log = self.uuid+" "+self.qid+" response "+ self.milterConfig._unconvertDispositionMode(self.rtnToMTA)
                    self.logger.writeLog(syslog.LOG_DEBUG, "%s"%(str(log)))
                    self.alreadyScanned = True
                else:
                    log = self.uuid+" File "+self.archiveFileName+" Already scanned"
                    self.logger.writeLog(syslog.LOG_DEBUG, "%s"%(str(log)))
        except Exception as e:
            exc_type, exc_value, exc_traceback = sys.exc_info()
            ERROR_INFO = repr(traceback.format_exception(exc_type, exc_value, exc_traceback))
            ERROR =  "%s ERROR EOM: RETURNING DEFAULT (%s)   %s" % (self.uuid, self.rtnToMTA, ERROR_INFO)
            print ERROR
            self.logger.writeLog(syslog.LOG_ERR, "%s"%(str(ERROR)))
        return self.rtnToMTA

Example 19

Project: laikaboss
Source File: laikamilter.py
View license
    def eom(self):
        try:
            self._getQID()
            checklist = "%s_%s" %(str(self._getIfAddr()), str(self._getClientAddr()))
            if checklist in global_whitelist:
                self.logger.writeLog(syslog.LOG_DEBUG, "%s ACCEPT ON WHITELIST: qid:%s client_addr:%s if_addr:%s" %(self.uuid, str(self.qid), str(self._getClientAddr()), str(self._getIfAddr())))
                self.rtnToMTA = Milter.ACCEPT
            else:
                if not self.alreadyScanned:
                    self._getBufferFromFP()#build the header
                    self._generateArchiveFileName()
                    self.rtnToMTA = self._dispositionMessage()
                    self.fph.write("%s: %s\n"%(self.milterConfig.MailscanResultHeaderString,self.disposition))
                    self.fph.write("%s: %s\n"%("X-Flags",self.rulesMatched))
                    self._getBufferFromFP()#Rebuild the buffer with the result header
                    self.fph.close()
                    self.fpb.close()
                    self._writeFileToDisk()
                    self._addHeaders()
                    self._logDetails()
                    self._logEachEnvelope()
                    log = self.uuid+" "+self.qid+" response "+ self.milterConfig._unconvertDispositionMode(self.rtnToMTA)
                    self.logger.writeLog(syslog.LOG_DEBUG, "%s"%(str(log)))
                    self.alreadyScanned = True
                else:
                    log = self.uuid+" File "+self.archiveFileName+" Already scanned"
                    self.logger.writeLog(syslog.LOG_DEBUG, "%s"%(str(log)))
        except Exception as e:
            exc_type, exc_value, exc_traceback = sys.exc_info()
            ERROR_INFO = repr(traceback.format_exception(exc_type, exc_value, exc_traceback))
            ERROR =  "%s ERROR EOM: RETURNING DEFAULT (%s)   %s" % (self.uuid, self.rtnToMTA, ERROR_INFO)
            print ERROR
            self.logger.writeLog(syslog.LOG_ERR, "%s"%(str(ERROR)))
        return self.rtnToMTA

Example 20

Project: catflap-camera
Source File: camera.py
View license
    def catflap_callback(self, pin):
        """
        This function is called by the RPi.GPIO library when an interrupt
        occurs, set up by the add_event_detect call in __init__.

        Interrupts are very efficient compared to polling for low latency
        applications - we don't want delay between the cat appearing and
        the shutter on the camera!
        """
        # When was the interrupt triggered?
        time_now = time.time()
        # Read and store the current state of the pin - high or low
        current_value = GPIO.input(pin)
        # Log the event
        syslog.syslog(syslog.LOG_DEBUG,
                      "GPIO event (%s) - time_now %s, last activation at %s"
                      % (GPIO.input(pin), time_now, self.time_stamp))
        if current_value == GPIO.LOW:
            # If the pin is low, the flap is closed!

            # Turn off the camera LED
            self.camera.led = False

            # Take a note
            syslog.syslog(syslog.LOG_DEBUG, "Flap closed at %s" % time.time())

        elif current_value == GPIO.HIGH:
            # If the pin is high, the flap has opened!
            # But it might be the case that we already saw the flap open and
            # what we're actually seeing is the flap swinging past the sensor
            # as it settles back down to close. Let's check!
            syslog.syslog(syslog.LOG_DEBUG, "Flap opened at %s" % time.time())
            if (time_now - self.time_stamp) >= 2:
                # If it's been two seconds since we last saw a flap open event
                # then we're interested in this one as a new event

                # Let's store the time this event happened
                self.time_stamp = time_now

                # Log it!
                syslog.syslog(syslog.LOG_INFO, "Taking a picture of a cat!")

                # We're going to turn on the camera light
                self.camera.led = True

                # Now we generate a filename based on the time, for instance
                # 20141007-200000.jpg (8pm Oct 7th 2014). This means we can
                # easily find out when a specific photo was taken!
                filename = "%s.jpg" % time.strftime("%Y%m%d-%H%M%S")
                # Now we prepend the filename with the path we're using
                # to store all our photos - in this case, /srv/cats
                final_path = "/srv/cats/%s" % filename

                # We're using the camera instance given to the class initially
                # which is being held open and ready for us - all we need
                # to do is ask it to capture an image to a path.
                # We configure the camera when we set up this class below.
                self.camera.capture(final_path)

                # Let syslog know for debugging purposes
                syslog.syslog(syslog.LOG_DEBUG, "Captured image %s at %s"
                              % (filename, time_now))
            else:
                # If it's been less than two seconds since the last cat,
                # this is probably just the flap swinging past the sensor

                # But keep a record to help us figure out problems
                syslog.syslog(syslog.LOG_INFO, "Debounce filtered an event")

Example 21

Project: privacyidea
Source File: privacyidea_apache.py
View license
def check_password(environ, username, password):
    PRIVACYIDEA, REDIS, SSLVERIFY = _get_config()
    syslog.syslog(syslog.LOG_DEBUG, "Authentication with {0!s}, {1!s}, {2!s}".format(
        PRIVACYIDEA, REDIS, SSLVERIFY))
    r_value = UNAUTHORIZED
    rd = redis.Redis(REDIS)
    seconds = 300  # 5 minutes timeout

    # check, if the user already exists in the database.
    key = _generate_key(username, environ)
    value = rd.get(key)
    if value and passlib.hash.pbkdf2_sha512.verify(password, value):
        # update the timeout
        rd.setex(key, _generate_digest(password), seconds)
        r_value = OK

    else:
        # Check against privacyidea
        data = {"user": username,
                "pass": password}
        response = requests.post(PRIVACYIDEA + "/validate/check", data=data,
                                 verify=SSLVERIFY)

        if response.status_code == 200:
            try:
                json_response = response.json()
                syslog.syslog(syslog.LOG_DEBUG, "requests > 1.0")
            except Exception as exx:
                # requests < 1.0
                json_response = response.json
                syslog.syslog(syslog.LOG_DEBUG, "requests < 1.0")
                syslog.syslog(syslog.LOG_DEBUG, "{0!s}".format(traceback.format_exc()))

            if json_response.get("result", {}).get("value"):
                rd.setex(key, _generate_digest(password), seconds)
                r_value = OK
        else:
            syslog.syslog(syslog.LOG_ERR, "Error connecting to privacyIDEA: "
                                          "%s: %s" % (response.status_code,
                                                      response.text))

    return r_value

Example 22

Project: laikaboss
Source File: laikamilter.py
View license
    def _checkOKToContinueWithOpenFiles(self):
        okToContinue = True
        
        try:
            pid = os.getpid()
            try:
                fd_dir=os.path.join('/proc/', str(pid), 'fd/')
            except:
                self.logger.writeLog(syslog.LOG_DEBUG, "Open Files:  Problem With PID: "+str(pid))
            numOpenFilesOutput = 0
            for file in os.listdir(fd_dir):
                numOpenFilesOutput += 1
            if (int(numOpenFilesOutput) > int(self.milterConfig.maxFiles)):
                self.logger.writeLog(syslog.LOG_ERR, "Open Files: "+str(numOpenFilesOutput)+", Returning "+str(self.milterConfig.dispositionModes["OverLimit".lower()])+" to avoid shutdown at "+str(self.milterConfig.maxFiles))
                okToContinue = False
            else:
                self.logger.writeLog(syslog.LOG_DEBUG, self.milterConfig.milterInstance+" Open Files: "+str(numOpenFilesOutput)+ " of "+ str(self.milterConfig.maxFiles))
        except ValueError:
            self.logger.writeLog(syslog.LOG_ERR, "Value Error in checkOpenFiles")
        except Exception as e:
            exc_type, exc_value, exc_traceback = sys.exc_info()
            print "ERROR EOM  %s" % (repr(traceback.format_exception(exc_type, exc_value, exc_traceback)))
            self.logger.writeLog(syslog.LOG_ERR, "Error in checkOpenFiles")
        return okToContinue

Example 23

Project: pycopia
Source File: logging.py
View license
def debug(msg):
    syslog.syslog(syslog.LOG_DEBUG, _encode(msg))

Example 24

Project: laikaboss
Source File: laikamilter.py
View license
    def unknown(self, cmd):
        log = self.uuid+" Unknown Callback Received: "+str(cmd)
        self.logger.writeLog(syslog.LOG_DEBUG, "%s"%(str(log)))
        return Milter.CONTINUE

Example 25

Project: pycopia
Source File: logging.py
View license
def loglevel_debug():
    loglevel(syslog.LOG_DEBUG)

Example 26

Project: laikaboss
Source File: laikamilter.py
View license
    def envfrom(self,f,*str):
        try:
            if self.CUSTOMFROM != "": #If anything is left over from the last email, re -initialize.
                self.__init__()
            self.startTime = time.time()
            self.startTimeDT = datetime.datetime.now()
            if (self.milterConfig.mode == "shutdown"):
                log = self.uuid+" Milter in Maint mode, returning [Sender:"+''.join(f)+"]" 
                self.logger.writeLog(syslog.LOG_DEBUG, "%s"%(log))
                return self.milterConfig.dispositionModes["InMaintMode".lower()] 
            
            log = self.uuid+" envFrom: "
            log += ''.join(f)
            self.logger.writeLog(syslog.LOG_DEBUG, "%s"%(log))
            self.CUSTOMFROM = f
            
            self.CUSTOMFROM = self.CUSTOMFROM.replace("<", "")
            self.CUSTOMFROM = self.CUSTOMFROM.replace(">", "")
            
            self.sender = self.CUSTOMFROM
            
            self.fph = StringIO.StringIO()
            self.fpb = StringIO.StringIO()
            
        except:
            log = self.uuid+" Uncaught Exception in EnvFrom"
            self.logger.writeLog(syslog.LOG_ERR, "%s"%(str(log)))
        return Milter.CONTINUE    #ALWAYS continue to gather the entire email

Example 27

Project: pycopia
Source File: logging.py
View license
def debug(msg):
    syslog.syslog(syslog.LOG_DEBUG, _encode(msg))

Example 28

Project: laikaboss
Source File: laikamilter.py
View license
    def _checkOKToContinueWithOpenFiles(self):
        okToContinue = True
        
        try:
            pid = os.getpid()
            try:
                fd_dir=os.path.join('/proc/', str(pid), 'fd/')
            except:
                self.logger.writeLog(syslog.LOG_DEBUG, "Open Files:  Problem With PID: "+str(pid))
            numOpenFilesOutput = 0
            for file in os.listdir(fd_dir):
                numOpenFilesOutput += 1
            if (int(numOpenFilesOutput) > int(self.milterConfig.maxFiles)):
                self.logger.writeLog(syslog.LOG_ERR, "Open Files: "+str(numOpenFilesOutput)+", Returning "+str(self.milterConfig.dispositionModes["OverLimit".lower()])+" to avoid shutdown at "+str(self.milterConfig.maxFiles))
                okToContinue = False
            else:
                self.logger.writeLog(syslog.LOG_DEBUG, self.milterConfig.milterInstance+" Open Files: "+str(numOpenFilesOutput)+ " of "+ str(self.milterConfig.maxFiles))
        except ValueError:
            self.logger.writeLog(syslog.LOG_ERR, "Value Error in checkOpenFiles")
        except Exception as e:
            exc_type, exc_value, exc_traceback = sys.exc_info()
            print "ERROR EOM  %s" % (repr(traceback.format_exception(exc_type, exc_value, exc_traceback)))
            self.logger.writeLog(syslog.LOG_ERR, "Error in checkOpenFiles")
        return okToContinue

Example 29

Project: rolekit
Source File: logger.py
View license
    def write(self, data, level, logger, is_debug=0):
        priority = None
        if is_debug:
            priority = syslog.LOG_DEBUG
        else:
            if level >= logger.INFO1:
                priority = syslog.LOG_INFO
            elif level == logger.WARNING:
                priority = syslog.LOG_WARNING
            elif level == logger.ERROR:
                priority = syslog.LOG_ERR
            elif level == logger.FATAL:
                priority = syslog.LOG_CRIT

        if data.endswith("\n"):
            data = data[:len(data)-1]
        if len(data) > 0:
            if priority == None:
                syslog.syslog(data)
            else:
                syslog.syslog(priority, data)

Example 30

Project: laikaboss
Source File: laikamilter.py
View license
    def _zmqSendBuffer(self, milterContext,numRetries, REQUEST_TIMEOUT,SERVER_ENDPOINT):
        gotResponseFromScanner=-1
        self.client = Client(SERVER_ENDPOINT)
        
        log = milterContext.uuid+" Sending "+ str(milterContext.qid)+" to "+ SERVER_ENDPOINT
        self.logger.writeLog(syslog.LOG_DEBUG, "%s"%(str(log)))
        myhostname = socket.gethostname()
        externalObject = ExternalObject(
                                        buffer=milterContext.fileBuffer, 
                                        externalVars=ExternalVars(
                                                                  filename=milterContext.archiveFileName, 
                                                                  source=milterContext.milterConfig.milterName+"-"+str(myhostname[:myhostname.index(".")]),
                                                                  ephID=milterContext.qid,
                                                                  uniqID=milterContext.messageID
                                                                 ),
                                        level=level_metadata
                                        )
        result = self.client.send(externalObject, retry=numRetries, timeout=REQUEST_TIMEOUT)
        if result:
            self.match  = flagRollup(result)
            if not self.match:
                self.match = []
            self.attachements  = ','.join(getAttachmentList(result))
            strScanResult = finalDispositionFromResult(result)
            strScanResults= " ".join(dispositionFromResult(result))
            if strScanResult:
                self.strScanResult = strScanResult
            try:
                self.dispositions  = strScanResults
            except:
                self.logger.writeLog(syslog.LOG_ERR, milterContext.uuid+" ERROR getting dispositions via client lib")
            gotResponseFromScanner=1
        else:
            self.logger.writeLog(syslog.LOG_ERR, milterContext.uuid+" "+str(milterContext.qid)+"| no result object from scanner, returning SCAN ERROR")
        
        return gotResponseFromScanner

Example 31

Project: weewx
Source File: pmon.py
View license
def logdbg(msg):
    logmsg(syslog.LOG_DEBUG, msg)

Example 32

Project: pakrat
Source File: log.py
View license
def trace(message):
    """ Record a trace message """
    write(syslog.LOG_DEBUG, 'trace: %s' % message)

Example 33

Project: laikaboss
Source File: laikamilter.py
View license
    def _logDetails(self):
        log = self.uuid+" Flags: %s" % self.rulesMatched
        self.logger.writeLog(syslog.LOG_DEBUG, "%s"%(str(log)))

Example 34

Project: yum
Source File: yum-updatesd.py
View license
    def updatesAvailable(self, updateInfo):
        """Emit a message stating that updates are available.

        :param updateInfo: a list of tuples of dictionaries.  Each
           dictionary contains information about a package, and each
           tuple specifies an available upgrade: the second dictionary
           in the tuple has information about a package that is
           currently installed, and the first dictionary has
           information what the package can be upgraded to
        """
        num = len(updateInfo)
        level = self.level
        if num > 1:
            msg = "%d updates available" %(num,)
        elif num == 1:
            msg = "1 update available"
        else:
            msg = "No updates available"
            level = syslog.LOG_DEBUG

        syslog.syslog(self._levelMap(level), msg)

Example 35

Project: cve-portal
Source File: notif.py
View license
@notif_blueprint.route('/addnotif', methods=['GET', 'POST'])
@login_required
def addnotif():
    if request.json['allversion'] is True and request.json['allproduct'] is False:
        notification = models.Notification(user_id=current_user.id,
                                           vendor=escape(request.json['queryvendor'].lower()),
                                           product=escape(request.json['queryproduct'].lower()),
                                           version='')

    elif request.json['allproduct'] is True:
        notification = models.Notification(user_id=current_user.id,
                                           vendor=escape(request.json['queryvendor'].lower()),
                                           product='',
                                           version='')
    else:
        notification = models.Notification(user_id=current_user.id,
                                           vendor=escape(request.json['queryvendor'].lower()),
                                           product=escape(request.json['queryproduct'].lower()),
                                           version=escape(request.json['queryversion'].lower()))

    # Checking Integrity Before Insert  #
    if models.Notification.query.filter_by(user_id=notification.user_id,
                                           vendor=notification.vendor,
                                           product=notification.product,
                                           version=notification.version).first() is None:
        models.db.session.add(notification)
        models.db.session.commit()
        flash('Notification Successfully Created.', 'success')
        syslog.syslog(syslog.LOG_DEBUG, "New notification created by: " + current_user.email)
        return redirect(url_for("notif.notiftab"))

    else:
        flash('Notification Already existing.', 'warning')
        syslog.syslog(syslog.LOG_ERR, "Notification Already existing: " + current_user.email)
        return redirect(url_for("notif.notiftab"))

Example 36

Project: laikaboss
Source File: __init__.py
View license
def log_debug(message):
    syslog.syslog(syslog.LOG_DEBUG, "DEBUG %s" % message)

Example 37

Project: laikaboss
Source File: laikamilter.py
View license
    def _zmqSendBuffer(self, milterContext,numRetries, REQUEST_TIMEOUT,SERVER_ENDPOINT):
        gotResponseFromScanner=-1
        self.client = Client(SERVER_ENDPOINT)
        
        log = milterContext.uuid+" Sending "+ str(milterContext.qid)+" to "+ SERVER_ENDPOINT
        self.logger.writeLog(syslog.LOG_DEBUG, "%s"%(str(log)))
        myhostname = socket.gethostname()
        externalObject = ExternalObject(
                                        buffer=milterContext.fileBuffer, 
                                        externalVars=ExternalVars(
                                                                  filename=milterContext.archiveFileName, 
                                                                  source=milterContext.milterConfig.milterName+"-"+str(myhostname[:myhostname.index(".")]),
                                                                  ephID=milterContext.qid,
                                                                  uniqID=milterContext.messageID
                                                                 ),
                                        level=level_metadata
                                        )
        result = self.client.send(externalObject, retry=numRetries, timeout=REQUEST_TIMEOUT)
        if result:
            self.match  = flagRollup(result)
            if not self.match:
                self.match = []
            self.attachements  = ','.join(getAttachmentList(result))
            strScanResult = finalDispositionFromResult(result)
            strScanResults= " ".join(dispositionFromResult(result))
            if strScanResult:
                self.strScanResult = strScanResult
            try:
                self.dispositions  = strScanResults
            except:
                self.logger.writeLog(syslog.LOG_ERR, milterContext.uuid+" ERROR getting dispositions via client lib")
            gotResponseFromScanner=1
        else:
            self.logger.writeLog(syslog.LOG_ERR, milterContext.uuid+" "+str(milterContext.qid)+"| no result object from scanner, returning SCAN ERROR")
        
        return gotResponseFromScanner

Example 38

Project: laikaboss
Source File: laikamilter.py
View license
    def _logDetails(self):
        log = self.uuid+" Flags: %s" % self.rulesMatched
        self.logger.writeLog(syslog.LOG_DEBUG, "%s"%(str(log)))

Example 39

Project: pycopia
Source File: logging.py
View license
def loglevel_debug():
    loglevel(syslog.LOG_DEBUG)

Example 40

Project: fuzzy-archer
Source File: historygenerator.py
View license
    def __init__(self, generator):
        SearchList.__init__(self, generator)

        self.table_dict = generator.skin_dict['HistoryReport']

        # Calculate the tables once every refresh_interval mins
        self.refresh_interval = int(self.table_dict.get('refresh_interval', 5))
        self.cache_time = 0

        self.search_list_extension = {}

        # Make bootstrap specific labels in config file available to
        if 'BootstrapLabels' in generator.skin_dict:
            self.search_list_extension['BootstrapLabels'] = generator.skin_dict['BootstrapLabels']
        else:
            syslog.syslog(syslog.LOG_DEBUG, "%s: No bootstrap specific labels found" % os.path.basename(__file__))

        # Make observation labels available to templates
        if 'Labels' in generator.skin_dict:
            self.search_list_extension['Labels'] = generator.skin_dict['Labels']
        else:
            syslog.syslog(syslog.LOG_DEBUG, "%s: No observation labels found" % os.path.basename(__file__))

Example 41

Project: rolekit
Source File: logger.py
View license
    def write(self, data, level, logger, is_debug=0):
        priority = None
        if is_debug:
            priority = syslog.LOG_DEBUG
        else:
            if level >= logger.INFO1:
                priority = syslog.LOG_INFO
            elif level == logger.WARNING:
                priority = syslog.LOG_WARNING
            elif level == logger.ERROR:
                priority = syslog.LOG_ERR
            elif level == logger.FATAL:
                priority = syslog.LOG_CRIT

        if data.endswith("\n"):
            data = data[:len(data)-1]
        if len(data) > 0:
            if priority == None:
                syslog.syslog(data)
            else:
                syslog.syslog(priority, data)

Example 42

Project: karaka
Source File: common.py
View license
def _dbg(s): _log(syslog.LOG_DEBUG, s)

class OperationAborted(Exception): pass

Example 43

Project: laikaboss
Source File: laikad.py
View license
def log_debug(message):
    '''Log a debug message'''
    syslog.syslog(syslog.LOG_DEBUG, "DEBUG (%s) %s" % (os.getpid(), message))

Example 44

Project: karaka
Source File: common.py
View license
def _dbg(s): _log(syslog.LOG_DEBUG, s)

class OperationAborted(Exception): pass

Example 45

Project: laikaboss
Source File: __init__.py
View license
def log_debug(message):
    syslog.syslog(syslog.LOG_DEBUG, "DEBUG %s" % message)

Example 46

Project: firewalld
Source File: logger.py
View license
    def write(self, data, level, logger, is_debug=0):
        priority = None
        if is_debug:
            priority = syslog.LOG_DEBUG
        else:
            if level >= logger.INFO1:
                priority = syslog.LOG_INFO
            elif level == logger.WARNING:
                priority = syslog.LOG_WARNING
            elif level == logger.ERROR:
                priority = syslog.LOG_ERR
            elif level == logger.FATAL:
                priority = syslog.LOG_CRIT

        if data.endswith("\n"):
            data = data[:len(data)-1]
        if len(data) > 0:
            if priority is None:
                syslog.syslog(data)
            else:
                syslog.syslog(priority, data)

Example 47

Project: cve-portal
Source File: notif.py
View license
@notif_blueprint.route('/searchnotif', methods=['GET', 'POST'])
@login_required
def searchnotif():
    notification = models.Notification(user_id=current_user.id,
                                       fulltxt=True,
                                       vendor=escape(request.json['searchquery']),
                                       product='',
                                       version='')
    # Checking Integrity Before Insert  #
    if models.Notification.query.filter_by(user_id=notification.user_id,
                                           vendor=notification.vendor,
                                           fulltxt=notification.fulltxt).first() is None:
        models.db.session.add(notification)
        models.db.session.commit()
        flash('Notification Successfully Created.', 'success')
        syslog.syslog(syslog.LOG_DEBUG, "New notification created by: " + current_user.email)
        return redirect(url_for("notif.notiftab"))
    else:
        flash('Notification Already existing.', 'warning')
        syslog.syslog(syslog.LOG_ERR, "Notification Already existing: " + current_user.email)
        return redirect(url_for("notif.notiftab"))

Example 48

Project: laikaboss
Source File: laikad.py
View license
def log_debug(message):
    '''Log a debug message'''
    syslog.syslog(syslog.LOG_DEBUG, "DEBUG (%s) %s" % (os.getpid(), message))

Example 49

Project: exabgp
Source File: bgp.py
View license
def main ():
	options = docopt.docopt(usage, help=False)

	major = int(sys.version[0])
	minor = int(sys.version[2])

	if major != 2 or minor < 5:
		sys.exit('This program can not work (is not tested) with your python version (< 2.5 or >= 3.0)')

	if options["--version"]:
		print 'ExaBGP : %s' % version
		print 'Python : %s' % sys.version.replace('\n',' ')
		print 'Uname  : %s' % ' '.join(platform.uname()[:5])
		sys.exit(0)

	if options["--folder"]:
		folder = os.path.realpath(os.path.normpath(options["--folder"]))
	elif sys.argv[0].endswith('/bin/exabgp'):
		folder = sys.argv[0][:-len('/bin/exabgp')] + '/etc/exabgp'
	elif sys.argv[0].endswith('/sbin/exabgp'):
		folder = sys.argv[0][:-len('/sbin/exabgp')] + '/etc/exabgp'
	else:
		folder = '/etc/exabgp'

	os.environ['EXABGP_ETC'] = folder  # This is not most pretty

	if options["--run"]:
		sys.argv = sys.argv[sys.argv.index('--run')+1:]
		if sys.argv[0] == 'healthcheck':
			from exabgp.application import run_healthcheck
			run_healthcheck()
		elif sys.argv[0] == 'cli':
			from exabgp.application import run_cli
			run_cli()
		else:
			print(usage)
			sys.exit(0)
		return

	envfile = 'exabgp.env' if not options["--env"] else options["--env"]
	if not envfile.startswith('/'):
		envfile = '%s/%s' % (folder, envfile)

	from exabgp.configuration.setup import environment

	try:
		env = environment.setup(envfile)
	except environment.Error,exc:
		print usage
		print '\nconfiguration issue,', str(exc)
		sys.exit(1)

	# Must be done before setting the logger as it modify its behaviour

	if options["--debug"]:
		env.log.all = True
		env.log.level = syslog.LOG_DEBUG

	logger = Logger()

	named_pipe = os.environ.get('NAMED_PIPE','')
	if named_pipe:
		from exabgp.application.control import main as control
		control(named_pipe)
		sys.exit(0)

	if options["--decode"]:
		decode = ''.join(options["--decode"]).replace(':','').replace(' ','')
		if not is_bgp(decode):
			print usage
			print 'Environment values are:\n' + '\n'.join(' - %s' % _ for _ in environment.default())
			print ""
			print "The BGP message must be an hexadecimal string."
			print ""
			print "All colons or spaces are ignored, for example:"
			print ""
			print "  --decode 001E0200000007900F0003000101"
			print "  --decode 001E:02:0000:0007:900F:0003:0001:01"
			print "  --decode FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF001E0200000007900F0003000101"
			print "  --decode FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF:001E:02:0000:0007:900F:0003:0001:01"
			print "  --decode 'FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF 001E02 00000007900F0003000101'"
			sys.exit(1)
	else:
		decode = ''

	# Make sure our child has a named pipe name
	if env.api.file:
		os.environ['NAMED_PIPE'] = env.api.file

	duration = options["--signal"]
	if duration and duration.isdigit():
		pid = os.fork()
		if pid:
			import time
			import signal
			try:
				time.sleep(int(duration))
				os.kill(pid,signal.SIGUSR1)
			except KeyboardInterrupt:
				pass
			try:
				pid,code = os.wait()
				sys.exit(code)
			except KeyboardInterrupt:
				try:
					pid,code = os.wait()
					sys.exit(code)
				except Exception:
					sys.exit(0)

	if options["--help"]:
		print(usage)
		print 'Environment values are:\n' + '\n'.join(' - %s' % _ for _ in environment.default())
		sys.exit(0)

	if options["--decode"]:
		env.log.parser = True
		env.debug.route = decode
		env.tcp.bind = ''

	if options["--profile"]:
		env.profile.enable = True
		if options["--profile"].lower() in ['1','true']:
			env.profile.file = True
		elif options["--profile"].lower() in ['0','false']:
			env.profile.file = False
		else:
			env.profile.file = options["--profile"]

	if envfile and not os.path.isfile(envfile):
		comment = 'environment file missing\ngenerate it using "exabgp --fi > %s"' % envfile
	else:
		comment = ''

	if options["--full-ini"] or options["--fi"]:
		for line in environment.iter_ini():
			print line
		sys.exit(0)

	if options["--full-env"] or options["--fe"]:
		print
		for line in environment.iter_env():
			print line
		sys.exit(0)

	if options["--diff-ini"] or options["--di"]:
		for line in environment.iter_ini(True):
			print line
		sys.exit(0)

	if options["--diff-env"] or options["--de"]:
		for line in environment.iter_env(True):
			print line
		sys.exit(0)

	if options["--once"]:
		env.tcp.once = True

	if options["--pdb"]:
		# The following may fail on old version of python (but is required for debug.py)
		os.environ['PDB'] = 'true'
		env.debug.pdb = True

	if options["--test"]:
		env.debug.selfcheck = True
		env.log.parser = True

	if options["--memory"]:
		env.debug.memory = True

	configurations = []
	# check the file only once that we have parsed all the command line options and allowed them to run
	if options["<configuration>"]:
		for f in options["<configuration>"]:
			normalised = os.path.realpath(os.path.normpath(f))
			if os.path.isfile(normalised):
				configurations.append(normalised)
				continue
			if f.startswith('etc/exabgp'):
				normalised = os.path.join(folder,f[11:])
				if os.path.isfile(normalised):
					configurations.append(normalised)
					continue

			logger.configuration('one of the arguments passed as configuration is not a file (%s)' % f,'error')
			sys.exit(1)

	else:
		print(usage)
		print 'Environment values are:\n' + '\n'.join(' - %s' % _ for _ in environment.default())
		print '\nno configuration file provided'
		sys.exit(1)

	from exabgp.bgp.message.update.attribute import Attribute
	Attribute.caching = env.cache.attributes

	if env.debug.rotate or len(configurations) == 1:
		run(env,comment,configurations)

	if not (env.log.destination in ('syslog','stdout','stderr') or env.log.destination.startswith('host:')):
		logger.configuration('can not log to files when running multiple configuration (as we fork)','error')
		sys.exit(1)

	try:
		# run each configuration in its own process
		pids = []
		for configuration in configurations:
			pid = os.fork()
			if pid == 0:
				run(env,comment,[configuration],os.getpid())
			else:
				pids.append(pid)

		# If we get a ^C / SIGTERM, ignore just continue waiting for our child process
		import signal
		signal.signal(signal.SIGINT, signal.SIG_IGN)

		# wait for the forked processes
		for pid in pids:
			os.waitpid(pid,0)
	except OSError,exc:
		logger.reactor('Can not fork, errno %d : %s' % (exc.errno,exc.strerror),'critical')
		sys.exit(1)

Example 50

Project: laikaboss
Source File: laikamilter.py
View license
    def unknown(self, cmd):
        log = self.uuid+" Unknown Callback Received: "+str(cmd)
        self.logger.writeLog(syslog.LOG_DEBUG, "%s"%(str(log)))
        return Milter.CONTINUE