-
-
Notifications
You must be signed in to change notification settings - Fork 55
Move crawl and QA logs to new mongo collection #2791
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
tw4l
wants to merge
14
commits into
main
Choose a base branch
from
issue-2765-split-off-logs
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 12 commits
Commits
Show all changes
14 commits
Select commit
Hold shift + click to select a range
9b5ed06
Save crawl logs to new mongo collection
tw4l f591bfb
Add migration
tw4l d5f6c0a
Deprecate errors and behaviorLogs Crawl fields
tw4l 6febcfe
Sort logs ascending by timestamp by default
tw4l d347cfd
Migrate QA run logs
tw4l d00b078
Hardcode get_crawl_logs to only return non-QA logs for now
tw4l e17f040
Allow sorting by message
tw4l d1bedd7
Add indices and fix typing
tw4l 2099876
Ensure QA behavior logs have isQA and qaRunId set correctly
tw4l 630351b
Remove isQA from model, duplicative of qaRunId
tw4l 6912910
Remove crawl_id to crawlId
tw4l 2ebc399
Add/improve nightly tests for error and behavior log endpoints
tw4l 9a656fd
Use ascending timestamp sort order by default for consistency
tw4l 50b13df
Fix isinstance arg
tw4l File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,181 @@ | ||
| """crawl logs""" | ||
|
|
||
| from typing import TYPE_CHECKING, Any, Optional, Dict, Tuple, List | ||
|
|
||
| import json | ||
| from uuid import UUID, uuid4 | ||
|
|
||
| from fastapi import HTTPException | ||
| import pymongo | ||
|
|
||
| from .models import CrawlLogLine, Organization | ||
| from .pagination import DEFAULT_PAGE_SIZE | ||
|
|
||
| if TYPE_CHECKING: | ||
| from .orgs import OrgOps | ||
| else: | ||
| OrgOps = object | ||
|
|
||
|
|
||
| # ============================================================================ | ||
| class CrawlLogOps: | ||
| """crawl log management""" | ||
|
|
||
| org_ops: OrgOps | ||
|
|
||
| # pylint: disable=too-many-locals, too-many-arguments, invalid-name | ||
|
|
||
| def __init__(self, mdb, org_ops): | ||
| self.logs = mdb["crawl_logs"] | ||
| self.org_ops = org_ops | ||
|
|
||
| async def init_index(self): | ||
| """init index for crawl logs""" | ||
| await self.logs.create_index( | ||
| [ | ||
| ("crawlId", pymongo.HASHED), | ||
| ("oid", pymongo.ASCENDING), | ||
| ("qaRunId", pymongo.ASCENDING), | ||
| ("timestamp", pymongo.ASCENDING), | ||
| ] | ||
| ) | ||
| await self.logs.create_index( | ||
| [ | ||
| ("crawlId", pymongo.HASHED), | ||
| ("oid", pymongo.ASCENDING), | ||
| ("qaRunId", pymongo.ASCENDING), | ||
| ("logLevel", pymongo.ASCENDING), | ||
| ] | ||
| ) | ||
| await self.logs.create_index( | ||
| [ | ||
| ("crawlId", pymongo.HASHED), | ||
| ("oid", pymongo.ASCENDING), | ||
| ("qaRunId", pymongo.ASCENDING), | ||
| ("context", pymongo.ASCENDING), | ||
| ] | ||
| ) | ||
| await self.logs.create_index( | ||
| [ | ||
| ("crawlId", pymongo.HASHED), | ||
| ("oid", pymongo.ASCENDING), | ||
| ("qaRunId", pymongo.ASCENDING), | ||
| ("message", pymongo.ASCENDING), | ||
| ] | ||
| ) | ||
|
|
||
| async def add_log_line( | ||
| self, | ||
| crawl_id: str, | ||
| oid: UUID, | ||
| log_line: str, | ||
| qa_run_id: Optional[str] = None, | ||
| ) -> bool: | ||
| """add crawl log line to database""" | ||
| try: | ||
| log_dict = json.loads(log_line) | ||
|
|
||
| # Ensure details are a dictionary | ||
| # If they are a list, convert to a dict | ||
| details = None | ||
| log_dict_details = log_dict.get("details") | ||
| if log_dict_details: | ||
| if isinstance(log_dict_details, Dict): | ||
| details = log_dict_details | ||
| else: | ||
| details = {"items": log_dict_details} | ||
|
|
||
| log_to_add = CrawlLogLine( | ||
| id=uuid4(), | ||
| crawlId=crawl_id, | ||
| oid=oid, | ||
| qaRunId=qa_run_id, | ||
| timestamp=log_dict["timestamp"], | ||
| logLevel=log_dict["logLevel"], | ||
| context=log_dict["context"], | ||
| message=log_dict["message"], | ||
| details=details, | ||
| ) | ||
| res = await self.logs.insert_one(log_to_add.to_dict()) | ||
| return res is not None | ||
| # pylint: disable=broad-exception-caught | ||
| except Exception as err: | ||
| print( | ||
| f"Error adding log line for crawl {crawl_id} to database: {err}", | ||
| flush=True, | ||
| ) | ||
| return False | ||
|
|
||
| async def get_crawl_logs( | ||
| self, | ||
| org: Organization, | ||
| crawl_id: str, | ||
| page_size: int = DEFAULT_PAGE_SIZE, | ||
| page: int = 1, | ||
| sort_by: str = "timestamp", | ||
| sort_direction: int = -1, | ||
| contexts: Optional[List[str]] = None, | ||
| log_levels: Optional[List[str]] = None, | ||
| qa_run_id: Optional[str] = None, | ||
| ) -> Tuple[list[CrawlLogLine], int]: | ||
| """list all logs for particular crawl""" | ||
| # pylint: disable=too-many-locals, duplicate-code | ||
|
|
||
| # Zero-index page for query | ||
| page = page - 1 | ||
| skip = page_size * page | ||
|
|
||
| match_query: Dict[str, Any] = { | ||
| "oid": org.id, | ||
| "crawlId": crawl_id, | ||
| "qaRunId": qa_run_id, | ||
| } | ||
|
|
||
| if contexts: | ||
| match_query["context"] = {"$in": contexts} | ||
|
|
||
| if log_levels: | ||
| match_query["logLevel"] = {"$in": log_levels} | ||
|
|
||
| aggregate: List[Dict[str, Any]] = [{"$match": match_query}] | ||
|
|
||
| if sort_by: | ||
| if sort_by not in ( | ||
| "timestamp", | ||
| "logLevel", | ||
| "context", | ||
| "message", | ||
| ): | ||
| raise HTTPException(status_code=400, detail="invalid_sort_by") | ||
| if sort_direction not in (1, -1): | ||
| raise HTTPException(status_code=400, detail="invalid_sort_direction") | ||
|
|
||
| aggregate.extend([{"$sort": {sort_by: sort_direction}}]) | ||
|
|
||
| aggregate.extend( | ||
| [ | ||
| { | ||
| "$facet": { | ||
| "items": [ | ||
| {"$skip": skip}, | ||
| {"$limit": page_size}, | ||
| ], | ||
| "total": [{"$count": "count"}], | ||
| } | ||
| }, | ||
| ] | ||
| ) | ||
|
|
||
| cursor = self.logs.aggregate(aggregate) | ||
| results = await cursor.to_list(length=1) | ||
| result = results[0] | ||
| items = result["items"] | ||
|
|
||
| try: | ||
| total = int(result["total"][0]["count"]) | ||
| except (IndexError, ValueError): | ||
| total = 0 | ||
|
|
||
| log_lines = [CrawlLogLine.from_dict(res) for res in items] | ||
|
|
||
| return log_lines, total | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.