本文整理汇总了Python中log函数的典型用法代码示例。如果您正苦于以下问题:Python log函数的具体用法?Python log怎么用?Python log使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了log函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __init__
def __init__(self, cleanupLeftovers = False, port = 6800, private = False):
log(DEBUG, "Starting aria process...\n");
# Start aria process
self._username = "user" + str(random.randint(0,100000)) * private
self._password = "pass" + str(random.randint(0,100000)) * private
self._proc = subprocess.Popen(["aria2c", "--enable-rpc=true", "--rpc-user="+self._username, "--rpc-passwd="+self._password, "--rpc-listen-port=%d" % port],
stdout=subprocess.PIPE)
self._server = xmlrpclib.ServerProxy('http://%s:%[email protected]:%d/rpc' % (self._username, self._password, port))
socket.setdefaulttimeout(5) # Do a quick timeout to catch problems
# wait for server to start up
running = False
while not running:
try:
self._server.aria2.tellActive()
running = True
except IOError:
time.sleep(0.2)
except xmlrpclib.ProtocolError, e:
log(ERROR, u"Couldn't connect to aria process. Is an old one still running? Aborting...\n")
raise e
示例2: test_setup
def test_setup(self):
ndb = self.ndb
# feed in machines
t1 = ndb.machines.getMachine("t1")
t4 = ndb.machines.getMachine("t4")
t5 = ndb.machines.getMachine("t5")
# set machine roles...
allroles = ndb.roles.fetchAllRows()
if not allroles:
role = ndb.roles.newRow()
role.name = "testrole"
role.is_shared=1
role.save()
allroles = [role]
for a_role in allroles:
ndb.mach_roles.addMachineRole(t1,a_role)
ndb.mach_roles.addMachineRole(t4,a_role)
ndb.mach_roles.addMachineRole(t5,a_role)
# create role triggers
cur_triggers = ndb.role_triggers.fetchRows( ('role_id', a_role.role_id) )
if not cur_triggers:
ntrigger = ndb.role_triggers.newRow()
ntrigger.role_id = a_role.role_id
serv_for_trig = ndb.services.getService("disk/size:cur")
log("serv_for_trig: %s" % serv_for_trig.serv_id)
ntrigger.serv_id = serv_for_trig.serv_id
ntrigger.level = "1"
ntrigger.source_pattern = "sda1"
ntrigger.save()
示例3: main
def main(argv, stdout, environ):
progname = argv[0]
optlist, args = getopt.getopt(argv[1:], "", ["help", "test", "debug"])
testflag = 0
if len(args) != 0:
usage(progname)
return
lock = do_lock(DISCUSS_DATA_ROOT, "archiver.lock")
global DONE
#signal.signal(signal.SIGTERM, handleSignal)
log("archiver: start")
try:
while not DONE:
try:
archive_dirs()
except:
handle_error.handleException("Archiver Error")
if DONE: break
# tlog("sleeping")
time.sleep(10)
finally:
os.unlink(os.path.join(DISCUSS_DATA_ROOT, "archiver.lock"))
示例4: stop
def stop(self):
log(DEBUG)
self._torrent.stop()
if self._aria:
self._aria.stop()
示例5: runpingweb
def runpingweb(ip=webIP): # If no IP is passed, 8.8.8.8 is used
result = pingweb(ip)
check_section(ip) # Check if IP is in the conf file, if not, add it.
status = check_option(ip,"status") # Add option if it does not exist
check_option(ip,"last-alive-time") # Add option if it does not exist
print result
if result == "0": # No connection
text = ("No connection to %s"%(ip))
if status == "connected": # Only log if previous state was "Connected"
log(text)
write_config(ip,'status', 'disconnected')
return text
elif result == "1" and status == "connected": # Connection OK
write_config(ip,"last-alive-time",dateandtime()) # Log alivetime
elif result == "1" and status != "connected":
write_config(ip, 'status', 'connected')
lastAliveStr = config.get(ip,'last-alive-time')
if lastAliveStr != "": # Time exists
lastAlive = datetime.strptime(lastAliveStr, '%Y-%m-%d %H:%M:%S')
nowtime = datetime.strptime(str(dateandtime()), '%Y-%m-%d %H:%M:%S')
alivetime_diff = nowtime - lastAlive # Calculate time since last time it was alive
text = ("Connection to %s restored after %s offline"%(ip,str(alivetime_diff)))
elif lastAliveStr == "": # No time has been recorded
text = ("First connection to IP %s"%(ip))
write_config(ip,"last-alive-time",dateandtime())
log(text)
示例6: log
def log (self, level = None, msg = None):
if msg is None:
msg = self.message
if level is None:
level = self.level
log (self.__class__.__module__, level, msg)
示例7: syncTorrents
def syncTorrents(self, force = False, downloadMode = "No"):
'''Synchronize local list with data from JSIT server: add new, remove deleted ones'''
log(DEBUG)
if self._jsit is None:
log(DEBUG, "self._jsit is None, skipping.")
return None, None
self._jsit.updateTorrents(force = force)
new, deleted = self._jsit.resetNewDeleted()
for d in deleted:
t = self.lookupTorrent(d)
if t:
# Don't do delete, as it's already gone from JSIT
# Keep deleted around for listing them as finished...
#self._torrents.remove(t)
#t.release()
pass
for n in new:
# Do we have this one already?
t = self.lookupTorrent(n)
if not t:
t = self._jsit.lookupTorrent(n)
self._torrents.append(Torrent(self, jsittorrent = t, downloadMode = downloadMode, basedir = prefDir("downloads", "basedir", "downloads")))
return new, deleted
示例8: addTorrentFiles
def addTorrentFiles(self):
log(INFO)
fns,ftype = QFileDialog.getOpenFileNames(self, "Open Torrent File", "", "Torrent Files (*.torrent)")
for fn in fns:
tor = self.mgr.addTorrentFile(fn, basedir=pref("downloads", "basedir", "downloads"),
unquoteNames=pref("downloads", "unquoteNames", True), interpretDirectories=pref("downloads", "interpretDirectories", True))
示例9: start
def start(self):
SHOULD_DISPLAY = 1
if self._israwpage:
SHOULD_DISPLAY = 0
ncgi = self.ncgi
if self.readDefaultHDF:
try:
if not self.pagename is None:
ncgi.hdf.readFile("%s.hdf" % self.pagename)
except:
log("Error reading HDF file: %s.hdf" % (self.pagename))
DISPLAY_ERROR = 0
ERROR_MESSAGE = ""
# call page main function!
try:
self.main()
except DisplayDone:
SHOULD_DISPLAY = 0
except Redirected:
# catch redirect exceptions
SHOULD_DISPLAY = 0
except DisplayError, num:
ncgi.hdf.setValue("Query.error", str(num))
if self._error_template:
ncgi.hdf.setValue("Content", self._error_template)
else:
DISPLAY_ERROR = 1
示例10: fixbody
def fixbody(raw_body):
log("-- fixbody")
# FIX #1: reassemble broken URLs
def fixurl(m):
log("matched url: %s" % m.group(0))
result = re.sub(" ?[\r\n]","",m.group(0))
log("fixed url: %s" % result)
return result
raw_body = re.sub("[a-z]+://\S+"
"("
"("
"(/ ?\r?\n(?![a-z]{0,7}://))"
"|"
"( ?\r?\n/)"
"|"
"(- ?\r?\n)"
")+"
"\S+)+"
"(?= ?\r?\n]>\\))",
fixurl,raw_body)
raw_body = re.sub("[a-z]+://\S+( ?\r?\n(?![a-z]{0,7}://)\S+)+",fixurl,raw_body)
# FIX #2: space pad URLs which are surrounded by (), <> or []
raw_body = re.sub("([<([])([a-z]+://[^ ]+)([>)\\]])","\\1 \\2 \\3",raw_body)
# FIX #3: remove Yahoo! Groups ad chunks
# done with fixes
return raw_body
示例11: data
def data(self, index, role):
if not index.isValid():
return None
tc = torrent_colums[index.column()]
if role == Qt.TextAlignmentRole:
try:
return tc["align"]
except KeyError:
return 0x82 # Qt.AlignRight | Qt.AlignVCenter doesn't work
if role == Qt.DisplayRole or role == Qt.EditRole:
v = tc["acc"](self.mgr[index.row()], tc["vname"])
if role == Qt.DisplayRole:
try:
v = tc["map"](v)
except KeyError:
pass
log(DEBUG2, "v=%s\n" % v)
return v
return None
示例12: geocode_by_semantics
def geocode_by_semantics(project, address, port):
from pymongo import MongoClient
client = MongoClient(address, port)
db = client[project]
search_json = {'$or': [{'latlng': [0, 0]}, {'latlng': [-1, -1]}], 'verified': True}
users = db.users.find(search_json)
count = db.users.find(search_json).count()
print count
i = 0
for user in users:
i += 1
verified_info = user['verified_info']
username = user['username']
verified_info = verified_info.replace(u'主持人', '').replace(u'职员', '').replace(u'院长', '').replace(u'经理', '')
verified_info = verified_info.split(u' ')[0]
if verified_info == u'前' or u'www' in verified_info or u'律师' in verified_info or u'学者' in verified_info or u'作家' in verified_info or u'媒体人' in verified_info or u'诗人' in verified_info:
verified_info = ''
locational_info = verified_info
if locational_info == '':
locational_info = username
if verified_info != '':
latlng = geocode(verified_info)
else:
continue
log(NOTICE, '#%d geocode the user by its semantic info %s. %d posts remain. latlng: %s ' % (i, verified_info.encode('gbk', 'ignore'), count - i, str(latlng)))
if latlng[0] != -1 and latlng[0] != 0:
db.users.update({'userid': user['userid']}, {'$set': {'latlng': latlng}})
log(NOTICE, "mission compeletes.")
示例13: loadMap
def loadMap(self, file, prefix, lang):
log("Loading map for language %s" % lang)
hdf = neo_util.HDF()
hdf.readFile(file)
obj = hdf.getChild(prefix)
updates = 0
new_r = 0
while obj is not None:
s_id = obj.name()
str = obj.value()
try:
map_r = self.tdb.maps.fetchRow( [('string_id', s_id), ('lang', lang)])
except odb.eNoMatchingRows:
map_r = self.tdb.maps.newRow()
map_r.string_id = s_id
map_r.lang = lang
new_r = new_r + 1
if map_r.string != str:
updates = updates + 1
map_r.string = str
map_r.save()
obj = obj.next()
log("New maps: %d Updates: %d" % (new_r, updates - new_r))
示例14: stringsHDF
def stringsHDF(self, prefix, locations, lang='en', exist=0, tiered=0):
hdf = neo_util.HDF()
if exist and lang == 'en': return hdf
done = {}
locations.sort()
maps = self.tdb.maps.fetchRows( ('lang', lang) )
maps_d = {}
for map in maps:
maps_d[int(map.string_id)] = map
strings = self.tdb.strings.fetchRows()
strings_d = {}
for string in strings:
strings_d[int(string.string_id)] = string
count = 0
for loc in locations:
s_id = int(loc.string_id)
if done.has_key(s_id): continue
try:
s_row = maps_d[s_id]
if exist: continue
except KeyError:
try:
s_row = strings_d[s_id]
except KeyError:
log("Missing string_id %d, skipping" % s_id)
continue
count = count + 1
if tiered:
hdf.setValue("%s.%d.%d.%s" % (prefix, int(s_id) / TIER1_DIV, int(s_id) / TIER2_DIV, s_id), s_row.string)
else:
hdf.setValue("%s.%s" % (prefix, s_id), s_row.string)
done[s_id] = 1
if exist == 1: log("Missing %d strings for lang %s" % (count, lang))
return hdf
示例15: __init__
def __init__(self, username, password):
log(DEBUG)
self._session = requests.Session()
# Adapter to increase retries
ad = requests.adapters.HTTPAdapter() # Older requests version don't expose the constructor arg :(
ad.max_retries=5
self._session.mount('http://', ad)
ad = requests.adapters.HTTPAdapter() # Older requests version don't expose the constructor arg :(
ad.max_retries=5
self._session.mount('https://', ad)
self._connected = False
self._api_key = None
# Torrents
self._torrentsValidUntil = 0
self._torrents = []
self._dataRemaining = 0
# General attributes
self._labelsValidUntil = 0
self._labels = []
# Torrent updates
self._newTorrents = []
self._deletedTorrents = []
# Connect already?
if username and password:
self._username = username
self._password = password
self.connect()