本文整理汇总了Python中raven.Client.captureMessage方法的典型用法代码示例。如果您正苦于以下问题:Python Client.captureMessage方法的具体用法?Python Client.captureMessage怎么用?Python Client.captureMessage使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类raven.Client
的用法示例。
在下文中一共展示了Client.captureMessage方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: connect_sentry
# 需要导入模块: from raven import Client [as 别名]
# 或者: from raven.Client import captureMessage [as 别名]
def connect_sentry(result):
pillar_data = __salt__['pillar.raw']()
sentry_data = {
'result': result,
'returned': ret,
'pillar': pillar_data,
'grains': __salt__['grains.items']()
}
servers = []
try:
for server in pillar_data['raven']['servers']:
servers.append(server + '/api/store/')
client = Client(
servers=servers,
public_key=pillar_data['raven']['public_key'],
secret_key=pillar_data['raven']['secret_key'],
project=pillar_data['raven']['project'],
)
except KeyError as missing_key:
logger.error("Sentry returner need config '%s' in pillar",
missing_key)
else:
try:
client.captureMessage(ret['comment'], extra=sentry_data)
except Exception as err:
logger.error("Can't send message to sentry: %s", err,
exc_info=True)
示例2: process_jobs
# 需要导入模块: from raven import Client [as 别名]
# 或者: from raven.Client import captureMessage [as 别名]
def process_jobs(self, beanstalk):
while True:
logger.debug("Beanstalk connection established, waiting for jobs")
job = beanstalk.reserve()
job_name = job.stats()["tube"]
if job_name in self.jobs:
logger.debug("Calling %s with arg: %s" % (job_name, job.body))
try:
connection = db.connections["default"]
if connection.connection:
try:
connection.connection.ping()
except OperationalError as e:
connection.close()
flush_transaction()
self.jobs[job_name](job.body)
except Exception, e:
tp, value, tb = sys.exc_info()
logger.error('Error while calling "%s" with arg "%s": ' "%s" % (job_name, job.body, e))
logger.debug("%s:%s" % (tp.__name__, value))
logger.debug("\n".join(traceback.format_tb(tb)))
client = Client(dsn=settings.RAVEN_CONFIG["dsn"])
client.captureMessage(str(e), stack=True, level=logging.ERROR)
job.bury()
else:
job.delete()
else:
job.release()
示例3: main
# 需要导入模块: from raven import Client [as 别名]
# 或者: from raven.Client import captureMessage [as 别名]
def main(self):
# consume standard input early
lines = []
p = re.compile("Subject: Cron <[^@][email protected][^ ]+> (.*)")
mail_subject = 'This mail has no subject.'
for line in sys.stdin:
line = line.rstrip()
lines.append(line)
if line.startswith('Subject:'):
mail_subject = line
# Removes hostname from cron subject to aggregate sentry events
if p.search(line):
cron_subject = p.search(line).group(1)
mail_subject = "Subject: Cron {0}".format(cron_subject)
body = os.linesep.join(lines)
if not len(body):
sys.stderr.write("Empty stdin, nothing to report")
sys.stderr.write(os.linesep)
sys.exit(1)
# init raven quickly, so if something is wrong it get logged early
from raven import Client
dsn = self.config['sentry_dsn']
if not dsn.startswith("requests+"):
dsn = "requests+" + dsn
client = Client(dsn=dsn)
if self.config['subject']:
subject = self.config['subject']
else:
subject = mail_subject
msg = os.linesep.join((subject, body))
client.captureMessage(msg, extra=os.environ)
示例4: _write_message_with_apnsclient
# 需要导入模块: from raven import Client [as 别名]
# 或者: from raven.Client import captureMessage [as 别名]
def _write_message_with_apnsclient(self, message, devices):
# start with all devices in "complete" list. remove as necessary.
# convert to list: attempting to avoid deadlock in "set_devices_last_notified_at"
complete_devices = list(devices[:])
fail_devices = []
retry_devices = []
con = self.session.get_connection(address=(self.hostname, 2195), cert_string=self.certificate, key_string=self.private_key)
srv = APNs(con)
res = srv.send(message)
# Check failures. Check codes in APNs reference docs.
for token, reason in res.failed.items():
code, errmsg = reason
# Log with sentry
client = Client(dsn=settings.RAVEN_CONFIG['dsn'])
client.captureMessage("APNs Failure - Reason:%s - Device:%s" % (errmsg, token))
# Disable device
for device in devices:
if device.token == token:
complete_devices.remove(device)
device.is_active = False
device.save()
print "Device faled: {0}, reason: {1}".format(token, errmsg)
# Check failures not related to devices.
for code, errmsg in res.errors:
# Log with sentry
client = Client(dsn=settings.RAVEN_CONFIG['dsn'])
client.captureMessage("APNs Failure - Error:%s" % errmsg)
print "Error: ", errmsg
# Check if there are tokens that can be retried
if res.needs_retry():
# repeat with retry_message
retry_message = res.retry()
# add retried devices to "retry_devices"
for token in retry_message.tokens:
for device in complete_devices:
if device.token == token:
retry_devices.append(device)
# remove retried devices from "complete_devices"
for device in retry_devices:
complete_devices.remove(device)
# retry message
self._write_message_with_apnsclient(retry_message, retry_devices)
# set date of last message for "complete_devices"
self.set_devices_last_notified_at(complete_devices)
示例5: common_except_info
# 需要导入模块: from raven import Client [as 别名]
# 或者: from raven.Client import captureMessage [as 别名]
def common_except_info(info, from_function):
"""
输出特定消息到sentry中
by: 马志 at: 2015-11-27
"""
client = Client(settings.SENTRY_CLIENT_KEY)
client.captureMessage("info:%s,from:%s" % (info, from_function))
示例6: CommandReporter
# 需要导入模块: from raven import Client [as 别名]
# 或者: from raven.Client import captureMessage [as 别名]
class CommandReporter(object):
def __init__(self, cmd, dsn):
self.dsn = dsn
self.command = cmd
self.client = None
def run(self):
start = time()
with TemporaryFile() as stdout:
with TemporaryFile() as stderr:
exit_status = call(self.command, stdout=stdout, stderr=stderr)
last_lines_stdout = self._get_last_lines(stdout)
last_lines_stderr = self._get_last_lines(stderr)
if exit_status > 0:
elapsed = int((time() - start) * 1000)
self.report_fail(exit_status, last_lines_stdout, last_lines_stderr, elapsed)
sys.stdout.write(last_lines_stdout)
sys.stderr.write(last_lines_stderr)
def report_fail(self, exit_status, last_lines_stdout, last_lines_stderr, elapsed):
if self.dsn is None:
return
message = "Command \"%s\" failed" % (self.command,)
if self.client is None:
self.client = Client(dsn=self.dsn)
self.client.captureMessage(
message,
data={
'logger': 'cron',
},
extra={
'command': self.command,
'exit_status': exit_status,
'last_lines_stdout': last_lines_stdout,
'last_lines_stderr': last_lines_stderr,
},
time_spent=elapsed
)
def _get_last_lines(self, buf):
buf.seek(0, SEEK_END)
file_size = buf.tell()
if file_size < MAX_MESSAGE_SIZE:
buf.seek(0)
last_lines = buf.read().decode('utf-8')
else:
buf.seek(-(MAX_MESSAGE_SIZE-3), SEEK_END)
last_lines = u'...' + buf.read().decode('utf-8')
return last_lines
示例7: CommandReporter
# 需要导入模块: from raven import Client [as 别名]
# 或者: from raven.Client import captureMessage [as 别名]
class CommandReporter(object):
def __init__(self, cmd, dsn, always, logger, description):
self.dsn = dsn
self.command = " ".join(cmd)
self.always = always
self.client = None
self.logger = logger
self.description = description
def run(self):
buf = TemporaryFile()
start = time()
exit_status = call(self.command, stdout=buf, stderr=buf, shell=True)
if exit_status > 0 or self.always == True:
elapsed = int((time() - start) * 1000)
self.report_fail(exit_status, buf, elapsed)
buf.close()
def report_fail(self, exit_status, buf, elapsed):
if self.dsn is None:
return
# Hack to get the file size since the tempfile doesn't exist anymore
buf.seek(0, SEEK_END)
file_size = buf.tell()
if file_size < MAX_MESSAGE_SIZE:
buf.seek(0)
last_lines = buf.read()
else:
buf.seek(-(MAX_MESSAGE_SIZE-3), SEEK_END)
last_lines = '...' + buf.read()
if self.description:
message=self.description
else:
message="Command \"%s\" failed" % (self.command,)
if self.client is None:
self.client = Client(dsn=self.dsn)
self.client.captureMessage(
message,
data={
'logger': self.logger,
},
extra={
'command': self.command,
'exit_status': exit_status,
'last_lines': last_lines,
},
time_spent=elapsed
)
示例8: activate
# 需要导入模块: from raven import Client [as 别名]
# 或者: from raven.Client import captureMessage [as 别名]
def activate(self):
"""Activates the user and logs him in."""
user = get_user_model().objects.get(pk=self.activation_key)
user.is_active = True
user.save(update_fields=['is_active'])
client = Client()
client.captureMessage("New user activated", extra={
'email': user.email
})
user.backend = 'ratelimitbackend.backends.RateLimitModelBackend'
auth_login(self.request, user)
示例9: connect_sentry
# 需要导入模块: from raven import Client [as 别名]
# 或者: from raven.Client import captureMessage [as 别名]
def connect_sentry(result):
pillar_data = __salt__['pillar.raw']()
grains = __salt__['grains.items']()
tags = {}
if 'tags' in pillar_data['raven']:
for tag in pillar_data['raven']['tags']:
tags[tag] = grains[tag]
global_extra_data = {
'pillar': pillar_data,
'grains': grains
}
global_data = {
'platform': 'python',
'level': 'error'
}
servers = []
try:
for server in pillar_data['raven']['servers']:
servers.append(server + '/api/store/')
client = Client(
servers=servers,
public_key=pillar_data['raven']['public_key'],
secret_key=pillar_data['raven']['secret_key'],
project=pillar_data['raven']['project'],
)
except KeyError as missing_key:
logger.error("Sentry returner need config '%s' in pillar",
missing_key)
else:
try:
if isinstance(result['return'], collections.Mapping):
for state, changes in result.get('return', {}).iteritems():
if changes.get('result', True):
continue
data = global_data
data['culprit'] = state.replace('_|-',' ')
extra_data = global_extra_data
extra_data['result'] = changes
client.captureMessage(message=changes.get('comment', 'No comment supplied'), data=data, extra=extra_data, tags=tags)
else:
data = global_data
data['culprit'] = result['fun']
extra_data = global_extra_data
extra_data['result'] = result
message = "\n".join(result['return'])
client.captureMessage(message=message, data=data, extra=extra_data, tags=tags)
except Exception as err:
logger.error("Can't send message to sentry: %s", err,
exc_info=True)
示例10: send_sentry
# 需要导入模块: from raven import Client [as 别名]
# 或者: from raven.Client import captureMessage [as 别名]
def send_sentry(message, result=None):
logger.trace("Sending some data to Sentry")
pillar_data = __salt__['pillar.data']()
sentry_data = {
'result': result,
'returned': ret,
'pillar': pillar_data,
'grains': __salt__['grains.items']()
}
try:
client = Client(pillar_data['sentry_dsn'])
client.captureMessage(message, extra=sentry_data)
except Exception, err:
logger.error("Can't send message '%s' extra '%s' to sentry: %s",
message, sentry_data, err)
示例11: main
# 需要导入模块: from raven import Client [as 别名]
# 或者: from raven.Client import captureMessage [as 别名]
def main():
root = logging.getLogger('sentry.errors')
root.setLevel(logging.DEBUG)
root.addHandler(logging.StreamHandler())
dsn = ' '.join(sys.argv[2:])
if not (dsn or os.environ.get('SENTRY_DSN')):
print "Error: No configuration detected!"
print "You must either pass a DSN to the command, or set the SENTRY_DSN environment variable."
sys.exit(1)
print "Using DSN configuration:"
print " ", dsn
print
client = Client(dsn)
print "Client configuration:"
for k in ('servers', 'project', 'public_key', 'secret_key'):
print ' %-15s: %s' % (k, getattr(client, k))
print
if not all([client.servers, client.project, client.public_key, client.secret_key]):
print "Error: All values must be set!"
sys.exit(1)
print 'Sending a test message...',
ident = client.get_ident(client.captureMessage('This is a test message generated using ``raven test``'))
print 'success!'
print
print 'The test message can be viewed at the following URL:'
url = client.servers[0].split('/api/store/', 1)[0]
print ' %s/%s/search/?q=%s' % (url, client.project, ident)
示例12: test_basic
# 需要导入模块: from raven import Client [as 别名]
# 或者: from raven.Client import captureMessage [as 别名]
def test_basic(self, send_remote):
send_remote.side_effect = self.sendRemote
client = Client(
dsn='http://%s:%[email protected]:8000/%s' % (
self.pk.public_key, self.pk.secret_key, self.pk.project_id)
)
with self.tasks():
client.captureMessage(message='foo')
assert send_remote.call_count is 1
assert Group.objects.count() == 1
group = Group.objects.get()
assert group.event_set.count() == 1
instance = group.event_set.get()
assert instance.data['sentry.interfaces.Message']['message'] == 'foo'
示例13: main
# 需要导入模块: from raven import Client [as 别名]
# 或者: from raven.Client import captureMessage [as 别名]
def main():
root = logging.getLogger('sentry.errors')
root.setLevel(logging.DEBUG)
root.addHandler(logging.StreamHandler())
parser = OptionParser()
parser.add_option("--data", action="callback", callback=store_json,
type="string", nargs=1, dest="data")
(opts, args) = parser.parse_args()
dsn = ' '.join(args[1:]) or os.environ.get('SENTRY_DSN')
if not dsn:
print "Error: No configuration detected!"
print "You must either pass a DSN to the command, or set the SENTRY_DSN environment variable."
sys.exit(1)
print "Using DSN configuration:"
print " ", dsn
print
client = Client(dsn, include_paths=['raven'])
print "Client configuration:"
for k in ('servers', 'project', 'public_key', 'secret_key'):
print ' %-15s: %s' % (k, getattr(client, k))
print
if not all([client.servers, client.project, client.public_key, client.secret_key]):
print "Error: All values must be set!"
sys.exit(1)
print 'Sending a test message...',
ident = client.get_ident(client.captureMessage(
message='This is a test message generated using ``raven test``',
data=opts.data or {
'culprit': 'raven.scripts.runner',
'logger': 'raven.test',
'sentry.interfaces.Http': {
'method': 'GET',
'url': 'http://example.com',
}
},
level=logging.INFO,
stack=True,
extra={
'user': pwd.getpwuid(os.geteuid())[0],
'loadavg': os.getloadavg(),
}
))
if client.state.did_fail():
print 'error!'
return False
print 'success!'
print
print 'The test message can be viewed at the following URL:'
url = client.servers[0].split('/api/store/', 1)[0]
print ' %s/%s/search/?q=%s' % (url, client.project, ident)
示例14: report_fail
# 需要导入模块: from raven import Client [as 别名]
# 或者: from raven.Client import captureMessage [as 别名]
def report_fail(self, exit_status, last_lines_stdout, last_lines_stderr, elapsed):
if self.dsn is None:
return
message = 'Command "%s" failed' % (self.command,)
client = Client(dsn=self.dsn, string_max_length=-1)
client.captureMessage(
message,
data={"logger": "cron"},
extra={
"command": self.command,
"exit_status": exit_status,
"last_lines_stdout": last_lines_stdout,
"last_lines_stderr": last_lines_stderr,
},
time_spent=elapsed,
)
示例15: main
# 需要导入模块: from raven import Client [as 别名]
# 或者: from raven.Client import captureMessage [as 别名]
def main():
root = logging.getLogger("sentry.errors")
root.setLevel(logging.DEBUG)
root.addHandler(logging.StreamHandler())
parser = OptionParser()
parser.add_option("--data", action="callback", callback=store_json, type="string", nargs=1, dest="data")
(opts, args) = parser.parse_args()
dsn = " ".join(args[1:]) or os.environ.get("SENTRY_DSN")
if not dsn:
print("Error: No configuration detected!")
print("You must either pass a DSN to the command, or set the SENTRY_DSN environment variable.")
sys.exit(1)
print("Using DSN configuration:")
print(" ", dsn)
print()
client = Client(dsn, include_paths=["raven"])
print("Client configuration:")
for k in ("servers", "project", "public_key", "secret_key"):
print(" %-15s: %s" % (k, getattr(client, k)))
print()
if not all([client.servers, client.project, client.public_key, client.secret_key]):
print("Error: All values must be set!")
sys.exit(1)
print("Sending a test message...", end=" ")
ident = client.get_ident(
client.captureMessage(
message="This is a test message generated using ``raven test``",
data=opts.data
or {
"culprit": "raven.scripts.runner",
"logger": "raven.test",
"sentry.interfaces.Http": {"method": "GET", "url": "http://example.com"},
},
level=logging.INFO,
stack=True,
extra={"user": pwd.getpwuid(os.geteuid())[0], "loadavg": os.getloadavg()},
)
)
if client.state.did_fail():
print("error!")
return False
print("success!")
print()
print("The test message can be viewed at the following URL:")
url = client.servers[0].split("/api/store/", 1)[0]
print(" %s/%s/search/?q=%s" % (url, client.project, ident))