def save_message(self, message_body: dict, result: EventResult, started: datetime, finished: datetime): try: message = Message( msg_id=message_body.get('message_id'), env=self.env_name, source=self.SOURCE_SYSTEM, object_id=result.related_object, display_context=result.display_context, level=message_body.get('priority'), msg=message_body, ts=message_body.get('timestamp'), received_ts=started, finished_ts=finished ) self.inv.collections['messages'].insert_one(message.get()) return True except Exception as e: self.inv.log.error("Failed to save message") self.inv.log.exception(e) return False
def emit(self, record): # Try to invoke InventoryMgr for logging if not self.inv: try: self.inv = InventoryMgr() except: return # make sure we do not try to log to DB when DB is not ready if not (self.inv.is_db_ready() and 'messages' in self.inv.collections): return # make ID from current timestamp now = datetime.datetime.utcnow() d = now - datetime.datetime(1970, 1, 1) timestamp_id = '{}.{}.{}'.format(d.days, d.seconds, d.microseconds) source = self.SOURCE_SYSTEM message = Message(msg_id=timestamp_id, env=self.env, source=source, msg=Logger.formatter.format(record), ts=now, level=record.levelname) if self.origin: message.extra['origin_id'] = ( str(self.origin.origin_id) if self.origin.origin_id else None ) message.extra['origin_type'] = ( self.origin.origin_type.value if self.origin.origin_type else None ) for extra_field in self.origin.extra: message.extra[extra_field] = getattr(self.origin, extra_field) self.inv.collections['messages'].insert_one(message.get())
def keep_message(self, doc, check_result, error_level=None): is_link = 'link_type' in doc msg_id = check_result['id'] obj_id = 'link_{}_{}'.format(doc['source_id'], doc['target_id']) \ if is_link \ else doc['id'] obj_type = 'link_{}'.format( doc['link_type']) if is_link else doc['type'] display_context = obj_id if is_link \ else doc['network_id'] if doc['type'] == 'port' else doc['id'] level = error_level if error_level\ else ERROR_LEVEL[check_result['status']] dt = datetime.datetime.utcfromtimestamp(check_result['executed']) message = Message(msg_id=msg_id, env=self.env, source=SOURCE_SYSTEM, object_id=obj_id, object_type=obj_type, display_context=display_context, level=level, msg=check_result, ts=dt) collection = self.inv.collections['messages'] collection.insert_one(message.get())